通过网卡获取IP真实地址信息



import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.quyougame.omp.sso.client.util.StringUtil;

/**
 * ip地址处理工具
 * @author Tseng  2015-9-10
 *
 */
public class IPUtil {
	
	/**
	 * 获取请求ip地址。
	 * 
	 * @param request
	 * @return
	 */
	public static String getRemoteAdd(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 ("0:0:0:0:0:0:0:1".equals(ip)) {
			InetAddress inet = null;
			try {
				inet = InetAddress.getLocalHost();
			} catch (UnknownHostException e) {
				e.printStackTrace();
			}
			ip = inet.getHostAddress();
		}
		return ip.trim();
	}
	
	/**
	 * 将IP转换为long类型
	 * Tseng 2015-9-10
	 * @param ip
	 * @return
	 */
	public static long ipToLong(String ip){
		long result = 0;
		if(!StringUtil.isEmpty(ip)){
			ip = ip.trim();
			String[] ipstr = ip.split("\\.");
			
			for (int i = 0; i < ipstr.length; i++) {
				int n = Integer.parseInt(ipstr[i]);
				result += n << (24 - i*8);
			}
			if(result < 0){
				result = Long.parseLong("4294967296") + result;
			}
		}else{
			result = 0;
		}
		
		return result;
	}


    public static boolean isWindows() {
		String osName = System.getProperty("os.name");
		if (osName.toLowerCase().indexOf("windows") != -1) {
			return true;
		}
		return false;
	}
	
