How do I know which servers are waiting for connection on my network?

2

I'm developing a multiplayer (LAN) game with Sockets in JAVA. Players will start a lobby, and in that lobby there will be a list of servers (game rooms) waiting for connections.

How can I list the servers on my network so players can connect?

    
asked by anonymous 28.09.2015 / 20:02

3 answers

1

Good evening, John

The way to do this might be by trying connections to the servers in your IP range on the chosen port. I do not recommend that you adopt this idea because you would need to know the machine's IPs (one machine can respond to multiple IP's), the bandwidth within the network mask they use, and iterate over a huge amount of IP's to get this list. You would try the connection and if there is a "Connection Refused" it means that the other machine is not expecting to receive anything on that port.

A more interesting way would be for one of the servers to centralize the list with the IP / hostnames of the other game servers. Whenever a game server started it would send a message to the centralizing server informing its current IP.

All lobbys would then always ask this centralizing server which game servers there are and are active, get the IP and then connect to the game.

With this technique you request the requests in a colossal way and establish a simple process to determine which IP to connect to.

    
01.10.2015 / 03:13
1

I was able to resolve my issue by making some edits to a example that I used as a basis.

Code:

public void checkHosts(String subnet) throws IOException {
    for (int i = 1; i < 255; i++) {
        String host = subnet + "." + i;

        SocketAddress sockaddr = new InetSocketAddress(host, 3128);
        Socket socket = new Socket();
        boolean connected = false;

        try {
            socket.connect(sockaddr, timeout);
            connected = true;
        } catch (SocketTimeoutException ex) {
            System.out.println(host + " isn't reachable");
        } catch (ConnectException ex) {
            System.out.println(host + " is reachable, but hasn't server on port 3128");
        }

        if (connected) {
            System.out.println(host + " has a server on port 3128!!!");
        }

        socket.close();
    }
}
    
01.10.2015 / 16:07
0

You can try to list the IP of the servers in this lobby. To get IP from a server you can use the following function:

public String getIp() {

  InetAddress ip;

  try {

    ip = InetAddress.getLocalHost();

    return ip.getHostAddress();

  } catch(UnknownHostException ex) {}

  return "IP não encontrado!";

}

Try to pass this string from the server to the lobby every time a new server is created. And when it's closed, you have to remember to take the IP from the lobby as well.

I hope I have helped!

    
01.10.2015 / 01:20