JavaWeb 获取ip地址

java获取IP地址分为两种情况:

一种是:根据网络请求,获取该请求对应的IP;

另一种是:获取本机的IP的网络地址。

获取请求IP

导包

import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.servlet.http.HttpServletRequest;

代码实现

/** 
 * 获取当前网络ip 
 * @param request 
 * @return 
 */  
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();  
        if(ip.equals("127.0.0.1") || ip.equals("0:0:0:0:0:0:0:1")){  
            //根据网卡取本机配置的IP  
            InetAddress inet=null;  
            try {  
                inet = InetAddress.getLocalHost();  
            } catch (UnknownHostException e) {  
                e.printStackTrace();  
            }  
            ip= inet.getHostAddress();  
        }  
    }  
    //对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割  
    if(ip!=null && ip.length()>15){ //"***.***.***.***".length() = 15  
        if(ip.indexOf(",")>0){  
            ip = ip.substring(0,ip.indexOf(","));  
        }  
    }  
    return ip;   
}

2023年4月8日11:48:43

public static String getIpAddress(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.getHeader("HTTP_CLIENT_IP");
    }

    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("HTTP_X_FORWARDED_FOR");
    }

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

    return ip;
}

2022年1月21日17:18:35

获取本地IP


import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.Nullable;

import java.net.*;
import java.util.Enumeration;

/**
 * IP工具类
 * @description:
 * @author: Marydon
 * @date: 2022-01-21 16:59
 * @version: 1.0
 * @email: marydon20170307@163.com
 */
@Slf4j
public final class IpUtils {

    private IpUtils() {
    }

    @Nullable
    public static String getLocalIP(Class<? extends InetAddress> inetClass) {
        Enumeration interfaces = null;

        try {
            interfaces = NetworkInterface.getNetworkInterfaces();

            while(true) {
                String iFDisplayName;
                String iName;
                NetworkInterface networkInterface;
                do {
                    do {
                        do {
                            if (!interfaces.hasMoreElements()) {
                                log.error("未找到本地端口:{}", interfaces);
                                return null;
                            }

                            networkInterface = (NetworkInterface)interfaces.nextElement();
                            iFDisplayName = networkInterface.getDisplayName().toLowerCase();
                            iName = networkInterface.getName().toLowerCase();
                        } while(!networkInterface.isUp());
                    } while(iFDisplayName.contains("tap"));
                } while(!iFDisplayName.startsWith("e") && !iFDisplayName.startsWith("w") && !iFDisplayName.startsWith("b") && !iName.startsWith("e") && !iName.startsWith("w") && !iName.startsWith("b"));

                Enumeration inetAddressEnum = networkInterface.getInetAddresses();

                while(inetAddressEnum.hasMoreElements()) {
                    InetAddress inetAddress = (InetAddress)inetAddressEnum.nextElement();
                    if (inetAddress.getClass() == inetClass) {
                        log.debug("获得IP:{}", inetAddress.getHostAddress());
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException var7) {
            log.error("获取本地IP出错:" + interfaces, var7);
            return null;
        }
    }

    public static String getLocalIPv4() {
        return getLocalIP(Inet4Address.class);
    }
    public static String getLocalIPv6() {
        return getLocalIP(Inet6Address.class);
    }

    public static void main(String[] args) {
        IpUtils.getLocalIPv4();
        IpUtils.getLocalIPv6();
    }
}

测试结果如下:

posted @ 2018-05-31 18:00  Marydon  阅读(1423)  评论(0编辑  收藏  举报