How to Determine the Ip of My Router/Gateway in Java

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

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.

how to get the ip address of the connected interface

this should do the trick:

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);
}
}

Courtesy of Chris Bunch from: How can I determine the IP of my router/gateway in Java?

Greets!

Get default gateway in java

There is not an easy way to do this. You'll have to call local system commands and parse the output, or read configuration files or the registry. There is no platform independent way that I'm aware of to make this work - you'll have to code for linux, mac and windows if you want to run on all of them.

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

That covers the gateway, and you could use ifconfig or ipconfig as well to get this. For DNS info, you'll have to call a different system command such as ipconfig on Windows or parse /etc/resolv.conf on Linux or mac.

Java getting my IP address

The NetworkInterface class contains all the relevant methods, but be aware that there's no such thing as "my IP". A machine can have multiple interfaces and each interface can have multiple IPs.

You can list them all with this class but which interface and IP you choose from the list depends on what you exactly need to use this IP for.

(InetAddress.getLocalHost() doesn't consult your interfaces, it simply returns constant 127.0.0.1 (for IPv4))



Related Topics



Leave a reply



Submit