Spring Boot中的RestTemplate获取客户端公网ip和局域网ip
时间: 2023-11-24 11:19:18 浏览: 104
在使用RestTemplate发送HTTP请求时,可以通过获取HTTP请求的RemoteAddr属性来获取客户端的公网IP地址。示例代码如下:
```java
RestTemplate restTemplate = new RestTemplate();
String remoteAddr = request.getRemoteAddr();
String url = "http://" + remoteAddr + ":8080/api/data";
String response = restTemplate.getForObject(url, String.class);
```
如果想获取局域网IP地址,可以使用Java的网络编程API,通过获取本机的网络接口信息来获取局域网IP地址。示例代码如下:
```java
RestTemplate restTemplate = new RestTemplate();
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
String localAddr = null;
while (interfaces.hasMoreElements()) {
NetworkInterface ni = interfaces.nextElement();
Enumeration<InetAddress> addresses = ni.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
if (!address.isLinkLocalAddress() && !address.isLoopbackAddress() && address instanceof Inet4Address) {
localAddr = address.getHostAddress();
}
}
}
String url = "http://" + localAddr + ":8080/api/data";
String response = restTemplate.getForObject(url, String.class);
```
请注意,获取局域网IP地址时可能会有多个网络接口,需要根据实际情况选择正确的网络接口。
阅读全文