在Java中如何使用InetAddress获取IP地址
时间:2020-02-23 14:34:19 来源:igfitidea点击:
IP地址是IP使用的32位或者128位无符号数字,IP是在其上构建UDP和TCP等协议的较低级别协议。
在Java中," InetAddress"类表示Internet协议(IP)地址。
其中我们将学习如何使用InetAddress在Java中获取本地主机IP地址和IP地址。
package com.theitroad.util;
import java.net.UnknownHostException;
import java.net.InetAddress;
public class JavaIPAddress {
/**
* @param args
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException {
//print localhost ip address
System.out.println(InetAddress.getLocalHost().getHostAddress());
//print website ip address
System.out.println(InetAddress.getByName("www.theitroad.local"));
//print all ip addresses for a website
InetAddress[] inetAddresses = InetAddress.getAllByName("www.google.com");
for(InetAddress inet : inetAddresses){
System.out.println(inet);
}
}
}
上面程序的输出是:
192.168.3.1 www.theitroad.local/50.116.65.160 www.google.com/74.125.224.82 www.google.com/74.125.224.81 www.google.com/74.125.224.80 www.google.com/74.125.224.83 www.google.com/74.125.224.84 www.google.com/2001:4860:4001:803:0:0:0:1010
当我们使用InetAddress.getByName(String host)时,它返回主机名的当前IPv4地址,当我们使用InetAddress.getAllByName(String host)时,它返回与该主机名关联的所有IP地址。
google.com IP的最后输出是IPv6格式的IP地址。
如果没有与主机名关联的IP地址,则这些方法将抛出UnknownHostException。
请注意,我们不应使用HTTP之类的协议来提供主机名输入。

