Java获取客户端IP地址、MAC地址,根据IP获取地理位置信息代码

时间:2022-02-18 10:42:21

获取IP地址:

/**
	 * 获取用户端的IP地址
	 */
	public String getRealUserIP(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if(!StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            //多次反向代理后会有多个ip值,第一个ip才是真实ip
            int index = ip.indexOf(",");
            if(index != -1){
                return ip.substring(0,index);
            }else{
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if(!StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            return ip;
        }
        return request.getRemoteAddr();
    }


获取MAC地址:

方法1、

/**
     * 根据IP获取MAC地址(该方法仅支持win7系统 TODO)
     */
    public String getMACAddress(String ip) {
        String str = "";
        String macAddress = "";
        try {
            Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
            InputStreamReader ir = new InputStreamReader(p.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            for (int i = 1; i < 100; i++) {
                str = input.readLine();
                if (str != null) {
                    if (str.indexOf("MAC") > -1) {
                        macAddress = str.substring(str.indexOf("=") + 1, str.length()).trim();
                        break;
                    }
                }
            }
        }
        catch (IOException e) {
            e.printStackTrace(System.out);
        }
        return macAddress;
    }


方法2、

/**
	 * 获取MAC地址
	 */
	public String getMAC() {
        String mac = null;
        try {
            Process pro = Runtime.getRuntime().exec("cmd.exe /c ipconfig/all");
 
            InputStream is = pro.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String message = br.readLine();
 
            int index = -1;
            while (message != null) {
                if ((index = message.indexOf("Physical Address")) > 0) {
                    mac = message.substring(index + 36).trim();
                    break;
                }
                message = br.readLine();
            }
            System.out.println(mac);
            br.close();
            pro.destroy();
        } catch (IOException e) {
            System.out.println("Can't get mac address!");
            return null;
        }
        return mac;
    }

方法3、

/**
	 * 获取MAC地址
	 */
	public String getMac2(String ip){  
		String mac = "";
        try {  
        Process p = Runtime.getRuntime().exec("arp -n");  
            InputStreamReader ir = new InputStreamReader(p.getInputStream());  
            LineNumberReader input = new LineNumberReader(ir);  
            p.waitFor();  
            boolean flag = true;  
            String ipStr = "(" + ip + ")";  
            while(flag) {  
                String str = input.readLine();  
                if (str != null) {  
                    if (str.indexOf(ipStr) > 1) {  
                        int temp = str.indexOf("at");  
                        mac = str.substring(  
                        temp + 3, temp + 20);  
                        break;  
                    }  
                } else  
                flag = false;  
            }  
        } catch (IOException | InterruptedException e) {  
            e.printStackTrace(System.out);  
        }  
        return mac;  
    }  

根据IP获取地理位置信息:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

import net.sf.json.JSONObject;

/**
 * 根据IP地址获取详细的地域信息 淘宝API : http://ip.taobao.com/service/getIpInfo.php?ip=xxx.xxx.xxx.xxx 
 * 新浪API :http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=xxx.xxx.xxx.xxx 
 */
public class AddressUtils {
	/**
	 * 
	 * @param content
	 *            请求的参数 格式为:name=xxx&pwd=xxx
	 * @param encoding
	 *            服务器端请求编码。如GBK,UTF-8等
	 */
	public String getAddresses(String content, String encodingString) throws UnsupportedEncodingException {
		// 这里调用淘宝API
		String urlStr = "http://ip.taobao.com/service/getIpInfo.php"; 
		//新浪接口
		//String urlStr = "http://int.dpool.sina.com.cn/iplookup/iplookup.php";
		// 从http://whois.pconline.com.cn取得IP所在的省市区信息
		String returnStr = this.getResult(urlStr, content, encodingString);
		if (returnStr != null) {

			System.out.println(returnStr);
			String[] temp = returnStr.split(",");
			if (temp.length < 3) {
				return "0";// 无效IP,局域网测试
			}
			String region = (temp[5].split(":"))[1].replaceAll("\"", "");
			region = decodeUnicode(region);

			String country = "";
			String area = "";
			// String region = "";
			String city = "";
			String county = "";
			String isp = "";
			for (int i = 0; i < temp.length; i++) {
				switch (i) {
				case 1:
					country = (temp[i].split(":"))[2].replaceAll("\"", "");
					country = decodeUnicode(country);
					break;
				case 3:
					area = (temp[i].split(":"))[1].replaceAll("\"", "");
					area = decodeUnicode(area);
					break;
				case 5:
					region = (temp[i].split(":"))[1].replaceAll("\"", "");
					region = decodeUnicode(region);
					break;
				case 7:
					city = (temp[i].split(":"))[1].replaceAll("\"", "");
					city = decodeUnicode(city);
					break;
				case 9:
					county = (temp[i].split(":"))[1].replaceAll("\"", "");
					county = decodeUnicode(county);
					break;
				case 11:
					isp = (temp[i].split(":"))[1].replaceAll("\"", "");
					isp = decodeUnicode(isp);
					break;
				}
			}

			System.out.println(country + "=" + area + "=" + region + "=" + city + "=" + county + "=" + isp);
			return region;
		}
		return null;
	}

	/**
	 * @param urlStr
	 *            请求的地址
	 * @param content
	 *            请求的参数 格式为:name=xxx&pwd=xxx
	 * @param encoding
	 *            服务器端请求编码。如GBK,UTF-8等
	 * @return
	 */
	private String getResult(String urlStr, String content, String encoding) {
		URL url = null;
		HttpURLConnection connection = null;
		try {
			url = new URL(urlStr);
			connection = (HttpURLConnection) url.openConnection();// 新建连接实例
			connection.setConnectTimeout(2000);// 设置连接超时时间,单位毫秒
			connection.setReadTimeout(2000);// 设置读取数据超时时间,单位毫秒
			connection.setDoOutput(true);// 是否打开输出流 true|false
			connection.setDoInput(true);// 是否打开输入流true|false
			connection.setRequestMethod("POST");// 提交方法POST|GET
			connection.setUseCaches(false);// 是否缓存true|false
			connection.connect();// 打开连接端口
			DataOutputStream out = new DataOutputStream(connection.getOutputStream());// 打开输出流往对端服务器写数据
			out.writeBytes(content);// 写数据,也就是提交你的表单 name=xxx&pwd=xxx
			out.flush();// 刷新
			out.close();// 关闭输出流
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding));// 往对端写完数据对端服务器返回数据
			// ,以BufferedReader流来读取
			StringBuffer buffer = new StringBuffer();
			String line = "";
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			reader.close();
			return buffer.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
		return null;
	}

	/**
	 * unicode 转换成 中文
	 */
	public static String decodeUnicode(String theString) {
		char aChar;
		int len = theString.length();
		StringBuffer outBuffer = new StringBuffer(len);
		for (int x = 0; x < len;) {
			aChar = theString.charAt(x++);
			if (aChar == '\\') {
				aChar = theString.charAt(x++);
				if (aChar == 'u') {
					int value = 0;
					for (int i = 0; i < 4; i++) {
						aChar = theString.charAt(x++);
						switch (aChar) {
						case '0':
						case '1':
						case '2':
						case '3':
						case '4':
						case '5':
						case '6':
						case '7':
						case '8':
						case '9':
							value = (value << 4) + aChar - '0';
							break;
						case 'a':
						case 'b':
						case 'c':
						case 'd':
						case 'e':
						case 'f':
							value = (value << 4) + 10 + aChar - 'a';
							break;
						case 'A':
						case 'B':
						case 'C':
						case 'D':
						case 'E':
						case 'F':
							value = (value << 4) + 10 + aChar - 'A';
							break;
						default:
							throw new IllegalArgumentException("Malformed      encoding.");
						}
					}
					outBuffer.append((char) value);
				} else {
					if (aChar == 't') {
						aChar = '\t';
					} else if (aChar == 'r') {
						aChar = '\r';
					} else if (aChar == 'n') {
						aChar = '\n';
					} else if (aChar == 'f') {
						aChar = '\f';
					}
					outBuffer.append(aChar);
				}
			} else {
				outBuffer.append(aChar);
			}
		}
		return outBuffer.toString();
	}

	/**
	 * 测试方法
	 * @param ip
	 * @throws Exception
	 */
	public void getAddressByIp(String ip) throws Exception {
		// 参数ip
		//String ip = "219.136.134.157";
		// json_result用于接收返回的json数据
		String json_result = null;
		try {
			json_result = new AddressUtils().getAddresses("format=js&ip=" + ip, "gbk");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		JSONObject json = JSONObject.fromObject(json_result);
		System.out.println("json数据: " + json);
		String country = JSONObject.fromObject(json.get("data")).get("country").toString();
		String region = JSONObject.fromObject(json.get("data")).get("region").toString();
		String city = JSONObject.fromObject(json.get("data")).get("city").toString();
		String county = JSONObject.fromObject(json.get("data")).get("county").toString();
		String isp = JSONObject.fromObject(json.get("data")).get("isp").toString();
		String area = JSONObject.fromObject(json.get("data")).get("area").toString();
		System.out.println("国家: " + country);
		System.out.println("地区: " + area);
		System.out.println("省份: " + region);
		System.out.println("城市: " + city);
		System.out.println("区/县: " + county);
		System.out.println("互联网服务提供商: " + isp);

		String address = country + "/";
		address += region + "/";
		address += city + "/";
		address += county;
		System.out.println(address);
	}

	public static void main(String[] args) {
		AddressUtils addressUtils = new AddressUtils();
		String address = "";
		try {
			addressUtils.getAddressByIp("192.168.108.208");
		} catch (Exception e) {

			e.printStackTrace();
		}
		System.out.println(address);
	}
}