zoukankan      html  css  js  c++  java
  • 获取IP地址

    获取本机ip

    public static String localIp(){  
            String ip = null;  
            Enumeration allNetInterfaces;  
            try {  
                allNetInterfaces = NetworkInterface.getNetworkInterfaces();              
                while (allNetInterfaces.hasMoreElements()) {  
                    NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();  
                    List<InterfaceAddress> InterfaceAddress = netInterface.getInterfaceAddresses();  
                    for (InterfaceAddress add : InterfaceAddress) {  
                        InetAddress Ip = add.getAddress();  
                        if (Ip != null && Ip instanceof Inet4Address) {  
                            ip = Ip.getHostAddress();  
                        }  
                    }  
                }  
            } catch (SocketException e) {  
            lg.warn("获取本机Ip失败:异常信息:"+e.getMessage());  
            }  
            return ip;  
        }  
    

      

    获取用户ip

    public static String getUserIp() {
    		HttpServletRequest request = getHttpServletRequest();
    		String ipAddress = null;
    		// ipAddress = this.getRequest().getRemoteAddr();
    		ipAddress = request.getHeader("x-forwarded-for");
    		if (ipAddress == null || ipAddress.length() == 0
    				|| "unknown".equalsIgnoreCase(ipAddress)) {
    			ipAddress = request.getHeader("Proxy-Client-IP");
    		}
    		if (ipAddress == null || ipAddress.length() == 0
    				|| "unknown".equalsIgnoreCase(ipAddress)) {
    			ipAddress = request.getHeader("WL-Proxy-Client-IP");
    		}
    		if (ipAddress == null || ipAddress.length() == 0
    				|| "unknown".equalsIgnoreCase(ipAddress)) {
    			ipAddress = request.getRemoteAddr();
    			if (ipAddress.equals("127.0.0.1")
    					|| ipAddress.equals("0:0:0:0:0:0:0:1")) {
    				// 根据网卡取本机配置的IP
    				InetAddress inet = null;
    				try {
    					inet = InetAddress.getLocalHost();
    				} catch (UnknownHostException e) {
    					e.printStackTrace();
    				}
    				ipAddress = inet.getHostAddress();
    			}
    
    		}
    
    		// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
    		if (ipAddress != null && ipAddress.length() > 15) {
    			if (ipAddress.indexOf(",") > 0) {
    				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
    			}
    		}
    		return ipAddress;
    	}

  • 相关阅读:
    sessionid如何产生?由谁产生?保存在哪里?
    springmvc原理
    java基础面试题
    mysql数据库去重复
    git安装和初次使用
    String的按值传递,java传参都是传值
    sublime Text3使用笔记
    git命令使用记录
    Git:错误:error:src refspec master does not match any
    java并发编程实战学习(3)--基础构建模块
  • 原文地址:https://www.cnblogs.com/HHR-SUN/p/10563874.html
Copyright © 2011-2022 走看看