在 Java 中创建 InetAddress 对象

我正在尝试将一个 IP 编号或名称指定的地址转换为一个 网址对象,这两者都是字符串(即 localhost127.0.0.1)。没有构造函数,只有返回 InetAddress的静态方法。所以,如果我得到一个主机名,这不是一个问题,但如果我得到的 IP 号码?有一种方法可以得到 字节[],但是我不知道这对我有什么帮助。所有其他方法获取主机名。

InetAddress API 文档

159557 次浏览

From the API for InetAddress

The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.

You should be able to use getByName or getByAddress.

The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address

InetAddress addr = InetAddress.getByName("127.0.0.1");

The method that takes a byte array can be used like this:

byte[] ipAddr = new byte[]{127, 0, 0, 1};
InetAddress addr = InetAddress.getByAddress(ipAddr);

InetAddress.getByName also works for ip address.

From the JavaDoc

The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.

The api is fairly easy to use.

// Lookup the dns, if the ip exists.
if (!ip.isEmpty()) {
InetAddress inetAddress = InetAddress.getByName(ip);
dns = inetAddress.getCanonicalHostName();
}
ip = InetAddress.getByAddress(new byte[] {
(byte)192, (byte)168, (byte)0, (byte)102}
);

This is a project for getting IP address of any website , it's usefull and so easy to make.

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 class can be used to store IP addresses in IPv4 as well as IPv6 formats. You can store the IP address to the object using either InetAddress.getByName() or InetAddress.getByAddress() methods.

In the following code snippet, I am using InetAddress.getByName() method to store IPv4 and IPv6 addresses.

InetAddress IPv4 = InetAddress.getByName("127.0.0.1");
InetAddress IPv6 = InetAddress.getByName("2001:db8:3333:4444:5555:6666:1.2.3.4");

You can also use InetAddress.getByAddress() to create object by providing the byte array.

InetAddress addr = InetAddress.getByAddress(new byte[]{127, 0, 0, 1});

Furthermore, you can use InetAddress.getLoopbackAddress() to get the local address and InetAddress.getLocalHost() to get the address registered with the machine name.

InetAddress loopback = InetAddress.getLoopbackAddress(); // output: localhost/127.0.0.1
InetAddress local = InetAddress.getLocalHost(); // output: <machine-name>/<ip address on network>

Note- make sure to surround your code by try/catch because InetAddress methods return java.net.UnknownHostException