20230627 java.net.InetAddress
介绍
- java.net.InetAddress
- public class InetAddress implements java.io.Serializable
- 因特网地址,是一串数字表示的主机地址(IPv4 是 4 字节,IPv6 是 16 字节)
- 支持在主机名和因特网地址之间进行转换
- 封装了一个字节序列(IPv4 是 4 字节),byte 的取值范围是 [-126, 125) ,IPv4 的大小是 [0, 255] ,所以超过 125 的是负数表示,例如 183.3.226.35 表示为字节数组 [-73, 3, -30, 35]
API
static
- getByAddress
- 返回代表某个主机的 InetAddress 对象
- getByName
- 通过主机名获取 InetAddress
- getAllByName
- 获取主机名对应的所有 InetAddress
- getLocalHost
- 获取本地主机的地址
- getLoopbackAddress
- 返回环回地址,IPv4 环回地址一般是 127.0.0.1
public
-
getAddress
- 返回字节数组
-
getHostAddress
- 返回一个由十进制数组成的字符串,各数字间用圆点符号隔开,例如,129.6.15.28
-
getHostName
- 返回主机名
-
getCanonicalHostName
- 返回主机名
- 从 NameService 获取
-
isReachable
- 测试该地址是否可达
-
isAnyLocalAddress
-
isLinkLocalAddress
-
isLoopbackAddress
-
isMulticastAddress
-
isSiteLocalAddress
-
isMCGlobal
-
isMCLinkLocal
-
isMCNodeLocal
-
isMCOrgLocal
-
isMCSiteLocal
示例代码
import cn.hutool.core.lang.Console;
import org.junit.jupiter.api.Test;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* TestInetAddress
*
* @date 2023/6/27
*/
public class TestInetAddress {
@Test
public void test1() throws UnknownHostException {
InetAddress localHost = InetAddress.getLocalHost();
InetAddress loopbackAddress = InetAddress.getLoopbackAddress();
Console.log(localHost); // 电脑主机名称/局域网IPv4地址
Console.log(loopbackAddress); // localhost/127.0.0.1
InetAddress byName = InetAddress.getByName("qq.com");
InetAddress[] allByName = InetAddress.getAllByName("qq.com");
Console.log(byName); // qq.com/183.3.226.35
Console.log(allByName); // [qq.com/183.3.226.35, qq.com/123.151.137.18, qq.com/61.129.7.47]
byte[] address = byName.getAddress();
for (byte b : address) {
Console.log((int)b); // -73, 3, -30, 35
}
InetAddress byAddress = InetAddress.getByAddress("qq.com", new byte[]{-73, 3, -30, 35});
Console.log(byAddress); // qq.com/183.3.226.35
InetAddress byAddress2 = InetAddress.getByAddress(new byte[]{-73, 3, -30, 35});
Console.log(byAddress2.getCanonicalHostName()); // 183.3.226.35
}
}