使用java查找ip地址的省市区,使用淘宝的ip地址库http://ip.taobao.com/index.php
package com.common.util;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Map;
import java.util.regex.Pattern;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
/**
* IP地址实用类
*/
public class IpAddressUtil {
private static final String LOCALHOST = "127.0.0.1";
private static final String ANYHOST = "0.0.0.0";
private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$");
public static void main(String[] args) {
System.out.println(getIpRegion("***.***.***.**"));
}
/**
* 获取指定IP的区域位置
*/
public static String getIpRegion(String ip){
String urlStr = "http://ip.taobao.com/service/getIpInfo.php";
Map<String, Object> params = Maps.newHashMap();
params.put("ip", ip);
String returnStr = HttpUtil.doPost(urlStr, params);
if (returnStr != null) {
String[] temp = returnStr.split(",");
if (temp.length < 3) {
return "本地";
}
JSONObject jsonObject = JSON.parseObject(returnStr).getJSONObject("data");
String region = jsonObject.getString("region");
String city = jsonObject.getString("city");
String isp = jsonObject.getString("isp");
return region + city + "[" + isp+"]";
}
return null;
}
/**
* 遍历本地网卡,返回第一个合理的IP。
*
* @return 本地网卡IP
*/
public static String getLocalAddress() {
String localIp = LOCALHOST;
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
if (interfaces != null) {
while (interfaces.hasMoreElements()) {
try {
NetworkInterface network = interfaces.nextElement();
Enumeration<InetAddress> addresses = network.getInetAddresses();
while (addresses.hasMoreElements()) {
try {
InetAddress address = addresses.nextElement();
if (isValidAddress(address)) {
return address.getHostAddress();
}
} catch (Throwable e) {
e.printStackTrace();
}
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}
} catch (Throwable e) {
e.printStackTrace();
}
return localIp;
}
private static boolean isValidAddress(InetAddress address) {
if (address == null || address.isLoopbackAddress())
return false;
String name = address.getHostAddress();
return (name != null && !ANYHOST.equals(name) && !LOCALHOST.equals(name) && IP_PATTERN.matcher(name).matches());
}
}
查询结果:
湖北省武汉市[电信]