I am working on a multiplayer game in python that uses the socket library for its networking. The game will support play over LAN. One player will set up the server and other players on the LAN will be able to join the game.
To implement this, I need a simple way for the players to discover a list of available servers (players shouldn't be expected to have to enter IP addresses!). My preferred solution would use only the python socket library (and optionally other parts of the standard library).
What I am looking for is client and server code:
client: broadcasts its request for games to all machines listening on a certain port on the LAN
server(s): replies to the client with its availability
ATTEMPTED ANSWER Following Hans' advice in his answer below, a UDP socket can be used to respond broadcast requests from the client.
Server:
#UDP server responds to broadcast packets
#you can have more than one instance of these running
import socket
address = ('', 54545)
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
server_socket.bind(address)
while True:
print "Listening"
recv_data, addr = server_socket.recvfrom(2048)
print addr,':',recv_data
server_socket.sendto("*"+recv_data, addr)
Client:
#UDP client broadcasts to server(s)
import socket
address = ('<broadcast>', 54545)
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
data = "Request"
client_socket.sendto(data, address)
while True:
recv_data, addr = client_socket.recvfrom(2048)
print addr,recv_data
Are there other compelling ways to handle this discoverability problem?