3

我在使用带有 Python 的 UDP 套接字发送和接收消息时遇到问题。

问题是当我尝试使用此代码发送和接收消息时,我没有收到任何内容:Receiver.py:

import socket

UDP_IP = "127.0.0.1"
UDP_PORT = 55681
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))
while True:
     data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print "received message:", data

发件人.py:

import socket

UDP_IP = "192.168.1.161"
UDP_PORT = 55681
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.bind((UDP_IP, UDP_PORT))
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))

但是,如果我通过以下方式更改接收器的代码:

import socket

UDP_IP = "192.168.1.161"
UDP_PORT = 55681

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

它完美地工作。如果我将 127.0.0.1 作为两个程序中的地址也是同样的情况。为什么?

我使用 python 2.7 在 linux 上工作,这是 ifconfig 的结果:

lo        Link encap:Local Loopback  
      inet addr:127.0.0.1  Mask:255.0.0.0
      inet6 addr: ::1/128 Scope:Host
      UP LOOPBACK RUNNING  MTU:16436  Metric:1
      RX packets:12252 errors:0 dropped:0 overruns:0 frame:0
      TX packets:12252 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:0 
      RX bytes:1528301 (1.5 MB)  TX bytes:1528301 (1.5 MB)

wlan0     Link encap:Ethernet  HWaddr 00:21:6a:5b:b4:dc  
      inet addr:192.168.1.161  Bcast:192.168.1.255  Mask:255.255.255.0
      inet6 addr: XXXX::XXX:XXXX:XXXX:XXXX/64 Scope:Link
      UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
      RX packets:532561 errors:0 dropped:0 overruns:0 frame:0
      TX packets:318747 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1000 
      RX bytes:629969205 (629.9 MB)  TX bytes:32669218 (32.6 MB)

提前感谢您的回答。

4

1 回答 1

7

当您在接收器中执行此行时:

sock.bind((UDP_IP, UDP_PORT))

您仅绑定到UDP_IP. 因此,您的套接字将只接收发送到该地址的数据包。这就是当您匹配发件人和收件人的地址时它起作用的原因。

If you want to receive packets on any address, bind like this instead:

sock.bind(('', UDP_PORT))

As documented, specifying '' makes bind bind to all available addresses.

于 2013-03-30T19:31:15.700 回答