现在的位置: 首页 > 综合 > 正文

【猪猪-后端】过滤IP格式工具类,将IP地址格式化,开发必备工具。

2017年12月04日 ⁄ 综合 ⁄ 共 1164字 ⁄ 字号 评论关闭

原文:【猪猪-后端】过滤IP格式工具类,将IP地址格式化,开发必备工具。

源代码下载地址:http://www.zuidaima.com/share/1550463556340736.htm

通常我们在开发中会遇到如下情况,IP:192.168.000.001,存放到数据库时我们需要,192.168.0.1,此时就需要过滤IP进行格式化。【猪猪-后端】过滤IP格式工具类,将IP地址格式化,开发必备工具。

package com.zuidaima.service.util;
/**
 * 
 * @author www.zuidaima.com
 *
 */
public class IPFormat {
	public static void main(String[] args) {
		IPFormat ipFormat=new IPFormat();
		System.out.println("原始IP:192.168.000.001,转换结果:"+ipFormat.IPFormatTo0("192.168.000.001"));
		System.out.println("原始IP:192.168.0.1,转换结果:"+ipFormat.IPFormatTo000("192.168.0.1"));
	}
	
	public static String IPFormatTo0(String ipAddress){
		String[] strs = ipAddress.split("\\."); 
		int ip1 = Integer.valueOf(strs[0]).intValue(); 
		int ip2 = Integer.valueOf(strs[1]).intValue(); 
		int ip3 = Integer.valueOf(strs[2]).intValue(); 
		int ip4= Integer.valueOf(strs[3]).intValue(); 

		String ip=String.format("%1$01d.%2$01d.%3$01d.%4$01d", ip1,ip2,ip3,ip4);
		return ip;
	}
	
	public static String IPFormatTo000(String ipAddress){
		String[] strs = ipAddress.split("\\."); 
		int ip1 = Integer.valueOf(strs[0]).intValue(); 
		int ip2 = Integer.valueOf(strs[1]).intValue(); 
		int ip3 = Integer.valueOf(strs[2]).intValue(); 
		int ip4= Integer.valueOf(strs[3]).intValue(); 

		String ip=String.format("%1$03d.%2$03d.%3$03d.%4$03d", ip1,ip2,ip3,ip4);
		return ip;
	}
	
	
}

	    			

抱歉!评论已关闭.