recvfrom返回的地址的第二部分是什么?
我正在使用 http://wiki.python.org/moin/UdpCommunication
服务器:
import socket
UDP_IP="127.0.0.1"
UDP_PORT=5005
sock = socket.socket( socket.AF_INET, # Internet
socket.SOCK_DGRAM ) # UDP
sock.bind( (UDP_IP,UDP_PORT) )
while True:
data, addr = sock.recvfrom( 1024 ) # buffer size is 1024 bytes
print "received message:", data,"from", addr
客户端:
import socket
UDP_IP="127.0.0.1"
UDP_PORT=5005
MESSAGE="Hello, World!"
print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
print "message:", MESSAGE
sock = socket.socket( socket.AF_INET, # Internet
socket.SOCK_DGRAM ) # UDP
sock.sendto( MESSAGE, (UDP_IP, UDP_PORT) )
在服务器中,我修改了最后一行:
print "received message:", data,"from", addr
因此它打印了发送消息的地址。 在我的 MacBook 上,端口似乎是 40000 或 65000 之间的某个随机数(我只是确定它看起来是随机的)。
知道这可能是什么吗?
I'm using those 2 pieces of code from http://wiki.python.org/moin/UdpCommunication
The server:
import socket
UDP_IP="127.0.0.1"
UDP_PORT=5005
sock = socket.socket( socket.AF_INET, # Internet
socket.SOCK_DGRAM ) # UDP
sock.bind( (UDP_IP,UDP_PORT) )
while True:
data, addr = sock.recvfrom( 1024 ) # buffer size is 1024 bytes
print "received message:", data,"from", addr
The client:
import socket
UDP_IP="127.0.0.1"
UDP_PORT=5005
MESSAGE="Hello, World!"
print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
print "message:", MESSAGE
sock = socket.socket( socket.AF_INET, # Internet
socket.SOCK_DGRAM ) # UDP
sock.sendto( MESSAGE, (UDP_IP, UDP_PORT) )
In the server, I modified the last line:
print "received message:", data,"from", addr
so it prints the address that the message was sent from.
On my macbook the port seems to be some random number between 40000 or 65000 (i'm just sure it seems random).
Any idea what this could be ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它是客户端用来向服务器发送数据的临时端口。
It's an ephemeral port used by the client to send data to the server.
毫无疑问是港口。您可以使用
print sock.getsockname()
在发送方验证它。您也可以在
sock.sendto()
行之前故意设置它,例如sock.bind(('', 54312))
。这在软件检查发送者的端口范围的情况下可能很有用:端口 0..1023 是特权端口 - 在许多操作系统下,仅允许
root
绑定到这些端口。然而,在大多数情况下,更改它是没有意义的,因此最好保持原样。
该端口的含义是标识连接或连接的对应项的元组的第四个元素。元组为(source_ip、source_port、destination_ip、destination_port)。
It definitely is the port. You can verify it on the sender side with
print sock.getsockname()
.You can as well set it deliberately with e. g.
sock.bind(('', 54312))
before thesock.sendto()
line.This could be useful in context where software checks the port range of the sender: Ports 0..1023 are privileged ports - under many OSes only
root
is allowed to bind to these ports.However, in the very most cases there is no point in changing it, so it mostly is better to leave it set the way it is.
This port has the meaning to be the 4th element of the tuple identifying a connection or counterpart of a connection. The tuple is (source_ip, source_port, destination_ip, destination_port).