Foundations of Python Network Programming

(WallPaper) #1
Chapter 2 ■ UDp

35

def server(interface, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((interface, port))
print('Listening for datagrams at {}'.format(sock.getsockname()))
while True:
data, address = sock.recvfrom(BUFSIZE)
text = data.decode('ascii')
print('The client at {} says: {!r}'.format(address, text))


def client(network, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
text = 'Broadcast datagram!'
sock.sendto(text.encode('ascii'), (network, port))


if name == 'main':
choices = {'client': client, 'server': server}
parser = argparse.ArgumentParser(description='Send, receive UDP broadcast')
parser.add_argument('role', choices=choices, help='which role to take')
parser.add_argument('host', help='interface the server listens at;'
' network the client sends to')
parser.add_argument('-p', metavar='port', type=int, default=1060,
help='UDP port (default 1060)')
args = parser.parse_args()
function = choices[args.role]
function(args.host, args.p)


When trying this server and client, the first thing you should notice is they behave exactly like a normal client
and server if you simply use the client to send packets that are addressed to the IP address of a particular server.
Turning on broadcast for a UDP socket does not disable or change its normal ability to send and receive specifically
addressed packets.
The magic happens when you view the settings for your local network and use its IP “broadcast address”
as the destination for the client. First bring up one or two servers on your network, using commands like
the following:


$ python udp_broadcast.py server ""
Listening for broadcasts at ('0.0.0.0', 1060)


Then, while those servers are running, first use the client to send messages to each server. You will see that only
one server gets each message.


$ python udp_broadcast.py client 192.168.5.10

Free download pdf