原文:http://blog.csdn.net/chwshuang/article/details/78027873?locationNum=10&fps=1

Java使用纯真IP库获取IP对应省份和城市

项目上接到一个需求,按照用户IP地址判断用户省份、城市,来展示不同的内容。在网上进行选型的时候,有几个选择

开源免费的IP库选型


  1. GeoIP2 GeoLite2开源免费的数据库

    MaxMind作为一家私营企业,总部设于美国马萨诸塞州的沃尔瑟姆。MaxMind公司成立于2002年,是领先业界的IP智能与在线欺诈检测工具供应商。有兴趣的可以访问官方网站了解。

    这个IP库的特点是免费,全球支持比较好,国外的IP应该比较全,国内的IP地址获取率不高,获取后的准确率也不高,公司网站上使用过一段时间,我统计过,国内地址获取率80%左右,而这80%里与淘宝的IP进行对比的准确率只有60%~80%,所以,整体的成功率只有65%以下,所以上线一段时间就没有用了。

  2. 淘宝IP库

    淘宝IP库只能通过Http方式查询IP,没有提供本地库的方式,遇到实时处理系统,肯定是不行,解决方案是建一个缓存和一个队列,如果缓存中没有的IP,就放到队列,然后用一个线程单独去队列中把要查询地址的IP通过Http的方式获取。

    淘宝IP库的特点是准确,官方宣称的省级准确率达到99.14%。缺点就是只提供线上的Rest API,而且线上的Rest API有请求限制,如果你写个程序一直请求,每个请求返回的间隔是30秒!所以不适合实时的场景用。

  3. 纯真IP库

    纯真IP库是国人开源的一个IP库,支持多语言的,它的格式是公开的,所以,你可以将它用在目前主流的开发语言的项目中。纯真IP库的获取率是99.99%,除非是本地内网IP,比如以192.168开头的一些IP会不认,而这个是没有影响的。而淘宝IP库比较有意思的是会返回本地IP这个地区描述。纯真库还有一个最大的好处,就是它在定期更新,且比较频繁,最新更新时间是几天前2017年9月15号。使用过程中库更新也比较方便,直接更新项目上的库文件,然后重启服务即可。当然,你也可以让程序手动或者自动定时触发更新。

    纯真IP库需要在Window的操作系统上安装程序,然后在安装目录(默认是 ?\cz88.net\ip\)找到qqwry.dat这个文件, 这个就是压缩后的IP本地库



.

纯真IP库使用


