Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get default gateway in java

I want to fetch default gateway for local machine using java. I know how to get it by executing dos or shell commands, but is there any another way to fetch? Also need to fetch primary and secondary dns ip.

like image 667
Nirmal- thInk beYond Avatar asked May 10 '11 04:05

Nirmal- thInk beYond


2 Answers

My way is:

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

Because of using datagram (UDP), it isn't connecting anywhere, so port number may be meaningless and remote address (1.1.1.1) needn't be reachable, just routable.

like image 57
motas Avatar answered Sep 18 '22 19:09

motas



In Windows with the help of 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'm getting the default gateway IP address of my router, and opening it in a browser to see my router's setup page.

like image 38
Ian Campbell Avatar answered Sep 18 '22 19:09

Ian Campbell