我正在尝试将一个用IP地址或名称(都是字符串,例如localhost
或127.0.0.1
)指定的地址转换为一个InetAddress对象。没有构造函数,而是返回一个InetAddress的静态方法。如果我得到主机名,这不是问题,但如果我得到IP地址呢?有一个方法可以传入byte[],但我不确定它如何帮助我。所有其他方法都需要主机名。
我正在尝试将一个用IP地址或名称(都是字符串,例如localhost
或127.0.0.1
)指定的地址转换为一个InetAddress对象。没有构造函数,而是返回一个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);
来自InetAddress的API
主机名可以是机器名称,例如“java.sun.com”,也可以是其IP地址的文本表示。如果提供了字面IP地址,则仅检查地址格式的有效性。
ip = InetAddress.getByAddress(new byte[] {
(byte)192, (byte)168, (byte)0, (byte)102}
);
这个API非常容易使用。
// Lookup the dns, if the ip exists.
if (!ip.isEmpty()) {
InetAddress inetAddress = InetAddress.getByName(ip);
dns = inetAddress.getCanonicalHostName();
}
InetAddress.getByName也适用于IP地址。
从JavaDoc中可以看到:
主机名可以是机器名称,例如“java.sun.com”,也可以是其IP地址的文本表示。如果提供了字面IP地址,则仅检查地址格式的有效性。
InetAddress类可用于存储IPv4和IPv6格式的IP地址。您可以使用InetAddress.getByName()
或InetAddress.getByAddress()
方法将IP地址存储到对象中。
在以下代码片段中,我使用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
这是一个获取任何网站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();
}
}
}
byte[] loopback = {0x7f,0x00,0x00,0x01};
- Carlos Ferreyra