What I am trying to do is discover servers on the same subnet.
I believe that multicast UDP is the standard sort of way for solving this problem. (At least that's what I've done before, and IIRC it's what JINI service discovery is based on). It's really simple (and fast). Your server just broadcasts a small id-string on a pre-determined multicast group on a periodic basis (i.e. once every 250ms). Clients join the group and listen for a second or so to pick up any id-strings being broadcasted. That's it.
Actually with Jini it's more the other way around. The client sends a multicast request for the next lookup service, with it's ip address in the source address field. The lookup services (the servers) are listening for these requests and will send back a unicast answer.
The 255.255.255.255 isn't a multicast, but a global broadcast. You can send and receive broadcasts by setting the broadcast property on a DatagramSocket.
Using the global broadcast address usally works but is regarded as BadStyleTM
The real broadcast adress is the highest address of your subnet. So the actual value depends on you netmask. For a class C net, having a netmask of 255.255.255.0, the broadcast address is x.x.x.255. The host part of their address is: Addresses in this subnet minus one. (256 -1).
A net with a netmask of 255.255.255.224 (only the last five bits of the ip address are host adresses) uses a broadcast address of (x.x.x.x & 255.255.255.224) + 31.
The differences between broadcasts and multicasts are:
- Broadcasts will not be routed. They are restricted to one subnet. Multicasts can be routed if the router is configured to do so.
- Broadcast are read by every network card. To receive a multicast packet you will have to join the corresponding multicast socket beforehand.
If you are to program a server discovery algorithm in Java, take a look at Jini http://www.jini.org
. Gives you all this and more. Don't be intimidated by the 'more', the core is very simple to handle.