...
/Improvements to UDP Programs: Avoiding Arbitrary Servers
Improvements to UDP Programs: Avoiding Arbitrary Servers
There are a few improvements that can easily be made to our UDP program. Let's have a look.
We'll cover the following...
Problem: Replies From Arbitrary Servers
Note that at the moment, our UDP client accepts replies from any machine and assumes that it’s the one that it sent the initial message to, evident in the following line,
data, address = s.recvfrom(MAX_SIZE_BYTES)
Note how the client does not check who it is receiving the message from. It just receives a message.
Fix with connect()
There are two quick ways to go about fixing this. The first of which is to use the connect()
method to forbid other addresses from sending packets to the client.
Press + to interact
import socketMAX_SIZE_BYTES = 65535 # Mazimum size of a UDP datagramdef client(port):host = '127.0.0.1's = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)s.connect((host, port))message = input('Input lowercase sentence:' )data = message.encode('ascii')s.send(data)print('The OS assigned the address {} to me'.format(s.getsockname()))data = s.recv(MAX_SIZE_BYTES)text = data.decode('ascii')print('The server replied with {!r}'.format(text))
With ...