Example Java code to find a service running on a LAN by using UDP broadcasts. The purpose is to "discover" a host for a particular service without entering the server's name or IP address on the client.
DiscoveryServer
- runs on the server machine to receive and respond to discovery requestsDiscoveryClient
- run on client to get server's IP addressDiscoveryConfig
- constants used by both client and server
- After cloning the project, check
DISCOVERY_PORT
inserver/DiscoveryConfig.java
. Use any available port above 1024. - Run the DiscoveryServer on one machine.
- On a different machine on the same LAN run DiscoveryClient. It should print the server's address. It sends a broadcast every 2 seconds until a response is received. You can run server and client on the same machine, too.
Both client and server print several log messages on the console. You can reconfigure the Logger (java.util.logging.Logger
) to either print messages to a file or not log anything.
Example Server Output
2017-05-13 14:37:07 DiscoveryServer INFO My IP Address 10.2.23.174
Server listening on port 8888
2017-05-13 14:37:22 DiscoveryServer INFO Packet received from 10.2.23.111:58852
Example Client Output
2017-05-13 14:37:22 DiscoveryClient INFO Sent packet to 255.255.255.255:8888
2017-05-13 14:37:22 DiscoveryClient INFO Received reply from 10.2.23.174
2017-05-13 14:37:22 DiscoveryClient INFO Reply data: FOO_SERVER_IP 10.2.23.174
- If the client and server are on different LAN or VLAN then the broadcasts won't be forwarded by an intervening router.
- If client and server are on a WiFi network with "WiFi Isolation" enabled, the router won't allow direct communication between them.
- If client or server have more than one IP address, the broadcast might not be sent on the logical network that the server is listening on. This can be fixed by sending broadcasts on all IP addresses (excluding loopback and other special addresses).
The DiscoveryClient returns the address of the first server that responds. If there may be more than one server, then the client should wait a bit to give all servers a chance to respond and return a List of all responses, instead of just one.
- Network Discovery using UDP Broadcast by De Mey.
- Writing a Datagram Client and Server in the Java Tutorial.