Get default gateway in java

I want to get a standard gateway for a local machine using java. I know how to get it by running dos or shell commands, but is there any other way to extract it? It is also necessary to get the primary and secondary dns ip.

+6
java networking dns ip gateway
source share
4 answers

There is no easy way to do this. You will have to call local system commands and analyze the output, read configuration files or the registry. There is no platform-independent way that I know to make this work β€” you'll have to code for Linux, Mac, and Windows if you want to run them on everyone.

See How to determine the IP address of my router / gateway in Java?

This covers the gateway, and you can use ifconfig or ipconfig to get this. For DNS information, you will have to call another system command, such as ipconfig, on Windows or parse / etc / resolv.conf for Linux or Mac.

0
source share


On Windows using ipconfig :

 import java.awt.Desktop; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URI; public final class Router { private static final String DEFAULT_GATEWAY = "Default Gateway"; private Router() { } public static void main(String[] args) { if (Desktop.isDesktopSupported()) { try { Process process = Runtime.getRuntime().exec("ipconfig"); try (BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(process.getInputStream()))) { String line; while ((line = bufferedReader.readLine()) != null) { if (line.trim().startsWith(DEFAULT_GATEWAY)) { String ipAddress = line.substring(line.indexOf(":") + 1).trim(), routerURL = String.format("http://%s", ipAddress); // opening router setup in browser Desktop.getDesktop().browse(new URI(routerURL)); } System.out.println(line); } } } catch (Exception e) { e.printStackTrace(); } } } } 

Here I get the IP address of the default gateway for my router and open it in my browser to see the router settings page.

+1
source share

There is currently no standard Java interface for obtaining the default gateway or DNS server addresses. You will need a shell command.

0
source share

My way :

 try(DatagramSocket s=new DatagramSocket()) { s.connect(InetAddress.getByAddress(new byte[]{1,1,1,1}), 0); return NetworkInterface.getByInetAddress(s.getLocalAddress()).getHardwareAddress(); } 

Due to the use of a datagram (UDP), it is not connected anywhere, so the port number can be meaningless, and the remote address (1.1.1.1) cannot be accessed, we simply route it.

0
source share

All Articles