1

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?

2
  • Do those other hosts have anything listening and replying on UDP port 80? Oct 23, 2012 at 21:16
  • No, I try to discover my LAN like overlooksoft.com do. Perhaps should I use ICMP?
    – Aubin
    Oct 23, 2012 at 21:23

2 Answers 2

1

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.

1

Try using Nmap4j (http://nmap4j.sourceforge.net) if you want to integrate Java and Nmap. It's a wrapper API around nmap that allows you to access the data returned from nmap in Java objects.

2
  • Thanks. The main goal is to learn TCP/IP deeply. I'll try to code in C/C++ and eventually with Java/JNI if it'll rain next week-end... ;-)
    – Aubin
    Oct 24, 2012 at 16:38
  • I am not an expert, but I do know that C/C++ would be a better route to follow for a good understanding of TCP/IP. NMap is written in one or the other because you need access to OS libraries that you won't be able to access easily in Java (it's probably possible but it would be harder than doing it all in C/C++). Best of luck to you!
    – Jon
    Oct 25, 2012 at 14:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.