简体   繁体   中英

Java Lan Game list Ip addresses of Running Server

We are currently working on a client-server game in java. We used DatagramSocket to perform communications between client and server. Inorder for the client to communicate to server, he must know the LAN ip address of the machine where the server is running. Multiple clients can connect to server, we used a thread for each client.

Our problem is we wanted to show a list of LAN ip addresses of running servers to the clients so that it is easier for them to find servers like slist command in Counter Strike. Our solution is the client sends a message to all computers connected to the network and if a computer with a running server receives it, it will reply a message back to the client and then we print it's ip address in the client.

InetAddress localHost = Inet4Address.getLocalHost();
String myIP=localHost.toString().substring(localHost.toString().lastIndexOf("/")+1);

//split myIP into 4 parts (part1.part2.part3.part4)
//use the first part to check the class of the network (A, B, or C)

//I'll skip to C
if(part1>=1 && part1<=126) //A
else if(part1>=128 && part1<=191) //B
else if(part1>=192 && part1<=223){
    String network= part1 + "." + part2 + "." part3;
    String guess;
    for(i=0;i<255;i++){
         guess = network+"."+i;
         serverSend(guess); //send the message to an ip address in the network
    }
}

It works fine for network in class C but for B and A, it is too slow. We assume the worst-case subnet mask for B and A which is 255.255.0.0 (65,025 iterations) and 255.0.0.0 (16,581,375).

Does anyone got a better solution to this? thank you in advance.

what you are looking for is broadcast.

I have gathered a tutorial for you: http://download.oracle.com/javase/tutorial/networking/datagrams/broadcasting.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM