Reputation: 13120
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?
Upvotes: 7
Views: 3424
Reputation: 47
Upon successful completion, sendto() shall return the number of bytes sent. Otherwise, -1 shall be returned and errno set to indicate the error.
@source: https://pubs.opengroup.org/onlinepubs/009695399/functions/sendto.html
custom this function as you want!
def send_my_request():
try:
#Your request Code
re = sendsock.sendto(str2bytes, ("%s" % phone.ip_addr, int(phone.sip_port)))
if re >= 0:
#Success
return True;
except:
# Handler your error
return False;
return False;
Upvotes: 0
Reputation: 38233
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.
Upvotes: 2