【发布时间】:2011-08-08 19:59:58
【问题描述】:
我正在尝试将由 IP 号或名称指定的地址转换为 InetAdress 对象,两者都是字符串(即localhost 或127.0.0.1)。没有构造函数,而是返回 InetAddress 的静态方法。因此,如果我得到一个主机名,这不是问题,但如果我得到 IP 号怎么办?有一种方法可以获得 byte[] 但我不确定这对我有什么帮助。所有其他方法都获取主机名。
【问题讨论】:
我正在尝试将由 IP 号或名称指定的地址转换为 InetAdress 对象,两者都是字符串(即localhost 或127.0.0.1)。没有构造函数,而是返回 InetAddress 的静态方法。因此,如果我得到一个主机名,这不是问题,但如果我得到 IP 号怎么办?有一种方法可以获得 byte[] 但我不确定这对我有什么帮助。所有其他方法都获取主机名。
【问题讨论】:
您应该能够使用 getByName 或 getByAddress。
主机名可以是机器 名称,例如“java.sun.com”,或 其 IP 的文本表示 地址
InetAddress addr = InetAddress.getByName("127.0.0.1");
采用字节数组的方法可以这样使用:
byte[] ipAddr = new byte[]{127, 0, 0, 1};
InetAddress addr = InetAddress.getByAddress(ipAddr);
【讨论】:
byte[] loopback = {0x7f,0x00,0x00,0x01};
来自 InetAddress 的 API
主机名可以是机器 名称,例如“java.sun.com”,或 其 IP 的文本表示 地址。如果文字 IP 地址是 提供,只有的有效性 地址格式已检查。
【讨论】:
ip = InetAddress.getByAddress(new byte[] {
(byte)192, (byte)168, (byte)0, (byte)102}
);
【讨论】:
InetAddress.getByName 也适用于 IP 地址。
来自 JavaDoc
主机名可以是机器 名称,例如“java.sun.com”,或 其 IP 的文本表示 地址。如果文字 IP 地址是 提供,只有的有效性 地址格式已检查。
【讨论】:
API 相当容易使用。
// Lookup the dns, if the ip exists.
if (!ip.isEmpty()) {
InetAddress inetAddress = InetAddress.getByName(ip);
dns = inetAddress.getCanonicalHostName();
}
【讨论】:
这是一个获取任意网站IP地址的项目,非常好用,制作也很简单。
import java.net.InetAddress;
import java.net.UnkownHostExceptiin;
public class Main{
public static void main(String[]args){
try{
InetAddress addr = InetAddresd.getByName("www.yahoo.com");
System.out.println(addr.getHostAddress());
}catch(UnknownHostException e){
e.printStrackTrace();
}
}
}
【讨论】:
InetAddress 类可用于以 IPv4 和 IPv6 格式存储 IP 地址。您可以使用InetAddress.getByName() 或InetAddress.getByAddress() 方法将IP 地址存储到对象中。
在下面的代码sn-p中,我使用InetAddress.getByName()方法来存储IPv4和IPv6地址。
InetAddress IPv4 = InetAddress.getByName("127.0.0.1");
InetAddress IPv6 = InetAddress.getByName("2001:db8:3333:4444:5555:6666:1.2.3.4");
您也可以使用InetAddress.getByAddress()通过提供字节数组来创建对象。
InetAddress addr = InetAddress.getByAddress(new byte[]{127, 0, 0, 1});
另外,可以使用InetAddress.getLoopbackAddress()获取本地地址,InetAddress.getLocalHost()获取机器名注册的地址。
InetAddress loopback = InetAddress.getLoopbackAddress(); // output: localhost/127.0.0.1
InetAddress local = InetAddress.getLocalHost(); // output: <machine-name>/<ip address on network>
注意 - 确保使用 try/catch 包围您的代码,因为 InetAddress 方法返回 java.net.UnknownHostException
【讨论】: