简体   繁体   English

Python udp socket.recv将从哪个数据包接收?

[英]Python udp socket.recvfrom what packets will this receive?

I just started working with udp in python, and came up with the following client for talking back and forth with the server I'm writing. 我刚刚开始在python中使用udp,并想出了以下客户端来与正在编写的服务器进行来回通信。 My question is about the recvfrom call. 我的问题是关于recvfrom呼叫。 What packets will it receive? 它会收到什么数据包? Will it get any packets or is there some registration that happens that says I want the results from the thing I sent to? 它会收到任何数据包,还是会发生一些注册,说我想要发送给我的东西的结果? I'm more curious about it at lower level, like what syscalls are being made. 我对较低级别的功能更感兴趣,例如正在执行什么系统调用。

#!/usr/bin/python3
# shell.py
#
# Usage:
#
#       ./shell.py <IP_ADDR> <PORT>


import sys
import socket

SERVER_IP = sys.argv[1]
SERVER_PORT = int(sys.argv[2])
MAX_MESSAGE_LEN = 4096

# set up the right socket type

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
target = (SERVER_IP, SERVER_PORT)

try:
    while True:
        data = input("> ")
        sent = sock.sendto(data.encode('utf-8'), target)

        data, server = sock.recvfrom(MAX_MESSAGE_LEN)

        print(repr(server))
        print("Got {}".format(data))
finally:
    print("Closing socket")
    sock.close()

socket.recvfrom is implemented in C here: socket.recvfrom在C中实现:

https://github.com/python/cpython/blob/master/Modules/socketmodule.c#L3525 https://github.com/python/cpython/blob/master/Modules/socketmodule.c#L3525

if you want to know exactly what it is doing. 如果您想确切知道它在做什么。

To answer the other part of your question, UDP is connectionless, so there is no handshaking or registration involved. 要回答问题的另一部分,UDP是无连接的,因此不涉及握手或注册。 It will read any data you send to that port. 它将读取您发送到该端口的所有数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM