ip地址查询工具类

谁借莪1个温暖的怀抱¢ 2022-06-18 05:06 404阅读 0赞

使用java查找ip地址的省市区,使用淘宝的ip地址库http://ip.taobao.com/index.php

  1. package com.common.util;
  2. import java.net.InetAddress;
  3. import java.net.NetworkInterface;
  4. import java.util.Enumeration;
  5. import java.util.Map;
  6. import java.util.regex.Pattern;
  7. import com.alibaba.fastjson.JSON;
  8. import com.alibaba.fastjson.JSONObject;
  9. import com.google.common.collect.Maps;
  10. /**
  11. * IP地址实用类
  12. */
  13. public class IpAddressUtil {
  14. private static final String LOCALHOST = "127.0.0.1";
  15. private static final String ANYHOST = "0.0.0.0";
  16. private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$");
  17. public static void main(String[] args) {
  18. System.out.println(getIpRegion("***.***.***.**"));
  19. }
  20. /**
  21. * 获取指定IP的区域位置
  22. */
  23. public static String getIpRegion(String ip){
  24. String urlStr = "http://ip.taobao.com/service/getIpInfo.php";
  25. Map<String, Object> params = Maps.newHashMap();
  26. params.put("ip", ip);
  27. String returnStr = HttpUtil.doPost(urlStr, params);
  28. if (returnStr != null) {
  29. String[] temp = returnStr.split(",");
  30. if (temp.length < 3) {
  31. return "本地";
  32. }
  33. JSONObject jsonObject = JSON.parseObject(returnStr).getJSONObject("data");
  34. String region = jsonObject.getString("region");
  35. String city = jsonObject.getString("city");
  36. String isp = jsonObject.getString("isp");
  37. return region + city + "[" + isp+"]";
  38. }
  39. return null;
  40. }
  41. /**
  42. * 遍历本地网卡,返回第一个合理的IP。
  43. *
  44. * @return 本地网卡IP
  45. */
  46. public static String getLocalAddress() {
  47. String localIp = LOCALHOST;
  48. try {
  49. Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
  50. if (interfaces != null) {
  51. while (interfaces.hasMoreElements()) {
  52. try {
  53. NetworkInterface network = interfaces.nextElement();
  54. Enumeration<InetAddress> addresses = network.getInetAddresses();
  55. while (addresses.hasMoreElements()) {
  56. try {
  57. InetAddress address = addresses.nextElement();
  58. if (isValidAddress(address)) {
  59. return address.getHostAddress();
  60. }
  61. } catch (Throwable e) {
  62. e.printStackTrace();
  63. }
  64. }
  65. } catch (Throwable e) {
  66. e.printStackTrace();
  67. }
  68. }
  69. }
  70. } catch (Throwable e) {
  71. e.printStackTrace();
  72. }
  73. return localIp;
  74. }
  75. private static boolean isValidAddress(InetAddress address) {
  76. if (address == null || address.isLoopbackAddress())
  77. return false;
  78. String name = address.getHostAddress();
  79. return (name != null && !ANYHOST.equals(name) && !LOCALHOST.equals(name) && IP_PATTERN.matcher(name).matches());
  80. }
  81. }

查询结果:

湖北省武汉市[电信]

发表评论

表情:
评论列表 (有 0 条评论,404人围观)

还没有评论,来说两句吧...

相关阅读