10

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?

dlm
  • 4,054
  • 2
  • 23
  • 19
  • 1
    You should be asking for help with code not strategy - you could probably hang around a chat room to get this question answered – PyNEwbie Aug 06 '13 at 12:35

1 Answers1

6

You could try a UDP broadcast. You can e.g. send a broadcast from the client. The server should then broadcast a response with its address so the client can use a regular connection.

See here for some example code: http://wiki.python.org/moin/UdpCommunication

Hans Then
  • 10,935
  • 3
  • 32
  • 51
  • Thanks for the answer. Are you suggesting iterating over 192.168.0.x for x in range(1,256) and trying a UDP connection on the specific port for each? The specific example at the wiki assumes the server is local host. – dlm Aug 06 '13 at 13:41
  • A broadcast will be sent to each address in range, so there is no need to iterate. – Hans Then Aug 07 '13 at 08:01
  • In the sample, you need to make the server respond to the client. This can be done by reversing the broadcast (Have the server send a response UDP broadcast. Make the client open a UDP listener and wait for the response) – Hans Then Aug 07 '13 at 08:05