注册 X
提交 注:点击提交后系统会发送邮件到邮箱验证!(仅支持中国大陆邮箱)
我已阅读并同意 服务条款
首页 > IT技术笔记 > 查看笔记

java获取本机ip,获取接口请求ip

java获取本机ip,获取接口请求ip

	        
package com.tool.utils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import cn.hutool.core.exceptions.UtilException;

/**
 * 获取ip工具类
 * @author jspanjsp
 *
 */
public class GetIpAddr {
    public static String getRemoteIp(HttpServletRequest request){
        String ip;
        ip = request.getHeader("x-forwarded-for");
        if (isNullIp(ip)){
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (isNullIp(ip)){
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (isNullIp(ip)){
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (isNullIp(ip)){
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (isNullIp(ip)){
            ip = request.getRemoteAddr();
        }
        if(ip.contains(",")){
            ip=ip.split(",")[0];
        }
        if ("0.0.0.0.0.0.0.1".equals(ip) || "0.0.0.0.0.0.0.1%0".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)){ //
            ip = "127.0.0.1";
        }
        return ip;
    }
    private static boolean isNullIp(final String ip){
        return ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip);
    }
    
    /**
     * 获取真实ip
     */
    public static String getTpAddr(HttpServletRequest request) {
    	String ip = request.getHeader("X-Real-IP");
    	if(null != ip && !"".equals(ip.trim()) && !"unknown".equalsIgnoreCase(ip) ) {
    		return ip;
    	}
    	ip = request.getHeader("x-forwarded-for");
    	if( null != ip && !"".equals(ip.trim()) && !"unknown".equalsIgnoreCase(ip) ) {
    		//多次反向代理后会有多个IP值,第一个为真实
    		int index = ip.indexOf(',');
    		if(index != -1) {
    			return ip.substring(0,index);
    		}else {
    			return ip;
    		}
    	}
    	
    	return request.getRemoteAddr();
    }
    
    //获取本地ip地址
    public static Map<String,String> getLocalIpAddr() throws SocketException {
    	Map<String,String> map = new HashMap<String, String>();
        //获取本地所有网络ip地址
        //返回数据类型为Enumeration

		// 获取所有接口,并放进枚举集合中,然后使用Collections.list()将枚举集合转换为ArrayList集合
		Enumeration<NetworkInterface> enu = NetworkInterface.getNetworkInterfaces();
		ArrayList<NetworkInterface> arr = Collections.list(enu);
		for (Iterator<NetworkInterface> it = arr.iterator(); it.hasNext();) {
			NetworkInterface ni = it.next();
			String intName = ni.getName(); // 获取接口名
			// 获取每个接口中的所有ip网络接口集合,因为可能有子接口
			ArrayList<InetAddress> inets = Collections.list(ni.getInetAddresses());
			for (Iterator<InetAddress> it1 = inets.iterator(); it1.hasNext();) {
				InetAddress inet = it1.next();
				// 只筛选ipv4地址,否则会同时得到Ipv6地址
				if (inet instanceof Inet4Address) {
					String ip = inet.getHostAddress();
					map.put(intName, ip);
					// log.info("%-10s %-5s %-6s %-15s
", "InetfaceName:", intName, "|
					// IPv4:", ip);
				}
			}
		}
		return map;
    }
    
    public static LinkedHashSet<InetAddress> getLocalIpAddr2() {
		Enumeration<NetworkInterface> networkInterfaces;
		try {
			networkInterfaces = NetworkInterface.getNetworkInterfaces();
		} catch (SocketException e) {
			throw new UtilException(e);
		}
		if (networkInterfaces == null) {
			throw new UtilException("Get network interface error!");
		}
		final LinkedHashSet<InetAddress> ipSet = new LinkedHashSet<>();
		while (networkInterfaces.hasMoreElements()) {
			final NetworkInterface networkInterface = networkInterfaces.nextElement();
			final Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
			while (inetAddresses.hasMoreElements()) {
				final InetAddress inetAddress = inetAddresses.nextElement();
				// 只筛选ipv4地址,否则会同时得到Ipv6地址
				if (inetAddress instanceof Inet4Address) {
					//System.out.println(inetAddress.getHostAddress());
					if(!"127.0.0.1".equals(inetAddress.getHostAddress())) {
						ipSet.add(inetAddress);
					}
				}
			}
		}
		return ipSet;
    }
}
			
	      

 打赏        分享



评论

邮箱: 昵称:
\n