I have a client server architecture in Java where a server listens using a fixed port. The client can connect using the server ip address but I would like to scan the network using the port so that user don't have to deal with server's ip address. Currently I achieve this by looking at client's ip and looping into each possible address using client's ip (192.168.1.0 - I loop through 1-255 for the last part). This method works but is there a better way to do this in java?
for (int a = 0; a < 256; a++) {
try {
String ServerIp = clientIpLast3Parts + "." + a;
InetAddress IPAddress = InetAddress.getByName(ServerIp);
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, PORT);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(
receiveData, receiveData.length);
clientSocket.receive(receivePacket);
InetAddress ServerIp = receivePacket.getAddress();
String modifiedSentence = new String(receivePacket.getData());
ip = ServerIp.getHostAddress().toString();
if (modifiedSentence != null) {
//Got it
break;
}
} catch (Exception e1) {
}
If you need automatically re-configurable topology, I'd recommend to use multicast notification. Server sends a periodical multicast packet with its unicast IP and port specified. Any client listens to that multicast group when starting until a packet with server IP/port received. Or use DNS :)
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.