How can I determine the IP of my router/gateway in Java?

Frank Krueger picture Frank Krueger · Aug 15, 2008 · Viewed 29.4k times · Source

How can I determine the IP of my router/gateway in Java? I can get my IP easily enough. I can get my internet IP using a service on a website. But how can I determine my gateway's IP?

This is somewhat easy in .NET if you know your way around. But how do you do it in Java?

Answer

Alnitak picture Alnitak · Oct 29, 2008

On Windows, OSX, Linux, etc then Chris Bunch's answer can be much improved by using

netstat -rn

in place of a traceroute command.

Your gateway's IP address will appear in the second field of the line that starts either default or 0.0.0.0.

This gets around a number of problems with trying to use traceroute:

  1. on Windows traceroute is actually tracert.exe, so there's no need for O/S dependencies in the code
  2. it's a quick command to run - it gets information from the O/S, not from the network
  3. traceroute is sometimes blocked by the network

The only downside is that it will be necessary to keep reading lines from the netstat output until the right line is found, since there'll be more than one line of output.

EDIT: The Default Gateway's IP Address is in the second field of the line that starts with 'default' if you are on a MAC (tested on Lion), or in the third field of the line that starts with '0.0.0.0' (tested on Windows 7)

Windows:

Network Destination Netmask Gateway Interface Metric

0.0.0.0 0.0.0.0 192.168.2.254 192.168.2.46 10

Mac:

Destination Gateway Flags Refs Use Netif Expire

default 192.168.2.254 UGSc 104 4 en1