webdude at dingnet dot org dot uk

ICMP Echo/Reply (aka Ping) Implementation for Java

Update (26/12/2004)

I've just discovered that Java 1.5 finally includes ICMP support, via the isReachable() method of the InetAddress object. I guess this partially depracates my code! I'll leave it below anyway, in case it comes in useful to anyone - for example, needing to do anything with round trip times or variable sized payloads.

My old Java ICMP implementation

Yesterday (well, when I wrote this it was "Yesterday" but it was actually around the 20th June 2002), my flatmate was telling me how he was writing a little Java program which would monitor which machines were online, on our network. He did this by connecting to TCP port 22, the secure shell port, as nearly all the machines in our flat run secure shell. "Why not just ping them?", I wondered. As it turns out, there is no way to create ICMP packets in Java - you can only create TCP or UDP connections.

Well, I'd been looking for something to do and this sounded like fun. So I grabbed a copy of the relevant RFC, and wrote a ICMP Echo/Reply implementation in C, then linked it in with a Java class using the Java Native Interface (JNI).

Unfortunately, it requires root (at least, on a Linux box) - as ping.c creates a raw packet, which can only be done by the super-user. Does anyone know if there is any way round this? A kinda suid-root for shared libraries? I'm not sure what the deal under windows is. I believe that with Win9x you can Just Do It. Or something. Win2k/ME might not let you, though.... Unfortunately, I can't actually verify any of the windows stuff, as I lack a Windows C compiler.

Well, here it is. I wonder if it will ever be of any use to anyone.

  • Ping.h - The JNI-generated header file.
  • ping.c - The actual code which creates a rudimentary icmp packet and sends it, or listens for a ICMP packet.
  • - The Java front-end to ping.c - also implements things like ttl reporting, detection of duplicate packets etc..
  • - A sample ping client.
  • rfc792.txt - the ICMP RFC. By the way, it doesn't make it too clear, but the data part is included in the checksum.
  • Makefile - My Makefile, if it's of any use to anyone.
  • - A compiled copy of the ping library. Stick this in your library path (or set LD_LIBRARY_PATH appropriately), then either write your own code to do something with it, or use the Ping class.

By the way, looking at the web logs, I see that people are actually downloading these files! That suprised me. If you have downloaded them, I wouldn't mind a e-mail from you - just saying what you want a java icmp implementation for. This isn't a requirement or condition of use, or anything, I'm just curious as to where the code I wrote may end up :)

Copyright (c) TeamLinux, 2004