我正在尝试转换由IP号码或名称指定的地址,无论是在字符串(即localhost
或127.0.0.1
),到一个 inetaddress 对象。没有构造函数,只有返回InetAddress的静态方法。如果我得到主机名没问题,但如果我得到IP号呢?有一种方法可以获得byte[],但我不确定这对我有什么帮助。所有其他方法获取主机名。
InetAddress API文档
您应该能够使用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}
);
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();
}
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();
}
}
}