IP地址

对于ipv4地址: 192.168.1.3:
每段都用二进制表示: 192(10) = 11000000(2) ; 168(10) = 10101000(2) ; 1(10) = 00000001(2) ; 3(10) = 00000011(2) 。
所以连在一起就是:11000000101010000000000100000011,对应的int数字就是-1062731775 。

具体算法分析:
192左移24位: 11000000 00000000 00000000 00000000
168左移16位: 00000000 10101000 00000000 00000000
001左移08位: 00000000 00000000 00000001 00000000
003左移00位: 00000000 00000000 00000000 00000011
按位或的结果: 11000000 10101000 00000001 00000011
即 -1062731775
 

    /**
	 ** ipv4 地址转成long型数据
	 ** @Title: fmtStrTOLong
	 ** @Description: TODO
	 ** @param @param ipv4Addr 
	 ** @return void
	 ** @author CC
	 ** @throws
	 */
	public static long fmtStrToLong(String ipv4Addr){
		if(!validateIPV4Address(ipv4Addr)){
			throw new RuntimeException("Invalid IP Address");
		}
		
		// --- 匹配数字
		Pattern pattern = Pattern.compile("\\d+");
		Matcher matcher = pattern.matcher(ipv4Addr);
		long result = 0;
		long counter = 0;
        while(matcher.find()){
        	long value = Long.parseLong(matcher.group());
        	// --- 向左侧的偏移量
        	result = (value << 8 * (3-counter++)) | result;
        }
        
        return result;
	}
	
	/**
	 ** 将Long转换成ipv4地址
	 ** @Title: fmtLongToStr
	 ** @Description: TODO
	 ** @param @param ipv4Addr
	 ** @param @return 
	 ** @return String
	 ** @author CC
	 ** @throws
	 */
	public static String fmtLongToStr(long ipv4Addr){
		StringBuilder strBuilder = new StringBuilder();
		long num = 0;
		// --- 间隔.
		boolean isNeedPoint = false;
		for(int i = 0; i < 4; i++){
			if(isNeedPoint){
				strBuilder.append('.');
			}
			
			isNeedPoint = true;
			int offset = 8 * (3 - i);
			num = (ipv4Addr >> offset) & 0xff;
			
			strBuilder.append(num);
		}
		
		return strBuilder.toString();
	}
	
	/**
	 ** 验证是否是IP4地址
	 ** @Title: validateIPV4Address
	 ** @Description: TODO
	 ** @param @param ipV4Addr
	 ** @param @return 
	 ** @return boolean
	 ** @author CC
	 ** @throws
	 */
	public static boolean validateIPV4Address(String ipV4Addr){
		
		try {
			String lower = "(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])";
			String regex = lower + "(\\." + lower + "){3}";
			Pattern pattern = Pattern.compile(regex);
			Matcher matcher = pattern.matcher(ipV4Addr);
			return matcher.matches();
		} catch (Exception e) {
			_LOG.info("{IPV4地址验证异常! e:"+JSONObject.toJSONString(e)+"}");
			e.printStackTrace();
		}
		
		return false;
	}

 

转载于:https://my.oschina.net/u/2609570/blog/1524289

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值