rul3s
rul3s

Reputation: 342

Wait X seconds to recieve a UDP packet Python

I'm doing a client in Python, who registers into a server. That client sends a UDP packet to register and waits for a register accepted response packet from server.

There's the possibility that some packets are lost, because it's UDP, so I need code to:

Send packet and wait 5 second for response, if no packet received, send again the packet and then wait 10 seconds, if already no response, now 15 seconds and if again no response, break the loop.

My problem is that to receive packet I'm doing:

skt1.sendto(pqtUdp,(srvAdr,prtUdp))
data,addrs = skt1.recvfrom(56)

And rcvfrom is a blocking method. I searched and I think that using select I could know when I receive a packet to then read the socket and get it, but I have no idea how to do it, I don't find select easy examples for what I'm doing.

Could someone give me some help please?

Thanks!

Upvotes: 0

Views: 2993

Answers (2)

domorecalculus
domorecalculus

Reputation: 36

If you set the socket to non-blocking you can easily achieve this. After you declare the socket do:

skt1.setblocking(0)

By doing this if recvfrom() doesn't receive a packet it will raise an error which you can handle and move on from, like so:

try:
    skt1.recvfrom(64)
except socket.error:
    pass

Upvotes: 0

barrios
barrios

Reputation: 1124

This is an easy task with scapy:

>>> sr(IP(dst="172.20.29.5/30")/UDP(dport=[21,22,23]),inter=5,retry=2,timeout=1)

sr is the sendreceice function, you can specify a wait-interval with inter and the number of retries & timeout.

Upvotes: 1

Related Questions