---
title: "ip(58.246.0.0 - 58.247.255.255)到(58.246.0.0/15)的转换"
author: "codeall"
date: "2009-05-12T12:32:35Z"
tags: []
slug: "ip-58-246-0-0-58-247-255-255-58-246-0-0-15"
draft: false
lastmod: "2009-05-12T12:32:35Z"
id: 384127
url: "https://codeall.iteye.com/blog/384127"
---

对于恰好用一个掩码表示的段, 返回一个段, 例如
> 58.246.0.0 - 58.247.255.255
 -> 
> 58.246.0.0/15

对于不能用一个掩码表示的端, 会返回一系列段. 例如
> 0.0.0.0 - 0.0.5.128
 -> 
> 0.0.0.0/22;0.0.4.0/24;0.0.5.0/25;0.0.5.128/32;



```java

	public static long ip2long(String strIP) {
		try {
			long[] ip = new long[4];
			int position1 = strIP.indexOf(".");
			int position2 = strIP.indexOf(".", position1 + 1);
			int position3 = strIP.indexOf(".", position2 + 1);

			ip[0] = Long.parseLong(strIP.substring(0, position1));
			ip[1] = Long.parseLong(strIP.substring(position1 + 1, position2));
			ip[2] = Long.parseLong(strIP.substring(position2 + 1, position3));
			ip[3] = Long.parseLong(strIP.substring(position3 + 1));
			return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3];
		} catch (Exception e) {
			return 0;
		}
	}

	public static String long2ip(long longIP) {
		return new StringBuffer(String.valueOf(longIP >>> 24)).append(".")
			.append(String.valueOf((longIP & 0x00FFFFFF) >>> 16)).append(".")
			.append(String.valueOf((longIP & 0x0000FFFF) >>> 8)).append(".")
			.append(String.valueOf(longIP & 0x000000FF)).toString();
	}

	public static Map<String, Integer> ipBlock2mask(String startIps, String endIps) {
		Map<String, Integer> blocks = new LinkedHashMap<String, Integer>();
		int mask = 32;
		long startIp = ip2long(startIps), endIp = ip2long(endIps) + 1;
		while (true) {
			if (startIp + new Double(Math.pow(2, 32 - mask)).longValue() > endIp) {
				// found the mask
				mask++;
				blocks.put(startIps, mask);
				long newStartIp = startIp + new Double(Math.pow(2, 32 - mask)).longValue();
				if (newStartIp >= endIp) {
					break; // exit all
				} else {
					startIp = newStartIp;
					startIps = long2ip(startIp);
					mask = 32;
				}
			}
			mask--;
		}
		return blocks;
	}
	
	// 0.0.0.0 - 0.0.5.128 => 0.0.0.0/22;0.0.4.0/24;0.0.5.0/25;0.0.5.128/32;
	// 0.0.0.0 - 0.0.5.255 => 0.0.0.0/22;0.0.4.0/23;
	public static String ipBlock2maskString(String startIps, String endIps) {
		Map<String, Integer> blocks = ipBlock2mask(startIps, endIps);
		StringBuilder sb = new StringBuilder();
		for (Map.Entry<String, Integer> entry : blocks.entrySet()) {
			sb.append(entry.getKey()).append("/").append(entry.getValue()).append(";");
		}
		return sb.toString();
	}

```