Get default gateway in java

2019-02-17 08:09发布

问题:

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.

回答1:

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.



回答2:

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.



回答3:


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.



回答4:

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



回答5:

I'm not sure if it works on every system but at least here I found this:

import java.net.InetAddress;
import java.net.UnknownHostException;
public class Main
{
    public static void main(String[] args)
    {
        try
        {
            //Variables to find out the Default Gateway IP(s)
            String canonicalHostName = InetAddress.getLocalHost().getCanonicalHostName();
            String hostName = InetAddress.getLocalHost().getHostName();

            //"subtract" the hostName from the canonicalHostName, +1 due to the "." in there
            String defaultGatewayLeftover = canonicalHostName.substring(hostName.length() + 1);

            //Info printouts
            System.out.println("Info:\nCanonical Host Name: " + canonicalHostName + "\nHost Name: " + hostName + "\nDefault Gateway Leftover: " + defaultGatewayLeftover + "\n");
            System.out.println("Default Gateway Addresses:\n" + printAddresses(InetAddress.getAllByName(defaultGatewayLeftover)));
        } catch (UnknownHostException e)
        {
            e.printStackTrace();
        }
    }
    //simple combined string out the address array
    private static String printAddresses(InetAddress[] allByName)
    {
        if (allByName.length == 0)
        {
            return "";
        } else
        {
            String str = "";
            int i = 0;
            while (i < allByName.length - 1)
            {
                str += allByName[i] + "\n";
                i++;
            }
            return str + allByName[i];
        }
    }
}

For me this produces:

Info:
Canonical Host Name: PCK4D-PC.speedport.ip
Host Name: PCK4D-PC
Default Gateway Leftover: speedport.ip

Default Gateway Addresses:
speedport.ip/192.168.2.1
speedport.ip/fe80:0:0:0:0:0:0:1%12