I try to learn TCP/IP and as an exercise I have developed a LAN host discovery utility like http://overlooksoft.com.
After crawling the web, I’ve found nmap utility which do this job.
I have made this small test:
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
public class NetDiscovery {
public static void main( String[] args ) throws Throwable {
DatagramChannel channel = DatagramChannel.open();
channel.bind(
new InetSocketAddress( InetAddress.getByName( "192.168.1.7" ), 2416 ));
ByteBuffer buffer = ByteBuffer.allocate( 1024 );
SocketAddress address =
new InetSocketAddress( InetAddress.getByName( "192.168.1.255" ), 80 );
channel.send( buffer, address );
SocketAddress sender = channel.receive( buffer ); // <<<<<<<<<<<<<<<<<<<<
System.err.println(
((InetSocketAddress)sender).getAddress().getHostAddress());
}
}
I expect some response to this “udp ping broadcast” by the other hosts (4) on my LAN but this program waits indefinitely in the line marked with // <<<<<<<<<<<<<<<<<<<<
Why?
UDP doesn’t work like that. Unless something on those other machines is bound to UDP port 80, and responding, nothing would happen. The datagrams are just lost. Other machines probably send ICMP “port unreachable” messages, but since you can’t really connect to broadcast address, you get nothing at the UDP level.
If you don’t want anything deployed on other machines, then ICMP is probably your best option. Otherwise look into multicast and maybe zeroconf.