在我的应用程序中,我编写了查找用户的IP地址。
HttpServletRequest httpRequest = (HttpServletRequest) request;
String userIpAddress = httpRequest.getHeader("X-Forwarded-For");
HttpServletRequest.getLocalAddr();
获取服务器ips可以这样做:
Inet4Address.getLocalHost().getHostAddress();
那么,如果用户已经从一个ip地址登录,如何限制他从另一个ip地址登录?
答案 0 :(得分:2)
尝试以下代码:
Inet4Address address=(Inet4Address) Inet4Address.getLocalHost();
System.out.println(address.getHostAddress());
Inet4Address
来自java.net.Inet4Address;
答案 1 :(得分:0)
在LAN中查找主机地址的最佳方法可以按如下方式完成:
System.out.println(InetAddress.getByName("anyhostname").getHostAddress());
答案 2 :(得分:0)
试试这个,它将枚举本地机器的所有接口地址。
try {
Enumeration<NetworkInterface> interfaceEnumeration =
NetworkInterface.getNetworkInterfaces();
while (interfaceEnumeration.hasMoreElements()) {
Enumeration<InetAddress> inetAddressEnumeration =
interfaceEnumeration.nextElement().getInetAddresses();
while (inetAddressEnumeration.hasMoreElements()) {
System.out.println(inetAddressEnumeration.nextElement().getHostAddress());
}
}
} catch (SocketException e) {
e.printStackTrace();
}
但是下面的方法不可靠,在我的测试环境中,它总是返回循环接口地址。
try {
InetAddress inetAddress[] = InetAddress.getAllByName("localhost");
for (InetAddress address : inetAddress) {
System.out.println(address.getHostAddress());
}
} catch (UnknownHostException e) {
e.printStackTrace();
}