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 gat
try{
String gateway;
Process result = Runtime.getRuntime().exec("netstat -rn");
BufferedReader output = new BufferedReader(new InputStreamReader(result.getInputStream()));
String line = output.readLine();
while(line != null){
if ( line.trim().startsWith("default") == true || line.trim().startsWith("0.0.0.0") == true )
break;
line = output.readLine();
}
if(line==null) //gateway not found;
return;
StringTokenizer st = new StringTokenizer( line );
st.nextToken();
st.nextToken();
gateway = st.nextToken();
System.out.println("gateway is: "+gateway);
} catch( Exception e ) {
System.out.println( e.toString() );
gateway = new String();
adapter = new String();
}
To overcome the issues mentioned with traceroute (ICMP-based, wide area hit) you could consider:
You may be better off using something like checkmyip.org, which will determine your public IP address - not necessarily your first hop router: at Uni I have a "real" IP address, whereas at home it is my local router's public IP address.
You can parse the page that returns, or find another site that allows you to just get the IP address back as the only string.
(I'm meaning load this URL in Java/whatever, and then get the info you need).
This should be totally platform independent.
You can query the URL "http://whatismyip.com/automation/n09230945.asp". For example:
BufferedReader buffer = null;
try {
URL url = new URL("http://whatismyip.com/automation/n09230945.asp");
InputStreamReader in = new InputStreamReader(url.openStream());
buffer = new BufferedReader(in);
String line = buffer.readLine();
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (buffer != null) {
buffer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}