Java:判断IP4地址合法性

Java:判断IP4地址合法性

一、判断IP4地址是否是合法地址

         1. 最容易理解的方式

	public static boolean validIP(String ip) {
		try {
			if (ip == null || ip.isEmpty()) {
				return false;
			}

			String[] parts = ip.split("\\.");
			if (parts.length != 4) {
				return false;
			}

			for (String s : parts) {
				int i = Integer.parseInt(s);
				if ((i < 0) || (i > 255)) {
					return false;
				}
			}
			if (ip.endsWith(".")) {
				return false;
			}

			return true;
		} catch (NumberFormatException nfe) {
			return false;
		}
	}

         2. 正则表达式判断

	public static boolean validIP(String ip) {
		if (ip == null || ip.isEmpty())
			return false;
		ip = ip.trim();
		if ((ip.length() < 6) & (ip.length() > 15))
			return false;

		try {
			String rule = "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.)" + 
						  "{3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
			Pattern pattern = Pattern.compile(rule);
			Matcher matcher = pattern.matcher(ip);
			return matcher.matches();
		} catch (PatternSyntaxException ex) {
			return false;
		}
	}

         3. 使用commons-validator中的方法判断

	public static boolean validIP(String ip) {
		return InetAddressValidator.getInstance().isValidInet4Address(ip);
	}

二、IP与整数之间相互转换

1. IP地址转换成整数

方法1:

	public static long ip2long(String ip) {
		String[] ipArray = ip.split("\\.");

		long result = 0;
		for (int i = 0; i < ipArray.length; i++) {
			int power = 3 - i;
			result += (Integer.parseInt(ipArray[i]) % 256 * Math.pow(256, power));
		}

		return result;
	}
方法2:
	public static long ip2long(String ip) {
		long result = 0;
		String[] ipAddressInArray = ip.split("\\.");
		
		for (int i = 3; i >= 0; i--) {
			long temp = Long.parseLong(ipAddressInArray[3 - i]);
			result |= temp << (i * 8);
		}
		
		return result;
	}
2. 整数转换成IP地址

方法1:

	public static String long2ip(long decimal) {
		StringBuffer result = new StringBuffer(15);
		for (int i = 0; i < 4; i++) {
			result.insert(0,Long.toString(decimal & 0xff));
			if (i < 3) {
				result.insert(0,'.');
			}
			decimal = decimal >> 8;
		}
		return result.toString();
	}

方法2:

	public static String long2ip(long decimal) {
		return ((decimal >> 24) & 0xFF) + "." + 
			   ((decimal >> 16) & 0xFF) + "." + 
			   ((decimal >> 8 ) & 0xFF) + "." + 
			   (decimal & 0xFF);
	}

三、判断IP地址是否在某个地址段内

	public static boolean isRange(String ip, String start, String end){
		long temp = ip2long(ip);
		long low = ip2long(start);
		long high = ip2long(end);
		
		return temp >= low && temp <= high;
	}


猜你喜欢

转载自blog.csdn.net/zitong00/article/details/47393231