【问题标题】:Get default gateway in java在java中获取默认网关
【发布时间】:2011-08-22 03:56:17
【问题描述】:

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

【问题讨论】:

    标签: java networking dns ip gateway


    【解决方案1】:

    My way 是:

    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)不必可达,只需路由即可。

    【讨论】:

    • 这并不总是返回默认网关,这完全是虚构的。数据包路由由多种因素决定,其中之一是目标地址。如果您的默认网关无法接受/路由您的目标地址,您的数据包将通过另一条路线传送,这可能是所有可用路线中最差的,也可能不是;根据您的网络适配器指标,它也可能是第二好的路由或介于两者之间的路由。请不要编写带有假设的软件,这会使整个业务情况变得更糟。
    • 这很巧妙。不过,它确实取决于目标地址;使用real address that's out there on the internet 可能会更好,以确保您至少获得 a 有效路由,即使它不是默认路由。
    • 如果您有可用的 DNS,您可以在此处使用主机名而不是地址; a.root-servers.net 保证始终存在,并且不太可能在您的本地网络中。
    【解决方案2】:


    ipconfig 的帮助下在 Windows 中:

    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 地址,并在浏览器中打开它以查看路由器的设置页面。

    【讨论】:

      【解决方案3】:

      没有一个简单的方法可以做到这一点。您必须调用本地系统命令并解析输出,或读取配置文件或注册表。我知道没有独立于平台的方式来完成这项工作 - 如果你想在所有这些上运行,你必须为 linux、mac 和 windows 编写代码。

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

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          【解决方案5】:

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

          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
          

          【讨论】:

          • 不幸的是,这对我不起作用。只是给我本地主机。我想我会做getHostAddress。获取前 3 个八位字节并假设 xxx.xxx.xxx.1 或 xxx.xxx.xxx.254 是网关。
          猜你喜欢
          • 2012-11-18
          • 1970-01-01
          • 2011-10-10
          • 2023-04-07
          • 2011-07-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多