如何从Java中的域名中获取IP地址?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2462398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:03:15  来源:igfitidea点击:

How to get the IP address from the Domain Name in Java?

javaip-address

提问by giri

I am writing an application where I need the IP address. I have a domain name and I would like to know how to get the IP address from it. For example, "www.girionjava.com". How could I get the IP address of this website by programming in Java? Thanks.

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

回答by flybywire

InetAddress.getByName("www.girionjava.com")

回答by Powerlord

InetAddress giriAddress = java.net.InetAddress.getByName("www.girionjava.com");

Then, if you want the IP as a String

然后,如果您希望 IP 作为字符串

String address = giriAddress.getHostAddress();

回答by M. Jessup

(Extra mask in printing sine java considers all integers to be signed, but an IP address is unsigned)

(打印正弦 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();
}

回答by redoc

This should be simple.

这应该很简单。

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