上面纯真IP介绍里已经说过怎么获取IP库文件,下面再说如何使用

  1. 创建一个本地对象
  1. public class IPLocation {
  2. /**
  3. * 国家
  4. */
  5. private String country;
  6. /**
  7. * 区域 - 省份 + 城市
  8. */
  9. private String area;
  10. public IPLocation() {
  11. country = area = "";
  12. }
  13. public synchronized IPLocation getCopy() {
  14. IPLocation ret = new IPLocation();
  15. ret.country = country;
  16. ret.area = area;
  17. return ret;
  18. }
  19. public String getCountry() {
  20. return country;
  21. }
  22. public String getCity() {
  23. String city = "";
  24. if(country != null){
  25. String[] array = country.split("省");
  26. if(array != null && array.length > 1){
  27. city = array[1];
  28. } else {
  29. city = country;
  30. }
  31. if(city.length() > 3){
  32. city.replace("内蒙古", "");
  33. }
  34. }
  35. return city;
  36. }
  37. public void setCountry(String country) {
  38. this.country = country;
  39. }
  40. public String getArea() {
  41. return area;
  42. }
  43. public void setArea(String area) {
  44. //如果为局域网,纯真IP地址库的地区会显示CZ88.NET,这里把它去掉
  45. if(area.trim().equals("CZ88.NET")){
  46. this.area="本机或本网络";
  47. }else{
  48. this.area = area;
  49. }
  50. }
  51. }
  1. 创建工具类
  1. import org.slf4j.Logger;
  2. import org.slf4j.LoggerFactory;
  3. import java.io.UnsupportedEncodingException;
  4. import java.util.StringTokenizer;
  5. /**
  6. * 工具类,提供IP字符串转数组的方法
  7. */
  8. public class Util {
  9. private static final Logger log = LoggerFactory.getLogger(CZIPUtils.class);
  10. private static StringBuilder sb = new StringBuilder();
  11. /**
  12. * 从ip的字符串形式得到字节数组形式
  13. *
  14. * @param ip 字符串形式的ip
  15. * @return 字节数组形式的ip
  16. */
  17. public static byte[] getIpByteArrayFromString(String ip) {
  18. byte[] ret = new byte[4];
  19. StringTokenizer st = new StringTokenizer(ip, ".");
  20. try {
  21. ret[0] = (byte) (Integer.parseInt(st.nextToken()) & 0xFF);
  22. ret[1] = (byte) (Integer.parseInt(st.nextToken()) & 0xFF);
  23. ret[2] = (byte) (Integer.parseInt(st.nextToken()) & 0xFF);
  24. ret[3] = (byte) (Integer.parseInt(st.nextToken()) & 0xFF);
  25. } catch (Exception e) {
  26. log.error("从ip的字符串形式得到字节数组形式报错" + e.getMessage(), e);
  27. }
  28. return ret;
  29. }
  30. /**
  31. * 字节数组IP转String
  32. * @param ip ip的字节数组形式
  33. * @return 字符串形式的ip
  34. */
  35. public static String getIpStringFromBytes(byte[] ip) {
  36. sb.delete(0, sb.length());
  37. sb.append(ip[0] & 0xFF);
  38. sb.append('.');
  39. sb.append(ip[1] & 0xFF);
  40. sb.append('.');
  41. sb.append(ip[2] & 0xFF);
  42. sb.append('.');
  43. sb.append(ip[3] & 0xFF);
  44. return sb.toString();
  45. }
  46. /**
  47. * 根据某种编码方式将字节数组转换成字符串
  48. *
  49. * @param b 字节数组
  50. * @param offset 要转换的起始位置
  51. * @param len 要转换的长度
  52. * @param encoding 编码方式
  53. * @return 如果encoding不支持,返回一个缺省编码的字符串
  54. */
  55. public static String getString(byte[] b, int offset, int len, String encoding) {
  56. try {
  57. return new String(b, offset, len, encoding);
  58. } catch (UnsupportedEncodingException e) {
  59. return new String(b, offset, len);
  60. }
  61. }
  62. }
  1. 创建工具类
  1. import org.slf4j.Logger;
  2. import org.slf4j.LoggerFactory;
  3. import java.io.File;
  4. import java.io.FileNotFoundException;
  5. import java.io.IOException;
  6. import java.io.RandomAccessFile;
  7. import java.nio.MappedByteBuffer;
  8. import java.util.Map;
  9. import java.util.concurrent.ConcurrentHashMap;
  10. /**
  11. * IP地址服务
  12. */
  13. public class IPAddressUtils {
  14. private static Logger log = LoggerFactory.getLogger(IPAddressUtils.class);
  15. /**
  16. * 纯真IP数据库名
  17. */
  18. private String IP_FILE="qqwry.dat";
  19. /**
  20. * 纯真IP数据库保存的文件夹
  21. */
  22. private String INSTALL_DIR="/test/";
  23. /**
  24. * 常量,比如记录长度等等
  25. */
  26. private static final int IP_RECORD_LENGTH = 7;
  27. /**
  28. * 常量,读取模式1
  29. */
  30. private static final byte REDIRECT_MODE_1 = 0x01;
  31. /**
  32. * 常量,读取模式2
  33. */
  34. private static final byte REDIRECT_MODE_2 = 0x02;
  35. /**
  36. * 缓存,查询IP时首先查询缓存,以减少不必要的重复查找
  37. */
  38. private Map<String, IPLocation> ipCache;
  39. /**
  40. * 随机文件访问类
  41. */
  42. private RandomAccessFile ipFile;
  43. /**
  44. * 内存映射文件
  45. */
  46. private MappedByteBuffer mbb;
  47. /**
  48. * 起始地区的开始和结束的绝对偏移
  49. */
  50. private long ipBegin, ipEnd;
  51. /**
  52. * 为提高效率而采用的临时变量
  53. */
  54. private IPLocation loc;
  55. /**
  56. * 为提高效率而采用的临时变量
  57. */
  58. private byte[] buf;
  59. /**
  60. * 为提高效率而采用的临时变量
  61. */
  62. private byte[] b4;
  63. /**
  64. * 为提高效率而采用的临时变量
  65. */
  66. private byte[] b3;
  67. /**
  68. * IP地址库文件错误
  69. */
  70. private static final String BAD_IP_FILE = "IP地址库文件错误";
  71. /**
  72. * 未知国家
  73. */
  74. private static final String UNKNOWN_COUNTRY = "未知国家";
  75. /**
  76. * 未知地区
  77. */
  78. private static final String UNKNOWN_AREA = "未知地区";
  79. public void init() {
  80. try {
  81. // 缓存一定要用ConcurrentHashMap, 避免多线程下获取为空
  82. ipCache = new ConcurrentHashMap<>();
  83. loc = new IPLocation();
  84. buf = new byte[100];
  85. b4 = new byte[4];
  86. b3 = new byte[3];
  87. try {
  88. ipFile = new RandomAccessFile(IP_FILE, "r");
  89. } catch (FileNotFoundException e) {
  90. // 如果找不到这个文件,再尝试再当前目录下搜索,这次全部改用小写文件名
  91. // 因为有些系统可能区分大小写导致找不到ip地址信息文件
  92. String filename = new File(IP_FILE).getName().toLowerCase();
  93. File[] files = new File(INSTALL_DIR).listFiles();
  94. for(int i = 0; i < files.length; i++) {
  95. if(files[i].isFile()) {
  96. if(files[i].getName().toLowerCase().equals(filename)) {
  97. try {
  98. ipFile = new RandomAccessFile(files[i], "r");
  99. } catch (FileNotFoundException e1) {
  100. log.error("IP地址信息文件没有找到,IP显示功能将无法使用:{}" + e1.getMessage(), e1);
  101. ipFile = null;
  102. }
  103. break;
  104. }
  105. }
  106. }
  107. }
  108. // 如果打开文件成功,读取文件头信息
  109. if(ipFile != null) {
  110. try {
  111. ipBegin = readLong4(0);
  112. ipEnd = readLong4(4);
  113. if(ipBegin == -1 || ipEnd == -1) {
  114. ipFile.close();
  115. ipFile = null;
  116. }
  117. } catch (IOException e) {
  118. log.error("IP地址信息文件格式有错误,IP显示功能将无法使用"+ e.getMessage(), e);
  119. ipFile = null;
  120. }
  121. }
  122. } catch (Exception e) {
  123. log.error("IP地址服务初始化异常:" + e.getMessage(), e);
  124. }
  125. }
  126. /**
  127. * 查询IP地址位置 - synchronized的作用是避免多线程时获取区域信息为空
  128. * @param ip
  129. * @return
  130. */
  131. public synchronized IPLocation getIPLocation(final String ip) {
  132. IPLocation location = new IPLocation();
  133. location.setArea(this.getArea(ip));
  134. location.setCountry(this.getCountry(ip));
  135. return location;
  136. }
  137. /**
  138. * 从内存映射文件的offset位置开始的3个字节读取一个int
  139. * @param offset
  140. * @return
  141. */
  142. private int readInt3(int offset) {
  143. mbb.position(offset);
  144. return mbb.getInt() & 0x00FFFFFF;
  145. }
  146. /**
  147. * 从内存映射文件的当前位置开始的3个字节读取一个int
  148. * @return
  149. */
  150. private int readInt3() {
  151. return mbb.getInt() & 0x00FFFFFF;
  152. }
  153. /**
  154. * 根据IP得到国家名
  155. * @param ip ip的字节数组形式
  156. * @return 国家名字符串
  157. */
  158. public String getCountry(byte[] ip) {
  159. // 检查ip地址文件是否正常
  160. if(ipFile == null)
  161. return BAD_IP_FILE;
  162. // 保存ip,转换ip字节数组为字符串形式
  163. String ipStr = Util.getIpStringFromBytes(ip);
  164. // 先检查cache中是否已经包含有这个ip的结果,没有再搜索文件
  165. if(ipCache.containsKey(ipStr)) {
  166. IPLocation ipLoc = ipCache.get(ipStr);
  167. return ipLoc.getCountry();
  168. } else {
  169. IPLocation ipLoc = getIPLocation(ip);
  170. ipCache.put(ipStr, ipLoc.getCopy());
  171. return ipLoc.getCountry();
  172. }
  173. }
  174. /**
  175. * 根据IP得到国家名
  176. * @param ip IP的字符串形式
  177. * @return 国家名字符串
  178. */
  179. public String getCountry(String ip) {
  180. return getCountry(Util.getIpByteArrayFromString(ip));
  181. }
  182. /**
  183. * 根据IP得到地区名
  184. * @param ip ip的字节数组形式
  185. * @return 地区名字符串
  186. */
  187. public String getArea(final byte[] ip) {
  188. // 检查ip地址文件是否正常
  189. if(ipFile == null)
  190. return BAD_IP_FILE;
  191. // 保存ip,转换ip字节数组为字符串形式
  192. String ipStr = Util.getIpStringFromBytes(ip);
  193. // 先检查cache中是否已经包含有这个ip的结果,没有再搜索文件
  194. if(ipCache.containsKey(ipStr)) {
  195. IPLocation ipLoc = ipCache.get(ipStr);
  196. return ipLoc.getArea();
  197. } else {
  198. IPLocation ipLoc = getIPLocation(ip);
  199. ipCache.put(ipStr, ipLoc.getCopy());
  200. return ipLoc.getArea();
  201. }
  202. }
  203. /**
  204. * 根据IP得到地区名
  205. * @param ip IP的字符串形式
  206. * @return 地区名字符串
  207. */
  208. public String getArea(final String ip) {
  209. return getArea(Util.getIpByteArrayFromString(ip));
  210. }
  211. /**
  212. * 根据ip搜索ip信息文件,得到IPLocation结构,所搜索的ip参数从类成员ip中得到
  213. * @param ip 要查询的IP
  214. * @return IPLocation结构
  215. */
  216. private IPLocation getIPLocation(final byte[] ip) {
  217. IPLocation info = null;
  218. long offset = locateIP(ip);
  219. if(offset != -1)
  220. info = getIPLocation(offset);
  221. if(info == null) {
  222. info = new IPLocation();
  223. info.setCountry ( UNKNOWN_COUNTRY);
  224. info.setArea(UNKNOWN_AREA);
  225. }
  226. return info;
  227. }
  228. /**
  229. * 从offset位置读取4个字节为一个long,因为java为big-endian格式,所以没办法
  230. * 用了这么一个函数来做转换
  231. * @param offset
  232. * @return 读取的long值,返回-1表示读取文件失败
  233. */
  234. private long readLong4(long offset) {
  235. long ret = 0;
  236. try {
  237. ipFile.seek(offset);
  238. ret |= (ipFile.readByte() & 0xFF);
  239. ret |= ((ipFile.readByte() << 8) & 0xFF00);
  240. ret |= ((ipFile.readByte() << 16) & 0xFF0000);
  241. ret |= ((ipFile.readByte() << 24) & 0xFF000000);
  242. return ret;
  243. } catch (IOException e) {
  244. return -1;
  245. }
  246. }
  247. /**
  248. * 从offset位置读取3个字节为一个long,因为java为big-endian格式,所以没办法
  249. * 用了这么一个函数来做转换
  250. * @param offset 整数的起始偏移
  251. * @return 读取的long值,返回-1表示读取文件失败
  252. */
  253. private long readLong3(long offset) {
  254. long ret = 0;
  255. try {
  256. ipFile.seek(offset);
  257. ipFile.readFully(b3);
  258. ret |= (b3[0] & 0xFF);
  259. ret |= ((b3[1] << 8) & 0xFF00);
  260. ret |= ((b3[2] << 16) & 0xFF0000);
  261. return ret;
  262. } catch (IOException e) {
  263. return -1;
  264. }
  265. }
  266. /**
  267. * 从当前位置读取3个字节转换成long
  268. * @return 读取的long值,返回-1表示读取文件失败
  269. */
  270. private long readLong3() {
  271. long ret = 0;
  272. try {
  273. ipFile.readFully(b3);
  274. ret |= (b3[0] & 0xFF);
  275. ret |= ((b3[1] << 8) & 0xFF00);
  276. ret |= ((b3[2] << 16) & 0xFF0000);
  277. return ret;
  278. } catch (IOException e) {
  279. return -1;
  280. }
  281. }
  282. /**
  283. * 从offset位置读取四个字节的ip地址放入ip数组中,读取后的ip为big-endian格式,但是
  284. * 文件中是little-endian形式,将会进行转换
  285. * @param offset
  286. * @param ip
  287. */
  288. private void readIP(long offset, byte[] ip) {
  289. try {
  290. ipFile.seek(offset);
  291. ipFile.readFully(ip);
  292. byte temp = ip[0];
  293. ip[0] = ip[3];
  294. ip[3] = temp;
  295. temp = ip[1];
  296. ip[1] = ip[2];
  297. ip[2] = temp;
  298. } catch (IOException e) {
  299. log.error(e.getMessage(), e);
  300. }
  301. }
  302. /**
  303. * 从offset位置读取四个字节的ip地址放入ip数组中,读取后的ip为big-endian格式,但是
  304. * 文件中是little-endian形式,将会进行转换
  305. * @param offset
  306. * @param ip
  307. */
  308. private void readIP(int offset, byte[] ip) {
  309. mbb.position(offset);
  310. mbb.get(ip);
  311. byte temp = ip[0];
  312. ip[0] = ip[3];
  313. ip[3] = temp;
  314. temp = ip[1];
  315. ip[1] = ip[2];
  316. ip[2] = temp;
  317. }
  318. /**
  319. * 把类成员ip和beginIp比较,注意这个beginIp是big-endian的
  320. * @param ip 要查询的IP
  321. * @param beginIp 和被查询IP相比较的IP
  322. * @return 相等返回0,ip大于beginIp则返回1,小于返回-1。
  323. */
  324. private int compareIP(byte[] ip, byte[] beginIp) {
  325. for(int i = 0; i < 4; i++) {
  326. int r = compareByte(ip[i], beginIp[i]);
  327. if(r != 0)
  328. return r;
  329. }
  330. return 0;
  331. }
  332. /**
  333. * 把两个byte当作无符号数进行比较
  334. * @param b1
  335. * @param b2
  336. * @return 若b1大于b2则返回1,相等返回0,小于返回-1
  337. */
  338. private int compareByte(byte b1, byte b2) {
  339. if((b1 & 0xFF) > (b2 & 0xFF)) // 比较是否大于
  340. return 1;
  341. else if((b1 ^ b2) == 0)// 判断是否相等
  342. return 0;
  343. else
  344. return -1;
  345. }
  346. /**
  347. * 这个方法将根据ip的内容,定位到包含这个ip国家地区的记录处,返回一个绝对偏移
  348. * 方法使用二分法查找。
  349. * @param ip 要查询的IP
  350. * @return 如果找到了,返回结束IP的偏移,如果没有找到,返回-1
  351. */
  352. private long locateIP(byte[] ip) {
  353. long m = 0;
  354. int r;
  355. // 比较第一个ip项
  356. readIP(ipBegin, b4);
  357. r = compareIP(ip, b4);
  358. if(r == 0) return ipBegin;
  359. else if(r < 0) return -1;
  360. // 开始二分搜索
  361. for(long i = ipBegin, j = ipEnd; i < j; ) {
  362. m = getMiddleOffset(i, j);
  363. readIP(m, b4);
  364. r = compareIP(ip, b4);
  365. // log.debug(Utils.getIpStringFromBytes(b));
  366. if(r > 0)
  367. i = m;
  368. else if(r < 0) {
  369. if(m == j) {
  370. j -= IP_RECORD_LENGTH;
  371. m = j;
  372. } else
  373. j = m;
  374. } else
  375. return readLong3(m + 4);
  376. }
  377. // 如果循环结束了,那么i和j必定是相等的,这个记录为最可能的记录,但是并非
  378. // 肯定就是,还要检查一下,如果是,就返回结束地址区的绝对偏移
  379. m = readLong3(m + 4);
  380. readIP(m, b4);
  381. r = compareIP(ip, b4);
  382. if(r <= 0) return m;
  383. else return -1;
  384. }
  385. /**
  386. * 得到begin偏移和end偏移中间位置记录的偏移
  387. * @param begin
  388. * @param end
  389. * @return
  390. */
  391. private long getMiddleOffset(long begin, long end) {
  392. long records = (end - begin) / IP_RECORD_LENGTH;
  393. records >>= 1;
  394. if(records == 0) records = 1;
  395. return begin + records * IP_RECORD_LENGTH;
  396. }
  397. /**
  398. * 给定一个ip国家地区记录的偏移,返回一个IPLocation结构
  399. * @param offset 国家记录的起始偏移
  400. * @return IPLocation对象
  401. */
  402. private IPLocation getIPLocation(long offset) {
  403. try {
  404. // 跳过4字节ip
  405. ipFile.seek(offset + 4);
  406. // 读取第一个字节判断是否标志字节
  407. byte b = ipFile.readByte();
  408. if(b == REDIRECT_MODE_1) {
  409. // 读取国家偏移
  410. long countryOffset = readLong3();
  411. // 跳转至偏移处
  412. ipFile.seek(countryOffset);
  413. // 再检查一次标志字节,因为这个时候这个地方仍然可能是个重定向
  414. b = ipFile.readByte();
  415. if(b == REDIRECT_MODE_2) {
  416. loc.setCountry ( readString(readLong3()));
  417. ipFile.seek(countryOffset + 4);
  418. } else
  419. loc.setCountry ( readString(countryOffset));
  420. // 读取地区标志
  421. loc.setArea( readArea(ipFile.getFilePointer()));
  422. } else if(b == REDIRECT_MODE_2) {
  423. loc.setCountry ( readString(readLong3()));
  424. loc.setArea( readArea(offset + 8));
  425. } else {
  426. loc.setCountry ( readString(ipFile.getFilePointer() - 1));
  427. loc.setArea( readArea(ipFile.getFilePointer()));
  428. }
  429. return loc;
  430. } catch (IOException e) {
  431. return null;
  432. }
  433. }
  434. /**
  435. * 给定一个ip国家地区记录的偏移,返回一个IPLocation结构,此方法应用与内存映射文件方式
  436. * @param offset 国家记录的起始偏移
  437. * @return IPLocation对象
  438. */
  439. private IPLocation getIPLocation(int offset) {
  440. // 跳过4字节ip
  441. mbb.position(offset + 4);
  442. // 读取第一个字节判断是否标志字节
  443. byte b = mbb.get();
  444. if(b == REDIRECT_MODE_1) {
  445. // 读取国家偏移
  446. int countryOffset = readInt3();
  447. // 跳转至偏移处
  448. mbb.position(countryOffset);
  449. // 再检查一次标志字节,因为这个时候这个地方仍然可能是个重定向
  450. b = mbb.get();
  451. if(b == REDIRECT_MODE_2) {
  452. loc.setCountry ( readString(readInt3()));
  453. mbb.position(countryOffset + 4);
  454. } else
  455. loc.setCountry ( readString(countryOffset));
  456. // 读取地区标志
  457. loc.setArea(readArea(mbb.position()));
  458. } else if(b == REDIRECT_MODE_2) {
  459. loc.setCountry ( readString(readInt3()));
  460. loc.setArea(readArea(offset + 8));
  461. } else {
  462. loc.setCountry ( readString(mbb.position() - 1));
  463. loc.setArea(readArea(mbb.position()));
  464. }
  465. return loc;
  466. }
  467. /**
  468. * 从offset偏移开始解析后面的字节,读出一个地区名
  469. * @param offset 地区记录的起始偏移
  470. * @return 地区名字符串
  471. * @throws IOException
  472. */
  473. private String readArea(long offset) throws IOException {
  474. ipFile.seek(offset);
  475. byte b = ipFile.readByte();
  476. if(b == REDIRECT_MODE_1 || b == REDIRECT_MODE_2) {
  477. long areaOffset = readLong3(offset + 1);
  478. if(areaOffset == 0)
  479. return UNKNOWN_AREA;
  480. else
  481. return readString(areaOffset);
  482. } else
  483. return readString(offset);
  484. }
  485. /**
  486. * @param offset 地区记录的起始偏移
  487. * @return 地区名字符串
  488. */
  489. private String readArea(int offset) {
  490. mbb.position(offset);
  491. byte b = mbb.get();
  492. if(b == REDIRECT_MODE_1 || b == REDIRECT_MODE_2) {
  493. int areaOffset = readInt3();
  494. if(areaOffset == 0)
  495. return UNKNOWN_AREA;
  496. else
  497. return readString(areaOffset);
  498. } else
  499. return readString(offset);
  500. }
  501. /**
  502. * 从offset偏移处读取一个以0结束的字符串
  503. * @param offset 字符串起始偏移
  504. * @return 读取的字符串,出错返回空字符串
  505. */
  506. private String readString(long offset) {
  507. try {
  508. ipFile.seek(offset);
  509. int i;
  510. for(i = 0, buf[i] = ipFile.readByte(); buf[i] != 0; buf[++i] = ipFile.readByte());
  511. if(i != 0)
  512. return Util.getString(buf, 0, i, "GBK");
  513. } catch (IOException e) {
  514. log.error(e.getMessage(), e);
  515. }
  516. return "";
  517. }
  518. /**
  519. * 从内存映射文件的offset位置得到一个0结尾字符串
  520. * @param offset 字符串起始偏移
  521. * @return 读取的字符串,出错返回空字符串
  522. */
  523. private String readString(int offset) {
  524. try {
  525. mbb.position(offset);
  526. int i;
  527. for(i = 0, buf[i] = mbb.get(); buf[i] != 0; buf[++i] = mbb.get());
  528. if(i != 0)
  529. return Util.getString(buf, 0, i, "GBK");
  530. } catch (IllegalArgumentException e) {
  531. log.error(e.getMessage(), e);
  532. }
  533. return "";
  534. }
  535. public String getCity(final String ipAddress){
  536. try {
  537. if(ipAddress.startsWith("192.168.")){
  538. log.error("此IP[{}]段不进行处理!", ipAddress);
  539. return null;
  540. }
  541. return getIPLocation(ipAddress).getCity();
  542. }catch (Exception e){
  543. log.error("根据IP[{}]获取省份失败:{}", ipAddress, e.getMessage());
  544. return null;
  545. }
  546. }
  547. public static void main(String[] args){
  548. IPAddressUtils ip = new IPAddressUtils();
  549. ip.init();
  550. String address = "112.225.35.70";
  551. System.out.println("IP地址["+address + "]获取到的区域信息:" + ip.getIPLocation(address).getCountry() + ", 获取到的城市:" + ip.getIPLocation(address).getCity() + ", 运营商:"+ip.getIPLocation(address).getArea());
  552. }
  553. }

