✅ Java 网络编程:InetAddress 类详解
在 Java 中,InetAddress
类用于表示 IP 地址(IPv4 或 IPv6),它是 Java 网络编程中最常用的类之一,属于 java.net
包。
1️⃣ InetAddress 的作用
- 表示一个 IP 地址(域名或 IP 本身)
- 提供主机名与 IP 地址的解析功能
- 是进行 Socket 编程的基础类之一
2️⃣ 常用方法
方法名 |
说明 |
getLocalHost() |
获取本机的 InetAddress 对象 |
getByName(String host) |
根据主机名或 IP 获取对应的 InetAddress 对象 |
getAllByName(String host) |
获取与指定主机名关联的所有 IP 地址 |
getHostName() |
获取该 IP 对象对应的主机名 |
getHostAddress() |
获取该对象的 IP 地址字符串 |
isReachable(int timeout) |
判断该地址是否可以在指定时间内连通 |
3️⃣ 示例一:获取本机 IP 与主机名
1 2 3 4 5 6 7 8 9
| import java.net.*;
public class LocalHostInfo { public static void main(String[] args) throws UnknownHostException { InetAddress local = InetAddress.getLocalHost(); System.out.println("本机主机名: " + local.getHostName()); System.out.println("本机 IP 地址: " + local.getHostAddress()); } }
|
📌 输出示例:
1 2
| 本机主机名: DESKTOP-123ABC 本机 IP 地址: 192.168.1.100
|
4️⃣ 示例二:根据域名获取 IP 地址
1 2 3 4 5 6 7 8 9
| import java.net.*;
public class DomainIP { public static void main(String[] args) throws UnknownHostException { InetAddress address = InetAddress.getByName("www.baidu.com"); System.out.println("主机名: " + address.getHostName()); System.out.println("IP 地址: " + address.getHostAddress()); } }
|
📌 输出示例:
1 2
| 主机名: www.baidu.com IP 地址: 220.181.38.150
|
5️⃣ 示例三:获取主机所有 IP 地址
1 2 3 4 5 6 7 8 9 10 11
| import java.net.*;
public class AllIPAddresses { public static void main(String[] args) throws Exception { InetAddress[] addresses = InetAddress.getAllByName("www.google.com");
for (InetAddress addr : addresses) { System.out.println("IP: " + addr.getHostAddress()); } } }
|
📌 用途:获取网站的所有服务器地址,用于负载均衡场景分析。
6️⃣ 示例四:判断地址是否可达
1 2 3 4 5 6 7 8 9 10
| import java.net.*;
public class PingTest { public static void main(String[] args) throws Exception { InetAddress address = InetAddress.getByName("www.baidu.com");
boolean reachable = address.isReachable(3000); System.out.println("百度是否可达: " + reachable); } }
|
7️⃣ 补充说明
InetAddress
是一个 抽象类,不能直接实例化。
- 它的两个子类是:
Inet4Address
:IPv4 地址
Inet6Address
:IPv6 地址
✅ 总结
功能 |
方法示例 |
获取本机信息 |
InetAddress.getLocalHost() |
通过域名获取 IP |
InetAddress.getByName("example.com") |
获取所有 IP 地址 |
InetAddress.getAllByName(...) |
获取主机名 |
getHostName() |
获取 IP 字符串 |
getHostAddress() |
判断网络是否连通 |
isReachable(timeout) |