简体   繁体   中英

UDP Connect Cause Socket To Lose Packets?

I was debugging a python program, the application can't receive udp packets as expected. Finally I found it was the UdpSocket.connect cause the UdpSocket to lose these packets. See below code:

  def main:
      sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
      sock.connect((server_ip, 9))     #This results in the issue
                                       #Use sock.bind((local_ip, 12345)) 
                                       #instead would solve the problem

      localip, localport = sock.getsockname()
      packet = GetRegisterData(localip, localport)

      sock.sendto(packet, (server_ip, 5000))   #the host (server_ip, 5000) will 
                                               #always send back two udp packets 
                                               #to respond this statement

      sleep(1)
      while True:
          response = sock.recv(1024)   #packets from (server_ip, 5000) reached
                                       #machine but this statement never return 

          if not len(response) 
              break

          print response

I am very new to Python, and don't understand why this would happen. Any body helps explain this?

[Update]
I use tcpdump to capture packets, only to find the lost packets have reached the machine, but due to unkown reason the sock.recv just doesn't retuern. I want somebody to help explain why the sock.recv doesn't return everytime here.

You didn't mention where the packets that you expect to receive (but fail to) are coming from. I'm guessing they're not coming from the address you connected to, though. See the man page for connect(2) - which is what you're calling when you use this Python API - for information about why this matters. In particular:

If the socket sockfd is of type SOCK_DGRAM then addr is the address to which datagrams are sent by default, and the only address from which datagrams are received .

(emphasis mine).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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