	//获取本机IP
	/**
	 * 1、Windows平台下获得本机ip地址
	 * 2、Linux平台下获得本机ip地址。由于和Windows平台不同,不能用经典的方式查看。 
	 * 		但是可以通过查询网络接口(NetworkInterface)的方式来实现。 
	 * 		本程序中同样运用了JAVA核心技术:枚举类型。 
	 * 		枚举类型不仅可以使程序员少写某些代码,主要还提供了编译时的安全检查,可以很好的解决类安全问题。 
	 *  @Tseng 2016-1-21 
	 */
	public static String ipIsLinuxOrWindows() {
		String return_ip = "";
		InetAddress ip = null;
		try {
			// 如果是Windows操作系统,多个IP地址时把虚拟机的IP地址剔除掉
			if (isWindows()) {
//				ip = InetAddress.getLocalHost();
//				System.out.println(ip);  //打印网端名字  
				List<NetCard> cards = NetworkCardScan.getNetCards();//获取网卡信息:网卡名称,网卡对应的ip范围
				for (NetCard card : cards) {
					//System.out.println(card.getNetcard() + "--" + card.getNetcardIp() + "--" + card.getNetcardIpRange() + "--" + card.getNetcardName()); 
					int inde = (card.getNetcardName().toString().toUpperCase()).indexOf(("VM")) ;
					if(inde == -1){
						return_ip += card.getNetcardIp() + "," ;
					}
				}
				return_ip = return_ip.substring(0, return_ip.length()-1);
			} else {
				// 如果是Linux操作系统
				boolean bFindIP = false;
				//获得网络接口  
				Enumeration<NetworkInterface> netInterfaces = (Enumeration<NetworkInterface>) NetworkInterface.getNetworkInterfaces();
				//遍历所有的网络接口  
				while (netInterfaces.hasMoreElements()) {
					if (bFindIP) {
						break;
					}
					NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
					// ----------特定情况,可以考虑用ni.getName判断
					// 遍历所有ip
					Enumeration<InetAddress> ips = ni.getInetAddresses();//同样再定义网络地址枚举类  
					while (ips.hasMoreElements()) {
						ip = (InetAddress) ips.nextElement();
						if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() // 127.开头的都是lookback地址
								&& ip.getHostAddress().indexOf(":") == -1) {
					    if (ip != null && (ip instanceof Inet4Address)) //InetAddress类包括Inet4Address和Inet6Address  
							bFindIP = true;
							break;
						}
					}
				}
				if (null != ip) {
					return_ip = ip.getHostAddress();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return return_ip;
	} 
	
	public static void main(String[] args) {
		System.out.println(ipIsLinuxOrWindows());
	}

}

 


import java.io.Serializable;

public class NetCard implements Serializable {
	private static final long serialVersionUID = 1L;
	private String netcardName;
	private String netcardIp;
	private String netcardIpRange;
	private String netcard;

	public String getNetcardName() {
		return this.netcardName;
	}

	public void setNetcardName(String netcardName) {
		this.netcardName = netcardName;
	}

	public String getNetcard() {
		return this.netcard;
	}

	public void setNetcard(String netcard) {
		this.netcard = netcard;
	}

	public String getNetcardIp() {
		return this.netcardIp;
	}

	public void setNetcardIp(String netcardIp) {
		this.netcardIp = netcardIp;
	}

	public String getNetcardIpRange() {
		return this.netcardIpRange;
	}

	public void setNetcardIpRange(String netcardIpRange) {
		this.netcardIpRange = netcardIpRange;
	}
}

 


import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class NetworkCardScan {
	public static List<NetCard> getNetCards() {
		List<NetCard> netCards = new ArrayList<>();
		try {
			Enumeration<NetworkInterface> el = NetworkInterface.getNetworkInterfaces();
			Enumeration<InetAddress> ipArray;
			label254: for (; el.hasMoreElements(); ipArray.hasMoreElements()) {
				NetworkInterface e = (NetworkInterface) el.nextElement();

				if ((!e.isUp()) || (e.isLoopback()))
					break label254;
				ipArray = e.getInetAddresses();
				continue;
				/*
				 * InetAddress temp = (InetAddress) ipArray.nextElement(); if
				 * (temp.getAddress().length == 4) { byte[] array = temp.getAddress(); String
				 * ipAddress = String.format("%d.%d.%d.%d", new Object[] {
				 * Integer.valueOf(array[0] & 0xFF), Integer.valueOf(array[1] & 0xFF),
				 * Integer.valueOf(array[2] & 0xFF), Integer.valueOf(array[3] & 0xFF) });
				 * NetCard card = new NetCard(); card.setNetcardIp(ipAddress);
				 * card.setNetcardName(e.getDisplayName()); String ipRange =
				 * String.format("%d.%d.%d.1-254", new Object[] { Integer.valueOf(array[0] &
				 * 0xFF), Integer.valueOf(array[1] & 0xFF), Integer.valueOf(array[2] & 0xFF) });
				 * card.setNetcardIpRange(ipRange); card.setNetcard(e.getName());
				 * netCards.add(card); }
				 */

			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		if (netCards.size() == 0) {
			netCards = NetworkCardScanOther.getNetCardInfoByCommand();
		}
		return netCards;
	}

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NetworkCardScanOther {
	private static String convertStream(InputStream is) throws IOException {
		StringBuffer outputBuffer = new StringBuffer();
		BufferedReader streamReader = new BufferedReader(new InputStreamReader(is, Charset.forName("GBK")));
		String output;
		while ((output = streamReader.readLine()) != null) {
			outputBuffer.append(output);
			outputBuffer.append("\n");
		}
		return outputBuffer.toString();
	}

	public static int statisticStrInStringCount(String orgStr, String targetStr) {
		int count = 0;
		int index = 0;
		int currentPosition = 0;
		while ((currentPosition = orgStr.indexOf(targetStr, index)) != -1) {
			index += currentPosition;
			count++;
		}
		return count;
	}

	public static boolean isIpv4(String ipAddress) {
		String ip = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\.(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\.(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\.(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
		Pattern pattern = Pattern.compile(ip);
		Matcher matcher = pattern.matcher(ipAddress);
		return matcher.matches();
	}

	public static List<NetCard> getNetCardInfoByCommand() {
		List<NetCard> cards = new ArrayList<>();
		String command = "ipconfig /all";
		try {
			Process process = Runtime.getRuntime().exec(command);
			String content = convertStream(process.getInputStream());

			String[] array = content.split("连接特定");

			if (array.length == 1) {
				array = content.split("Connection-specific");
			}

			for (int i = 0; i < array.length; i++) {
				if ((array[i].contains("IPv4")) || (array[i].contains("IP Address"))) {
					String[] pArray = array[i].split("\n");

					if (pArray.length == 1) {
						pArray = array[i].split("        ");
					}

					String desc = "";
					String mac = "";
					for (int j = 0; j < pArray.length; j++) {
						if ((pArray[j].contains("描述"))
								|| (pArray[j].toUpperCase().contains("Description".toUpperCase()))) {
							desc = pArray[j].substring(pArray[j].indexOf(":") + 1, pArray[j].length());
							desc = desc.replaceAll("\\(首选\\)", "");
						}

						if ((pArray[j].contains("物理地址"))
								|| (pArray[j].toUpperCase().contains("Physical Address".toUpperCase()))) {
							mac = pArray[j].substring(pArray[j].indexOf(":") + 1, pArray[j].length());
							mac = mac.replaceAll("\\(首选\\)", "");
							mac = mac.replaceAll(" ", "");
						}

					}

					for (int j = 0; j < pArray.length; j++) {
						if ((pArray[j].contains("IPv4"))
								|| (pArray[j].toUpperCase().contains("IP Address".toUpperCase()))) {
							NetCard tempCard = new NetCard();
							String ip = pArray[j].substring(pArray[j].indexOf(":") + 1, pArray[j].length());
							ip = ip.replaceAll("\\(首选\\)", "");
							ip = ip.replaceAll(" ", "");
							try {
								String[] ipArray = ip.split("\\.");

								if (ipArray.length == 4) {
									Integer.parseInt(ipArray[0]);
									Integer.parseInt(ipArray[1]);
									Integer.parseInt(ipArray[2]);
									Integer.parseInt(ipArray[3]);
									String ipRange = String.format("%s.%s.%s.1-254",
											new Object[] { ipArray[0], ipArray[1], ipArray[2] });

									tempCard.setNetcardName(desc != null ? desc.trim() : "");
									tempCard.setNetcardIp(ip);
									tempCard.setNetcardIpRange(ipRange);
									cards.add(tempCard);
								}

							} catch (Exception localException) {
							}
						}

					}

				}

			}

		} catch (IOException e) {
			e.printStackTrace();
		}
		return cards;
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值