Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 - verify sendto() Success

I have 2 UDP responses to a destination ip, one right after the other:

sendsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sendsock.bind(('%s' % ip_adr, 1036))

#send first packet
ok_response = "Reception Success, more to come"
str2bytes = bytes(ok_response,'utf-8')
sendsock.sendto(str2bytes, ("%s" % phone.ip_addr, int(phone.sip_port)))

#send second packet
ok_response = "Fun data here"
str2bytes = bytes(ok_response,'utf-8')
sendsock.sendto(str2bytes, ("%s" % phone.ip_addr, int(phone.sip_port)))

I can see with Wireshark the second packet gets sent. But the first seems be ignored.

Unless someone can see a hiccup in my code, is there a way to do an if statement on each sendsock.sendto() instance, to ensure the code doesn't continue until it's acknowledged as sent?

Also, should I be closing the sendsock?

like image 308
coffeemonitor Avatar asked Dec 21 '12 17:12

coffeemonitor


1 Answers

There is no guarantee with UDP that the messages will arrive synchronously or that they will even arrive at all, so it's never actually acknowledged as sent unless you send an acknowledgement response back from the receiver program. That is the tradeoff that improves the speed of UDP versus TCP.

You could, however, check the return value of sendto (number of bytes sent) in a while loop and not exit the while loop until the bytes sent matches the bytes of the original message or a timeout value is reached.

Also, it might be easier to use the socketserver module to simplify the process of handling your sockets.

like image 200
Alex W Avatar answered Oct 01 '22 22:10

Alex W