获取客户端IP并判断内外网

package com.jason.utils;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;

public class AppUtil { 
	/**
	  * 获取客户端IP 
	  * @param request
	  * @return
	*/
	public static String getClientIp(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();
	      }
	      if(ip == null){
			  ip = "192.168.123.321";
		  }
	      return ip;
	}
    /**
     * 是否为外网 
     * @param ipAddress
     * @return
     */
	public static Integer getIpType(String ipAddress)
	{
		Integer ipType;
		Pattern p = Pattern.compile("^((192.168.)|(10.)|(172.16)|(127.0))+[0-9.]+$");		
		if(p.matcher(ipAddress).matches()) {
			ipType = 1;
		}else {
			ipType = 2;
		}
		return ipType;
	}
	
	/**
	 * 获取客户端IP对应网卡的MAC地址
	 * @param ipAddress
	 * @return
	 */
	 public static String getMACAddress(String ipAddress) { 
			String str = "", strMAC = "", macAddress = ""; 
			try { 
				Process pp = Runtime.getRuntime().exec("nbtstat -a " + ipAddress); 
				InputStreamReader ir = new InputStreamReader(pp.getInputStream()); 
				LineNumberReader input = new LineNumberReader(ir); 
				for (int i = 1; i < 100; i++) { 
					str = input.readLine(); 
					if (str != null) { 
						if (str.indexOf("MAC Address") > 1) { 
							strMAC = str.substring(str.indexOf("MAC Address") + 14, 
							str.length()); 
							break; 
						} 
					} 
				} 
			} catch (IOException ex) { 
				return "Can't Get MAC Address!"; 
			} 
			if (strMAC.length() < 17) { 
				return "Error!"; 
			} 
			
			macAddress = strMAC.substring(0, 2) + ":" + strMAC.substring(3, 5) 
			+ ":" + strMAC.substring(6, 8) + ":" + strMAC.substring(9, 11) 
			+ ":" + strMAC.substring(12, 14) + ":" 
			+ strMAC.substring(15, 17); 
			return macAddress; 
		}
	 /**
	  * main
	  * @param args
	  */
	 public static void main(String[] args) {
			Integer ty = getIpType("127.0.0.1");
			if(ty==1){
				System.out.println("内网");
			}else{
				System.out.println("外网");
			}
			System.out.println(getMACAddress("192.168.218.159"));
		}
}

posted @ 2012-11-09 17:34  問天  阅读(174)  评论(0编辑  收藏  举报