ipv4地址追踪(pc、移动端均支持)
ipv4代码块
通过java.net.URL 类来连接,然后读取返回的 IPv4 地址。最后,打印出获取到的公共 IPv4 地址
此操作通过用户访问/ip接口,将自动获取到用户当前设备ipv4地址,ipAddress自行打印操作。
/**
* 查询用户信息
* @param
* @return
*/
@RequestMapping("/ip")
public ResponseEntity<CommonResult<Object>> ip(){
String ipAddress = null;
try {
ipAddress = getPublicIPv4Address();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return setSuccessCommonResult(ipAddress);
}
private static String getIPv4Address() throws SocketException {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress.getAddress().length == 4) {
return inetAddress.getHostAddress();
}
}
}
return null;
}
private static String getPublicIPv4Address() throws IOException {
URL url = new URL("https://api.ipify.org");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String ipAddress = reader.readLine();
reader.close();
return ipAddress;
}
上述代码可进行相关的操作有,例:
获取用户ipv4后,调用高德地图有关ipv4的api进行信息获取,能得到用户城市、经纬度坐标