java 获取本机ip和外网 ip
时间: 2024-12-05 19:07:41 浏览: 21
在Java中获取本机IP地址(无论是内网还是公网IP)通常有两种方式:
1. **通过网络套接字(Socket)获取**:
```java
import java.net.InetAddress;
import java.net.UnknownHostException;
public class IPFinder {
public static void main(String[] args) {
try {
// 获取本地主机名
InetAddress localAddress = InetAddress.getLocalHost();
String ipAddress = localAddress.getHostAddress();
System.out.println("Local IP: " + ipAddress);
// 如果需要获取公网IP,有时会通过防火墙设置代理访问,这里需要连接到外部服务器并尝试读取响应头的"X-Forwarded-For"
// 但这不是标准做法,因为这依赖于网络环境配置,并非所有场景都能保证准确。下面示例仅供参考:
URL url = new URL("https://api.ipify.org");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
if (connection.getResponseCode() == 200) {
String remoteIp = connection.getHeaderField("X-Forwarded-For");
if (remoteIp != null && !remoteIp.isEmpty()) {
System.out.println("Public IP (via proxy): " + remoteIp);
} else {
System.out.println("Public IP: " + connection.getRemoteSocketAddress());
}
} else {
System.out.println("Failed to get public IP.");
}
} catch (UnknownHostException e) {
System.err.println("Failed to determine local IP address.");
e.printStackTrace();
} catch (IOException e) {
System.err.println("Error while fetching public IP.");
e.printStackTrace();
}
}
}
```
注意:上述公网IP获取方法仅适用于某些环境,并不是所有网络环境下都能得到正确的结果。
阅读全文