java实现IP归属地查询

IP归属地查询

使用ip-attribution.dat文件实现IP归属地查询。下载地址
网盘下载 提取码:zdhv


import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.springframework.core.io.ClassPathResource;

public final class IPDataHandler {
//	private static String IP_DATA_PATH = "./ip-attribution.dat";
   private static DataInputStream inputStream = null;
   private static long fileLength = -1;
   private static int dataLength = -1;
   private static Map<String, String> cacheMap = null;
   private static byte[] allData = null;

   static {
//		File file = new File(IP_DATA_PATH);
   	try {
   		//把文件放到src/main/resources下面
   		File file = new ClassPathResource("ip-attribution.dat").getFile();
   		inputStream = new DataInputStream(new FileInputStream(file));
   		fileLength = file.length();
   		cacheMap = new HashMap<String, String>();
   		if (fileLength > Integer.MAX_VALUE) {
   			throw new Exception("the filelength over 2GB");
   		}

   		dataLength = (int) fileLength;
   		allData = new byte[dataLength];
   		inputStream.read(allData, 0, dataLength);
   		dataLength = (int) getbytesTolong(allData, 0, 4,
   				ByteOrder.BIG_ENDIAN);
   	} catch (FileNotFoundException e) {
   		e.printStackTrace();
   	} catch (IOException e) {
   		e.printStackTrace();
   	} catch (Exception e) {
   		e.printStackTrace();
   	}
   }

   private static long getbytesTolong(byte[] bytes, int offerSet, int size,
   		ByteOrder byteOrder) {
   	if ((offerSet + size) > bytes.length || size <= 0) {
   		return -1;
   	}
   	byte[] b = new byte[size];
   	for (int i = 0; i < b.length; i++) {
   		b[i] = bytes[offerSet + i];
   	}
   	ByteBuffer byteBuffer = ByteBuffer.wrap(b);
   	byteBuffer.order(byteOrder);
   	long temp = -1;
   	if (byteBuffer.hasRemaining()) {
   		temp = byteBuffer.getInt();
   	}
   	return temp;
   }

   private static long ip2long(String ip) throws UnknownHostException {
   	InetAddress address = InetAddress.getByName(ip);
   	byte[] bytes = address.getAddress();
   	long reslut = getbytesTolong(bytes, 0, 4, ByteOrder.BIG_ENDIAN);
   	return reslut;
   }

   private static int getIntByBytes(byte[] b, int offSet) {
   	if (b == null || (b.length < (offSet + 3))) {
   		return -1;
   	}
   	byte[] bytes = Arrays.copyOfRange(allData, offSet, offSet + 3);
   	byte[] bs = new byte[4];
   	bs[3] = 0;
   	for (int i = 0; i < 3; i++) {
   		bs[i] = bytes[i];
   	}
   	return (int) getbytesTolong(bs, 0, 4, ByteOrder.LITTLE_ENDIAN);
   }

   public static String findGeography(String address) {
   	if (StringUtils.isBlank(address)) {
   		return "illegal address";
   	}
   	if (dataLength < 4 || allData == null) {
   		return "illegal ip data";
   	}
   	String ip = "127.0.0.1";
   	try {
   		ip = Inet4Address.getByName(address).getHostAddress();
   	} catch (UnknownHostException e) {
   		e.printStackTrace();
   	}
   	String[] ipArray = StringUtils.split(ip, ".");
   	int ipHeadValue = Integer.parseInt(ipArray[0]);
   	if (ipArray.length != 4 || ipHeadValue < 0 || ipHeadValue > 255) {
   		return "illegal ip";
   	}
   	if (cacheMap.containsKey(ip)) {
   		return cacheMap.get(ip);
   	}
   	long numIp = 1;
   	try {
   		numIp = ip2long(address);
   	} catch (UnknownHostException e1) {
   		e1.printStackTrace();
   	}
   	int tempOffSet = ipHeadValue * 4 + 4;
   	long start = getbytesTolong(allData, tempOffSet, 4,
   			ByteOrder.LITTLE_ENDIAN);
   	int max_len = dataLength - 1028;
   	long resultOffSet = 0;
   	int resultSize = 0;
   	for (start = start * 8 + 1024; start < max_len; start += 8) {
   		if (getbytesTolong(allData, (int) start + 4, 4,
   				ByteOrder.BIG_ENDIAN) >= numIp) {
   			resultOffSet = getIntByBytes(allData, (int) (start + 4 + 4));
   			resultSize = (char) allData[(int) start + 7 + 4];
   			break;
   		}
   	}
   	if (resultOffSet <= 0) {
   		return "resultOffSet too small";
   	}
   	byte[] add = Arrays.copyOfRange(allData, (int) (dataLength
   			+ resultOffSet - 1024),
   			(int) (dataLength + resultOffSet - 1024 + resultSize));
   	try {
   		if (add == null) {
   			cacheMap.put(ip, new String("no data found!!"));
   		} else {
   			cacheMap.put(ip, new String(add, "UTF-8"));
   		}
   	} catch (UnsupportedEncodingException e) {
   		e.printStackTrace();
   	}
   	return cacheMap.get(ip);
   }
   
   public static void main(String[] args) {
   	String s = findGeography("201.245.144.191");
   	System.out.println(s);
   }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java 中,我们可以使用第三方库来获取 IP归属地信息。其中一个常用的库是 GeoIP2,它基于 MaxMind 的 GeoIP2 数据库。 首先,需要将 GeoIP2 库添加到项目中。可以在 Maven 或 Gradle 构建脚本中添加相应的依赖项。 然后,我们可以使用 GeoIP2 提供的 API 来查询 IP归属地。以下是一个示例代码: ```java import com.maxmind.geoip2.DatabaseReader; import com.maxmind.geoip2.model.CityResponse; import com.maxmind.geoip2.record.Country; import java.io.File; import java.io.IOException; import java.net.InetAddress; public class IPUtils { public static String getIPCountry(String ip) { try { File database = new File("GeoIP2-City.mmdb"); DatabaseReader reader = new DatabaseReader.Builder(database).build(); InetAddress ipAddress = InetAddress.getByName(ip); CityResponse response = reader.city(ipAddress); Country country = response.getCountry(); return country.getName(); } catch (IOException e) { e.printStackTrace(); return null; } } public static void main(String[] args) { String ip = "123.456.789.0"; String country = getIPCountry(ip); System.out.println("IP " + ip + " 的归属地是:" + country); } } ``` 在上述示例中,我们通过 `getIPCountry` 方法传入一个 IP 地址,并在 `main` 方法中调用该方法来获取该 IP归属地信息。具体的归属地信息包括国家、地区、城市等,可以根据需要进行扩展和处理。 需要注意的是,在运行代码之前,我们需要下载并导入 GeoIP2 数据库文件 `GeoIP2-City.mmdb`,该文件包含了 IP 地址和归属地信息的映射关系。可以从 MaxMind 的官网或其他数据源获取该文件。 这样,我们就可以通过 Java 来获取 IP归属地信息了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值