Java获取IP地址,IpUtils工具类,Java IP地址获取
程序员文章站
2024-02-01 10:57:10
©Copyright 蕃薯耀 2020-01-17 https://www.cnblogs.com/fanshuyao/ import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterfa ......
================================
©copyright 蕃薯耀 2020-01-17
import java.net.inet4address; import java.net.inetaddress; import java.net.networkinterface; import java.util.enumeration; import javax.servlet.http.httpservletrequest; public class iputils { private static final string[] headers = { "x-forwarded-for", "proxy-client-ip", "wl-proxy-client-ip", "http_x_forwarded_for", "http_x_forwarded", "http_x_cluster_client_ip", "http_client_ip", "http_forwarded_for", "http_forwarded", "http_via", "remote_addr", "x-real-ip" }; /** * 判断ip是否为空,空返回true * @param ip * @return */ public static boolean isemptyip(final string ip){ return (ip == null || ip.length() == 0 || ip.trim().equals("") || "unknown".equalsignorecase(ip)); } /** * 判断ip是否不为空,不为空返回true * @param ip * @return */ public static boolean isnotemptyip(final string ip){ return !isemptyip(ip); } /*** * 获取客户端ip地址(可以穿透代理) * @param request httpservletrequest * @return */ public static string getipaddress(httpservletrequest request) { string ip = ""; for (string header : headers) { ip = request.getheader(header); if(isnotemptyip(ip)) { break; } } if(isemptyip(ip)){ ip = request.getremoteaddr(); } if(isnotemptyip(ip) && ip.contains(",")){ ip = ip.split(",")[0]; } if("0:0:0:0:0:0:0:1".equals(ip)){ ip = "127.0.0.1"; } return ip; } /** * 获取本机的局域网ip地址,兼容linux * @return string * @throws exception */ public string getlocalhostip() throws exception{ enumeration<networkinterface> allnetinterfaces = networkinterface.getnetworkinterfaces(); string localhostaddress = ""; while(allnetinterfaces.hasmoreelements()){ networkinterface networkinterface = allnetinterfaces.nextelement(); enumeration<inetaddress> address = networkinterface.getinetaddresses(); while(address.hasmoreelements()){ inetaddress inetaddress = address.nextelement(); if(inetaddress != null && inetaddress instanceof inet4address){ localhostaddress = inetaddress.gethostaddress(); } } } return localhostaddress; } }
(如果你觉得文章对你有帮助,欢迎捐赠,^_^,谢谢!)
================================
©copyright 蕃薯耀 2020-01-17
上一篇: 美团技术四面经历,作者已拿到Offer!
下一篇: 双项淘宝客是什么意思双项淘宝客怎么做?