【问题标题】:How to get the IP address from the Domain Name in Java?Java如何从域名中获取IP地址?
【发布时间】:2011-01-28 13:50:38
【问题描述】:

我正在编写一个需要 IP 地址的应用程序。我有一个域名,我想知道如何从中获取 IP 地址。例如,“www.girionjava.com”。我如何通过 Java 编程获得该网站的 IP 地址?谢谢。

【问题讨论】:

    标签: java ip-address


    【解决方案1】:
    InetAddress giriAddress = java.net.InetAddress.getByName("www.girionjava.com");
    

    那么,如果你想要 IP 作为字符串

    String address = giriAddress.getHostAddress();
    

    【讨论】:

      【解决方案2】:

      这应该很简单。

      InetAddress[] machines = InetAddress.getAllByName("yahoo.com");
      for(InetAddress address : machines){
        System.out.println(address.getHostAddress());
      }
      

      【讨论】:

      • 这是否会在循环 DNS 上获取所有 IP?
      【解决方案3】:
      InetAddress.getByName("www.girionjava.com")
      

      【讨论】:

        【解决方案4】:

        (打印正弦 java 中的额外掩码认为所有整数都是有符号的,但 IP 地址是无符号的)

        InetAddress[] machines = InetAddress.getAllByName("yahoo.com");
        for(InetAddress address : machines){
          byte[] ip = address.getAddress();
          for(byte b : ip){
            System.out.print(Integer.toString(((int)b)&0xFF)+".");
          }
          System.out.println();
        }
        

        【讨论】:

        • 这假设您将只获得 IPv4 地址。 IPv6 地址的格式不同,所以无论如何您都不应该手动格式化。
        猜你喜欢
        • 1970-01-01
        • 2011-04-04
        • 2011-01-28
        • 2012-09-04
        • 2012-05-11
        • 2017-06-20
        • 2023-04-08
        • 1970-01-01
        • 2018-04-10
        相关资源
        最近更新 更多