/**
 * 
 */
package cn.strong.leke.core.ip;

import java.util.ArrayList;

import org.springframework.util.Assert;

/**
 * IPv4 地址定位器
 * 
 * @author liulongbiao
 *
 */
public class IPv4Locator {

	private final ArrayList<IPv4Entry> entries; // 有序的IP地址范围条目

	public IPv4Locator(ArrayList<IPv4Entry> entries) {
		Assert.notNull(entries);
		this.entries = entries;
	}

	/**
	 * 找到 IP 所对应的地址和运营商信息
	 * 
	 * @param ip
	 * @return
	 */
	public IPv4Loc locate(IPv4 ip) {
		Assert.notNull(ip);
		int idx = binarySearch(entries, ip);
		return idx >= 0 ? entries.get(idx).loc : IPv4Loc.UNKNOWN;
	}

	/*
	 * 二叉搜索包含该IP的IP范围条目索引值
	 */
	private static int binarySearch(ArrayList<IPv4Entry> entries, IPv4 ip) {
		int low = 0;
		int high = entries.size() - 1;

		while (low <= high) {
			int mid = (low + high) >>> 1;
			IPv4Entry midEntry = entries.get(mid);

			if (ip.compareTo(midEntry.begin) < 0) {
				high = mid - 1;
			} else if (ip.compareTo(midEntry.end) > 0) {
				low = mid + 1;
			} else {
				return mid; // key found
			}
		}
		return -(low + 1); // key not found
	}
}

@@ -352,24 +352,197 @@
  entries;%0A%09%7D
+%0A%09%0A%09/**%0A%09 * %E6%A0%B9%E6%8D%AE IPv4 %E5%9C%B0%E5%9D%80%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%9F%A5%E6%89%BE%E5%AF%B9%E5%BA%94%E7%9A%84%E5%9C%B0%E5%9D%80%E5%92%8C%E8%BF%90%E8%90%A5%E5%95%86%E4%BF%A1%E6%81%AF%0A%09 * %0A%09 * @param ipv4Address%0A%09 * @return%0A%09 */%0A%09public IPv4Loc locate(String ipv4Address) %7B%0A%09%09return locate(IPv4.parse(ipv4Address));%0A%09%7D
 %0A%0A%09/**%0A%09 * %E6%89%BE

add locate by ipv4 string