总结

其实我也是从网络上找的解析纯真库代码[http://blog.csdn.net/rockstar541/article/details/7161505] , 当然,我的代码是在他的基础上进行优化的,主要的在高并发的情况下,会出现获取城市为空的情况,所以在以下几个地方有改进:

  • (1)ipCache初始化的时候使用并发Map
  1. ipCache = new HashMap<>();
  2. 替换为
  3. ipCache = new ConcurrentHashMap<>();
  • (2)获取IPLocation对象时进行同步处理,我尝试过将synchronized关键字加到更深或者更浅的方法上,在getIPLocation(String ip) 上加目前最安全,最高效
  1. public IPLocation getIPLocation(String ip) {
  2. IPLocation location = new IPLocation();
  3. location.setArea(this.getArea(ip));
  4. location.setCountry(this.getCountry(ip));
  5. return location;
  6. }
  7. 替换为
  8. public synchronized IPLocation getIPLocation(final String ip) {
  9. IPLocation location = new IPLocation();
  10. location.setArea(this.getArea(ip));
  11. location.setCountry(this.getCountry(ip));
  12. return location;
  13. }

Java使用纯真IP库获取IP对应省份和城市的更多相关文章

  1. python3.4学习笔记(二十三) Python调用淘宝IP库获取IP归属地返回省市运营商实例代码

    python3.4学习笔记(二十三) Python调用淘宝IP库获取IP归属地返回省市运营商实例代码 淘宝IP地址库 http://ip.taobao.com/目前提供的服务包括:1. 根据用户提供的 ...

  2. 使用新浪IP库获取IP详细地址

    使用新浪IP库获取IP详细地址 <?php class Tool{ /** * 获取IP的归属地( 新浪IP库 ) * * @param $ip String IP地址:112.65.102.1 ...

  3. 使用纯真IP库获取用户端地理位置信息

    引言 在一些电商类或者引流类的网站中经常会有获取用户地理位置信息的需求,下面我分享一个用纯真IP库获取用户地理位置信息的方案. 正文 第一步:本文的方案是基于纯真IP库的,所以首先要去下载最新的纯真I ...

  4. php利用淘宝IP库获取用户ip地理位置

    我们查ip的时候都是利用ip138查询的,不过那个有时候是不准确的,还不如自己引用淘宝的ip库来查询,这样准确度还高一些.不多说了,介绍一下淘宝IP地址库的使用. 淘宝IP地址库 淘宝公布了他们的IP ...

  5. php根据地理坐标获取国家、省份、城市,及周边数据类

    功能:当App获取到用户的地理坐标时,可以根据坐标知道用户当前在那个国家.省份.城市,及周边有什么数据. 原理:基于百度Geocoding API 实现,需要先注册百度开发者,然后申请百度AK(密钥) ...

  6. php依据地理坐标获取国家、省份、城市,及周边数据类

    功能:当App获取到用户的地理坐标时,能够依据坐标知道用户当前在那个国家.省份.城市.及周边有什么数据. 原理:基于百度Geocoding API 实现.须要先注冊百度开发人员.然后申请百度AK(密钥 ...

  7. Python之通过IP地址库获取IP地理信息

    利用第三方的IP地址库,各个公司可以根据自己的业务情况打造自己的IP地址采集分析系统.例如游戏公司可以采集玩家地区信息,进行有针对性的运营策略,还可能帮助分析玩家网络故障分布等等. #!/usr/bi ...

  8. PHP Swoole 基于纯真IP库根据IP匹配城市

    把纯真IP库读到内存,纯真IP库本来就是有序的,然后每次请求二分查找就行,44WIP查找十几次就搞定了 dispatch_mode最好写3,不然做服务的时候,会导致进程任务分配不均匀. max_req ...

  9. 根据IP地址获取IP的详细信息

    <?php header('Content-Type:text/html; charset=utf-8'); function ip_data() { $ip = GetIP(); $url = ...

随机推荐

  1. 关于hadoop: command not found的问题

    问题: 昨天在安装完hadoop伪分布式之后,执行hadoop下的子项目--文字计数功能时出现该错误,然后今天执行 hadoop fs -ls命令时系统给出同样的错误提醒,经过查找资料,初步认为是ha ...

  2. codechef T2 Chef and Sign Sequences

    CHEFSIGN: 大厨与符号序列题目描述 大厨昨天捡到了一个奇怪的字符串 s,这是一个仅包含‘<’.‘=’和‘>’三种比较符号的字符串. 记字符串长度为 N,大厨想要在字符串的开头.结尾 ...

  3. [bzoj1770][Usaco2009 Nov]lights 燈——Gauss消元法

    题意 给定一个无向图,初始状态所有点均为黑,如果更改一个点,那么它和与它相邻的点全部会被更改.一个点被更改当它的颜色与之前相反. 题解 第一道Gauss消元题.所谓gauss消元,就是使用初等行列式变 ...

  4. VC6.0显示行号的插件

    VC6.0显示行号的插件,很好很强大的显行号插件,使用VC编程的朋友再也不用烦恼VC6.0没有行号的编程环境了. VC显示行号插件使用说明:1. 如果你的VC安装在C盘,请拷贝文件VC6LineNum ...

  5. 《linux下进程的创建,执行,监控和终止》

    <linux下进程的创建,执行,监控和终止> http://blog.csdn.net/miss_acha/article/details/43671047 http://blog.csd ...

  6. 算法题之Climbing Stairs(leetcode 70)

    题目: You are climbing a stair case. It takes n steps to reach to the top. Each time you can either cl ...

  7. servlet(4) - servletAPI - 小易Java笔记

    Servlet规范核心类图 1.请求和响应对象 ==> HTTP协议包含请求和响应部分. ==> HttpServletRequest就代表着请求部分 ==> HttpServlet ...

  8. springboot整合jsp模板

    springboot整合jsp模板 在使用springboot框架里使用jsp的时候,页面模板使用jsp在pom.xnl中需要引入相关的依赖,否则在controller中无法返回到指定页面 〇.搭建s ...

  9. EasyUI的tree展开所有的节点或者根据特殊的条件控制展示指定的节点

    展示tree下的所有节点$(function(){ $('#t_funinfo_tree').tree({ checkbox: true, url:"<%=basePath %> ...

  10. 推荐下载App,如果本地安装则直接打开本地App(Android/IOS)

    推荐下载App,如果本地安装则直接打开本地App(Android/IOS) - 纵观现在每家移动网站,打开首页的时候,都有各种各样的形式来提示你下载自身的移动App(Android/IOS),这是做移 ...