java如何获取当前登录ip

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java如何获取当前登录ip相关的知识,希望对你有一定的参考价值。

为适应不同的网络情况,提供这个类:看下面的代码吧,Copy过去就能用。
import javax.servlet.http.HttpServletRequest;

public class HttpUtil

public static String getIpAddr(HttpServletRequest request)
String ip = request.getHeader("x-forwarded-for");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
ip = request.getHeader("Proxy-Client-IP");

if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
ip = request.getHeader("WL-Proxy-Client-IP");

if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
ip = request.getRemoteAddr();

return ip;

参考技术A 第一种:获取本机的IP

Enumeration<NetworkInterface> netInterfaces = null;
try
netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements())
NetworkInterface ni = netInterfaces.nextElement();
System.out.println("DisplayName:" + ni.getDisplayName());
System.out.println("Name:" + ni.getName());
Enumeration<InetAddress> ips = ni.getInetAddresses();
while (ips.hasMoreElements())
System.out.println("IP:" + ips.nextElement().getHostAddress());
ipTemp= ni.getInetAddresses().nextElement().getHostAddress();
if(ipTemp!="127.0.0.1" && !"127.0.0.1".equals(ipTemp))

ip=ipTemp;



catch(Exception ee)

ee.printStackTrace();


第二种:也是本机的:
InetAddress addr = InetAddress.getLocalHost();
ip=addr.getHostAddress().toString();//获得本机IP
参考技术B request.getRemoteAddr();本回答被提问者采纳

以上是关于java如何获取当前登录ip的主要内容,如果未能解决你的问题,请参考以下文章

Linux服务器如何获取出口ip

java如何获取当前时间,java如何获取ip地址

java如何获取Linux操作系统下的硬件信息

java中,如何获取真实的IP地址?

java 如何获取当前AD域用户名?

java如何获取本机IP?