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?
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
:
traceroute
is actually tracert.exe
, so there's no need for O/S dependencies in the codetraceroute
is sometimes blocked by the networkThe 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With