java中获取默认网关

发布于 2024-11-06 02:35:30 字数 87 浏览 0 评论 0原文

我想使用 java 获取本地计算机的默认网关。我知道如何通过执行dos或shell命令来获取它,但是还有其他方法来获取吗? 还需要获取主要和辅助 dns ip。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

心的憧憬 2024-11-13 02:35:31

我的方法是:

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

由于使用数据报(UDP),所以它不是无法连接到任何地方,因此端口号可能毫无意义,并且远程地址 (1.1.1.1) 不需要可达,只需可路由即可。

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.

诺曦 2024-11-13 02:35:31

在 Windows 中,借助 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();
            }
        }
    }
}

在这里,我获取了路由器的默认网关 IP 地址,并在浏览器中打开它以查看路由器的设置页面。

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.

窗影残 2024-11-13 02:35:31

没有一种简单的方法可以做到这一点。您必须调用本地系统命令并解析输出,或者读取配置文件或注册表。据我所知,没有一种独立于平台的方法可以实现这项工作——如果你想在所有平台上运行,你就必须为 Linux、Mac 和 Windows 编写代码。

请参阅 如何确定 IP我的 Java 路由器/网关?

这涵盖了网关,您也可以使用 ifconfig 或 ipconfig 来获取它。对于 DNS 信息,您必须调用不同的系统命令,例如 Windows 上的 ipconfig 或 Linux 或 Mac 上的 parse /etc/resolv.conf。

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.

九八野马 2024-11-13 02:35:31

目前 Java 中没有标准接口来获取默认网关或 DNS 服务器地址。您将需要一个 shell 命令。

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

很酷不放纵 2024-11-13 02:35:31

我不确定它是否适用于每个系统,但至少在这里我发现了这一点:

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

对我来说这会产生:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文