Dor Lugasi-Gal
Dor Lugasi-Gal

Reputation: 1572

python 2.7 Client Server UDP communication, how to overcome packet loss?

I have a UDP communication between a server and client on localhost according to this code: https://pymotw.com/2/socket/udp.html

Echo Server:

import socket
import sys

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

server_address = ('127.0.0.1', 12321)
sock.bind(server_address)

while True:
    data, address = sock.recvfrom(4096)

    if data:
        sent = sock.sendto(data, address)

echo Client

import socket
import sys

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

server_address = ('127.0.0.1', 12321)
message = 'This is the message.  It will be repeated.'

try:
    for i in range 4:
        sent = sock.sendto(message, server_address)    
        data, server = sock.recvfrom(4096)

finally:
    sock.close()

now let's say I got some MITM attack, and a specific packet doesn't arrive at the server, and the client is still waiting for a response from the server,

I get a deadlock.

how can I overcome this? is there some timeout parameter for UDP socket?

Upvotes: 0

Views: 1238

Answers (1)

Bruno Rijsman
Bruno Rijsman

Reputation: 3807

Yes, there is a timeout for UDP sockets. See socket.settimeout() in https://docs.python.org/2/library/socket.html and read up on non-blocking sockets in general.

Note that UDP packets can be dropped, duplicated, and/or re-ordered, even if there is no man-in-the-middle attacker. This is because UDP is (by design) an unreliable datagram protocol.

If you need a reliable protocol use TCP (or QUIC).

If you need assurance that no man-in-the-middle can modify or (optionally) observe the data, use TLS (or QUIC).

Upvotes: 1

Related Questions