springboot如何获取公网ip
时间: 2024-04-06 11:23:54 浏览: 88
Spring Boot应用程序可以使用Java的InetAddress类来获取公网IP地址。可以使用以下代码:
```java
import java.net.InetAddress;
import java.net.UnknownHostException;
public class IPAddress {
public static void main(String[] args) {
try {
InetAddress inetAddress = InetAddress.getLocalHost();
System.out.println("IP Address: " + inetAddress.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
```
上述代码将获取本地主机的IP地址。如果您需要获取公网IP地址,可以使用以下代码:
```java
import java.net.InetAddress;
import java.net.UnknownHostException;
public class IPAddress {
public static void main(String[] args) {
try {
InetAddress inetAddress = InetAddress.getByName("checkip.amazonaws.com");
System.out.println("Public IP Address: " + inetAddress.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
```
上述代码将通过访问Amazon AWS的checkip服务获取公网IP地址。注意,这需要访问外部服务并可能受到网络延迟的影响。
阅读全文