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

On windows parsing the output of IPConfig will get you the default gateway, without waiting for a trace.


Java doesn't make this as pleasant as other languages, unfortunately. Here's what I did:

import java.io.*;
import java.util.*;

public class ExecTest {
    public static void main(String[] args) throws IOException {
        Process result = Runtime.getRuntime().exec("traceroute -m 1 www.amazon.com");

        BufferedReader output = new BufferedReader(new InputStreamReader(result.getInputStream()));
        String thisLine = output.readLine();
        StringTokenizer st = new StringTokenizer(thisLine);
        st.nextToken();
        String gateway = st.nextToken();
        System.out.printf("The gateway is %s\n", gateway);
    }
}

This presumes that the gateway is the second token and not the third. If it is, you need to add an extra st.nextToken(); to advance the tokenizer one more spot.


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