6

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?

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
coffeemonitor
  • 12,780
  • 34
  • 99
  • 149
  • thanks Lev. how do you apply syntax highlighting to python? – coffeemonitor Dec 21 '12 at 18:01
  • @lev added the main `python` tag to your Q, so it will highlight using that (Python 2.x Python 3.x etc... tags don't do that) - otherwise, just manually put in a `` before the code block (or just at the top of your post to make it a default) – Jon Clements Dec 21 '12 at 18:08
  • Much clearer thanks Jon. – coffeemonitor Dec 21 '12 at 18:10
  • @coffeemonitor What you did wrong initially was indent the magic comment, so it was interpreted as part of the code. Otherwise it'd have worked just fine. – Lev Levitsky Dec 21 '12 at 18:16
  • From the [socket module](http://docs.python.org/dev/library/socket.html#socket.socket.sendto) documentation, the return of sendto is the number of bytes sent. Did you check the return value ? – Scharron Dec 21 '12 at 20:16

1 Answers1

2

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.

Alex W
  • 37,233
  • 13
  • 109
  • 109