How to make a server discoverable to LAN clients
Asked Answered
O

1

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?

Octonary answered 6/8, 2013 at 12:24 Comment(1)
You should be asking for help with code not strategy - you could probably hang around a chat room to get this question answeredTasso
C
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

Cess answered 6/8, 2013 at 12:58 Comment(3)
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.Octonary
A broadcast will be sent to each address in range, so there is no need to iterate.Cess
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)Cess

© 2022 - 2024 — McMap. All rights reserved.