using System;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using HttpClient client = new();
await GetAsync(client);
static async Task GetAsync(HttpClient client)
{
/// 街道 https://api.ipdatacloud.com/v2/query?ip=&key=
/// 区县 https://api.ipdatacloud.com/v2/query?ip=&key=
/// 风险 https://api.ipdatacloud.com/v2/query?ip=&key=
/// 应用场景 https://api.ipdatacloud.com/v2/query?ip=&key=
var type = 3;
var urlArr = new string[] {"https://api.ipdatacloud.com/v2/query?ip=&key=", "https://api.ipdatacloud.com/v2/query?ip=&key=", "https://api.ipdatacloud.com/v2/query?ip=&key=", "https://api.ipdatacloud.com/v2/query?ip=&key="};
var json = await client.GetStringAsync(urlArr[type]);
Console.WriteLine(json);
RespModel resp = JsonConvert.DeserializeObject<RespModel>(json);
Console.WriteLine(resp.code);
if (resp.code == 200) {
switch (type)
{
case 0:
Console.WriteLine(resp.data.location.ToString());
break;
case 1:
Console.WriteLine(resp.data.location.ToString());
break;
case 2:
Console.WriteLine(resp.data.risk.ToString());
break;
case 3:
Console.WriteLine(resp.data.scenes.ToString());
break;
default:
break;
}
}
}
public class RespModel
{
public int code = 0;
public string? msg;
public DataModel? data;
}
public class DataModel
{
public LocationModel? location;
public RiskModel? risk;
public ScenesModel? scenes;
}
public class LocationModel
{
public string? area_code; //行政区码
public string? city; //城市
public string? city_code; //城市代码
public string? continent; //洲
public string? country; //国家/地区
public string? country_code; //国家/地区英文简写
public string? district; //区县
public string? elevation; //海拔
public string? ip; //ip地址
public string? isp; //运营商
public string? latitude; //纬度
public string? longitude; //经度
public List<StreetModel>? multi_street; //历史街道位置
public string? province; //省份
public string? street; //街道
public string? time_zone; //时区
public string? weather_station; //气象站
public string? zip_code; //邮编
public override string ToString()
{
return $"LocationModel(Ip={ip}, continent={continent}, country={country}, country_code={country_code}, province={province}, city={city}, district={district}, street={street}, multi_street={multi_street}, area_code={area_code}, isp={isp}, longitude={longitude}, latitude={latitude}, time_zone={time_zone}, elevation={elevation}, weather_station={weather_station}, zip_code={zip_code}, city_code={city_code})";
}
}
public class StreetModel
{
public string? lng; //经度
public string? lat; //纬度
public string? province; //省份
public string? city; //城市
public string? district; //区县
public string? street; //街道
public string? street_number; //街道
public string? radius; //
public string? zip_code; //邮政编码
}
public class RiskTagModel
{
public string? label; //风险证据
public string? label_name; //风险标签名称
public string? last_time; //最近一次发生时间
}
public class RiskModel
{
public string? mb_rate; //秒拨概率
public string? proxy; //代理类型
public string? real; //真人概率
public string? risk_level; // 风险
public int risk_score = 0; //风险评分
public List<RiskTagModel>? risk_tag; //风险标签
public override string ToString()
{
return $"RiskModel(mb_rate={mb_rate}, proxy={proxy}, real={real}, risk_level={risk_level}, risk_score={risk_score}, risk_tag={risk_tag})";
}
}
public class ScenesModel {
public string? asn; //ASN号
public string? isp; //运营商
public string? usage_type; //应用场景类型
public override string ToString()
{
return $"ScenesModel(asn={asn}, isp={isp}, usage_type={usage_type})";
}
}
<!DOCTYPE html>
<html>
<body>
<?php
class Street {
public $lng; // 经度
public $lat; // 纬度
public $province; // 省份
public $city; // 城市
public $district; // 区县
public $street; // 街道
public $street_number; // 街道
public $radius; //
public $zip_code; // 邮政编码
public function __construct($obj) {
$this->lng = $obj->lng;
$this->lat = $obj->lat;
$this->province = $obj->province;
$this->city = $obj->city;
$this->district = $obj->district;
$this->street = $obj->street;
$this->street_number = $obj->street_number;
$this->radius = $obj->radius;
$this->zip_code = $obj->zip_code;
}
}
class Location {
public $area_code; // 行政区码
public $city; // 城市
public $city_code; // 城市代码
public $continent; // 洲
public $country; // 国家/地区
public $country_code; // 国家/地区英文简写
public $district; // 区县
public $elevation; // 海拔
public $ip; // ip地址
public $isp; // 运营商
public $latitude; // 纬度
public $longitude; // 经度
public $multi_street; // 历史街道位置 type=1时没有multi_street
public $province; // 省份
public $street; // 街道
public $time_zone; // 时区
public $weather_station; // 气象站
public $zip_code; // 邮编
public function __construct($obj) {
$this->area_code = $obj->area_code;
$this->city = $obj->city;
$this->city_code = $obj->city_code;
$this->continent = $obj->continent;
$this->country = $obj->country;
$this->country_code = $obj->country_code;
$this->district = $obj->district;
$this->elevation = $obj->elevation;
$this->ip = $obj->ip;
$this->isp = $obj->isp;
$this->latitude = $obj->latitude;
$this->longitude = $obj->longitude;
$this->province = $obj->province;
$this->street = $obj->street;
$this->time_zone = $obj->time_zone;
$this->weather_station = $obj->weather_station;
$this->zip_code = $obj->zip_code;
// type=1时没有multi_street
if (count($obj->multi_street) > 0) {
$multi_street = array();
foreach ($obj->multi_street as $item) {
$street = new Street($item);
$multi_street[] = $street;
}
$this->multi_street = $multi_street;
}
}
}
class RiskTag {
public $label; // 风险证据
public $label_name; // 风险标签名称
public $last_time; // 最近一次发生时间
public function __construct($obj) {
$this->label = $obj->label;
$this->label_name = $obj->label_name;
$this->last_time = $obj->last_time;
}
}
class Risk {
public $mb_rate; // 秒拨概率
public $proxy; // 代理类型
public $real; // 真人概率
public $risk_level; // 风险
public $risk_score; // 风险评分
public $risk_tag; // 风险标签
public function __construct($obj) {
$this->mb_rate = $obj->mb_rate;
$this->proxy = $obj->proxy;
$this->real = $obj->real;
$this->risk_level = $obj->risk_level;
$this->risk_score = $obj->risk_score;
if (count($obj->risk_tag) > 0) {
$risk_tag = array();
foreach ($obj->risk_tag as $item) {
$tag = new RiskTag($item);
$risk_tag[] = $tag;
}
$this->risk_tag = $risk_tag;
}
}
}
class Scenes {
public $asn; // ASN号
public $isp; // 运营商
public $usage_type; // 应用场景类型
function __construct($obj){
$this->asn = $obj->asn;
$this->isp = $obj->isp;
$this->usage_type = $obj->usage_type;
}
}
function request()
{
$type = 0;
$urlArr = array("https://api.ipdatacloud.com/v2/query?ip=&key=",
"https://api.ipdatacloud.com/v2/query?ip=&key=",
"https://api.ipdatacloud.com/v2/query?ip=&key=",
"https://api.ipdatacloud.com/v2/query?ip=&key=");
$response = file_get_contents($urlArr[$type]);
if ($response === false) {
// 处理错误
echo "err!";
} else {
// 处理响应数据
$object = json_decode($response);
if ($type <= 1) {
$location = new Location($object->data->location);
var_dump($location);
} else if ($type == 2) {
$risk = new Risk($object->data->risk);
print_r($risk);
} else if ($type == 3) {
$scenes = new Scenes($object->data->scenes);
print_r($scenes);
}
}
}
request();
?>
</body>
</html>
//
// RequestTest.swift
// IPDataCloud
//
// Created by apple on 2024/1/23.
//
import Foundation
class StreetModel: NSObject {
var lng : String? //经度
var lat : String? //纬度
var province : String? //省份
var city : String? //城市
var district : String? //区县
var street : String? //街道
var street_number : String? //街道
var radius : String? //
var zip_code : String? //邮政编码
required init(dict: [String: Any]) {
self.lng = dict["lng"] as? String
self.lat = dict["lat"] as? String
self.province = dict["province"] as? String
self.city = dict["city"] as? String
self.street = dict["street"] as? String
self.street_number = dict["street_number"] as? String
self.radius = dict["radius"] as? String
self.zip_code = dict["zip_code"] as? String
}
override var description: String {
return """
\n
\tProvince:\(province ?? "")
\tCity:\(city ?? "")
\tDistrict:\(district ?? "")
\tStreet:\(street ?? "")
\tMultiStreet:\(street_number ?? "")
\tLongitude:\(lng ?? "")
\tLatitude:\(lat ?? "")
\tZipCode:\(zip_code ?? "")
"""
}
}
class IPInfoModel: NSObject {
var area_code : String? //行政区码
var city : String? //城市
var city_code : String? //城市代码
var continent : String? //洲
var country : String? //国家/地区
var country_code : String? //国家/地区英文简写
var district : String? //区县
var elevation : String? //海拔
var ip : String? //ip地址
var isp : String? //运营商
var latitude : String? //纬度
var longitude : String? //经度
var multi_street : [StreetModel]? //历史街道位置
var province : String? //省份
var street : String? //街道
var time_zone : String? //时区
var weather_station : String? //气象站
var zip_code : String? //邮编
required init(dict: [String: Any]) {
self.area_code = dict["area_code"] as? String
self.city = dict["city"] as? String
self.city_code = dict["city_code"] as? String
self.continent = dict["continent"] as? String
self.country = dict["country"] as? String
self.country_code = dict["country_code"] as? String
self.district = dict["district"] as? String
self.elevation = dict["elevation"] as? String
self.ip = dict["ip"] as? String
self.isp = dict["isp"] as? String
self.latitude = dict["latitude"] as? String
self.longitude = dict["longitude"] as? String
self.province = dict["province"] as? String
self.street = dict["street"] as? String
self.time_zone = dict["time_zone"] as? String
self.weather_station = dict["weather_station"] as? String
self.zip_code = dict["zip_code"] as? String
var streetArr = [StreetModel]()
for item in dict["multi_street"] as! [[String: Any]] {
let model = StreetModel.init(dict: item)
streetArr.append(model)
}
self.multi_street = streetArr
}
override var description: String {
return """
Ip:\(ip ?? "")
Continent:\(continent ?? "")
Country:\(country ?? "")
CountryCode:\(country_code ?? "")
Province:\(province ?? "")
City:\(city ?? "")
District:\(district ?? "")
Street:\(street ?? "")
MultiStreet:\(multi_street ?? [])
AreaCode:\(area_code ?? "")
Isp:\(isp ?? "")
Longitude:\(longitude ?? "")
Latitude:\(latitude ?? "")
TimeZone:\(time_zone ?? "")
Elevation:\(elevation ?? "")
WeatherStation:\(weather_station ?? "")
ZipCode:\(zip_code ?? "")
CityCode:\(city_code ?? "")
"""
}
}
class IPRiskTagModel: NSObject {
var label: String? //风险证据
var label_name: String? //风险标签名称
var last_time: String? //最近一次发生时间
required init(dict: [String: Any]) {
self.label = dict["label"] as? String
self.label_name = dict["label_name"] as? String
self.last_time = dict["last_time"] as? String
}
override var description: String {
return """
\n
\tlabel:\(label ?? "")
\tlabel_name:\(label_name ?? "")
\tlast_time:\(last_time ?? "")
"""
}
}
class IPRiskModel: NSObject {
var mb_rate: String? //秒拨概率
var proxy: String? //代理类型
var real: String? //真人概率
var risk_level: String? // 风险
var risk_score: Int? //风险评分
var risk_tag: [IPRiskTagModel]? //风险标签
required init(dict: [String: Any]) {
self.mb_rate = dict["mb_rate"] as? String
self.proxy = dict["proxy"] as? String
self.real = dict["real"] as? String
self.risk_level = dict["risk_level"] as? String
self.risk_score = dict["risk_score"] as? Int
var tagArr = [IPRiskTagModel]()
for item in dict["risk_tag"] as! [[String: Any]] {
let model = IPRiskTagModel.init(dict: item)
tagArr.append(model)
}
self.risk_tag = tagArr
}
override var description: String {
return """
mb_rate:\(mb_rate ?? "")
proxy:\(proxy ?? "")
real:\(real ?? "")
risk_level:\(risk_level ?? "")
risk_score:\(risk_score ?? 0)
risk_tag:\(risk_tag ?? [])
"""
}
}
class IPScenesModel: NSObject {
var asn: String? //ASN号
var isp: String? //运营商
var usage_type: String? //应用场景类型
required init(dict: [String: Any]) {
self.asn = dict["asn"] as? String
self.isp = dict["isp"] as? String
self.usage_type = dict["usage_type"] as? String
}
override var description: String {
return """
asn:\(asn ?? "")
isp:\(isp ?? "")
usage_type:\(usage_type ?? "")
"""
}
}
/// ip查询
func requestIpQuery() {
/// 街道 https://api.ipdatacloud.com/v2/query?ip=&key=
/// 区县 https://api.ipdatacloud.com/v2/query?ip=&key=
/// 风险 https://api.ipdatacloud.com/v2/query?ip=&key=
/// 应用场景 https://api.ipdatacloud.com/v2/query?ip=&key=
let type = 3
let urlArr = ["https://api.ipdatacloud.com/v2/query?ip=&key=",
"https://api.ipdatacloud.com/v2/query?ip=&key=",
"https://api.ipdatacloud.com/v2/query?ip=&key=",
"https://api.ipdatacloud.com/v2/query?ip=&key="]
let url = urlArr[type]
let rUrl = URL.init(string: url)!
let request = URLRequest.init(url: rUrl, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 20)
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in
if error != nil {
print(error?.localizedDescription ?? "")
return
}
let dict = try! JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary
let code = dict["code"] as! Int
if code != 200 {
print("code: \(code)\nmsg: \(dict["msg"]!)")
return
}
let data = dict["data"] as! NSDictionary
if type == 0 || type == 1 {
let location = data["location"] as! [String : Any]
let model = IPInfoModel.init(dict: location)
print(model)
} else if type == 2 {
let risk = data["risk"] as! [String : Any]
let model = IPRiskModel.init(dict: risk)
print(model)
} else if type == 3 {
let risk = data["scenes"] as! [String : Any]
let model = IPScenesModel.init(dict: risk)
print(model)
}
}
task.resume()
}
离线库教程示例
Go
Java
NodeJS
PHP
Python
package ipdatacloud
import (
"encoding/binary"
"errors"
"io/ioutil"
"log"
"net"
"strconv"
"strings"
"sync"
)
type IpInfo struct {
prefStart [256]uint32
prefEnd [256]uint32
endArr []uint32
addrArr []string
}
var obj *IpInfo
var once sync.Once
func GetObject() *IpInfo {
once.Do(func() {
obj = &IpInfo{}
var err error
obj, err = LoadFile("conf/ipdatacloud.dat")
if err != nil {
log.Fatal("the IP Dat loaded failed!")
}
})
return obj
}
func LoadFile(file string) (*IpInfo, error) {
p := IpInfo{}
data, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
for k := 0; k < 256; k++ {
i := k*8 + 4
p.prefStart[k] = UnpackInt4byte(data[i], data[i+1], data[i+2], data[i+3])
p.prefEnd[k] = UnpackInt4byte(data[i+4], data[i+5], data[i+6], data[i+7])
}
RecordSize := int(UnpackInt4byte(data[0], data[1], data[2], data[3]))
p.endArr = make([]uint32, RecordSize)
p.addrArr = make([]string, RecordSize)
for i := 0; i < RecordSize; i++ {
j := 2052 + (i * 9)
endipnum := UnpackInt4byte(data[j], data[1+j], data[2+j], data[3+j])
offset := UnpackInt4byte(data[4+j], data[5+j], data[6+j], data[7+j])
length := uint32(data[8+j])
p.endArr[i] = endipnum
p.addrArr[i] = string(data[offset:int(offset+length)])
}
return &p, err
}
func (p *IpInfo) Get(ip string) (string, error) {
ips := strings.Split(ip, ".")
x, _ := strconv.Atoi(ips[0])
prefix := uint32(x)
intIP, err := ipToInt(ip)
if err != nil {
return "", err
}
low := p.prefStart[prefix]
high := p.prefEnd[prefix]
var cur uint32
if low == high {
cur = low
} else {
cur = p.Search(low, high, intIP)
}
if cur == 100000000 {
return "无信息", errors.New("无信息")
} else {
return p.addrArr[cur], nil
}
}
func (p *IpInfo) Search(low uint32, high uint32, k uint32) uint32 {
var M uint32 = 0
for low <= high {
mid := (low + high) / 2
endipNum := p.endArr[mid]
if endipNum >= k {
M = mid
if mid == 0 {
break
}
high = mid - 1
} else {
low = mid + 1
}
}
return M
}
func ipToInt(ipstr string) (uint32, error) {
ip := net.ParseIP(ipstr)
ip = ip.To4()
if ip == nil {
return 0, errors.New("ip 不合法")
}
return binary.BigEndian.Uint32(ip), nil
}
func UnpackInt4byte(a, b, c, d byte) uint32 {
return (uint32(a) & 0xFF) | ((uint32(b) << 8) & 0xFF00) | ((uint32(c) << 16) & 0xFF0000) | ((uint32(d) << 24) & 0xFF000000)
}
package com.ipdatacloud.ipdatacloud;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
public class Ip {
private int[] prefStart = new int[256];
private int[] prefEnd = new int[256];
private long[] endArr;
private String[] addrArr;
private static Ip instance = null;
private Ip() {
Path path = Paths.get("/home/dream/Desktop/ipdatacloud.dat");
byte[] data = null;
try {
data = Files.readAllBytes(path);
} catch (IOException e) {
e.printStackTrace();
}
for (int k = 0; k < 256; k++) {
int i = k * 8 + 4;
prefStart[k] = (int) UnpackInt4byte(data[i], data[i + 1], data[i + 2], data[i + 3]);
prefEnd[k] = (int) UnpackInt4byte(data[i + 4], data[i + 5], data[i + 6], data[i + 7]);
}
int RecordSize = (int) UnpackInt4byte(data[0], data[1], data[2], data[3]);
endArr = new long[RecordSize];
addrArr = new String[RecordSize];
for (int i = 0; i < RecordSize; i++) {
int p = 2052 + (i * 9);
long endipnum = UnpackInt4byte(data[p], data[1 + p], data[2 + p], data[3 + p]);
int offset = (int)UnpackInt4byte(data[4 + p], data[5 + p], data[6 + p],data[7+p]);
int length = data[8 + p] & 0xff;
endArr[i] = endipnum;
addrArr[i] = new String(Arrays.copyOfRange(data, offset, (offset + length)));
}
}
public static synchronized Ip getInstance() {
if (instance == null)
instance = new Ip();
return instance;
}
public String Get(String ip) {
String[] ips = ip.split("\\.");
int pref = Integer.valueOf(ips[0]);
long val = ipToLong(ip);
int low = prefStart[pref], high = prefEnd[pref];
long cur = low == high ? low : Search(low, high, val);
return addrArr[(int) cur];
}
private int Search(int low, int high, long k) {
int M = 0;
while (low <= high) {
int mid = (low + high) / 2;
long endipNum = endArr[mid];
if (endipNum >= k) {
M = mid;
if (mid == 0) {
break;
}
high = mid - 1;
} else
low = mid + 1;
}
return M;
}
private long UnpackInt4byte(byte a, byte b, byte c, byte d) {
return (a & 0xFFL) | ((b << 8) & 0xFF00L) | ((c << 16) & 0xFF0000L) | ((d << 24) & 0xFF000000L);
}
private long ipToLong(String ip) {
long result = 0;
String[] d = ip.split("\\.");
for (String b : d) {
result <<= 8;
result |= Long.parseLong(b) & 0xff;
}
return result;
}
public static void main(String[] args) {
Ip ip = Ip.getInstance();
System.out.println(ip.Get("35.201.142.37"));
}
}
"use strict";
var fs = require('fs');
var data = null;
var prefStart = [256];
var prefEnd = [256];
var endArr = [];
var addrArr = [];
var loadFile = function (filepath) {
data = fs.readFileSync(filepath);
var RecordSize = data.readUInt32LE(0);
for (var k = 0; k < 256; k++) {
var i = k * 8 + 4;
prefStart[k] = data.readUInt32LE(i);
prefEnd[k] = data.readUInt32LE(i + 4);
}
endArr = [RecordSize];
addrArr = [RecordSize];
for (var i = 0; i < RecordSize; i++) {
var p = 2052 + (i * 9);
endArr[i] = data.readUInt32LE(p);
var offset = data.readUInt32LE(4 + p);
var length = data.readUInt8(8 + p);//1 bit 无符号整型
addrArr[i] = data.slice(offset, offset + length).toString('utf-8');
}
};
var Get = function (ip) {
var ipArray = ip.split('.'), ipInt = ipToInt(ip), pref = parseInt(ipArray[0]);
var low = prefStart[pref], high = prefEnd[pref];
var cur = low == high ? low : Search(low, high, ipInt);
if (cur==100000000){
return null;
}
return addrArr[cur];
}
var Search = function (low, high, k) {
var M = 0;
while (low <= high) {
var mid = Math.floor((low + high) / 2);
var endipNum = endArr[mid];
if (endipNum >= k) {
M = mid;
if (mid === 0) {
break; //防止溢出
}
high = mid - 1;
}
else
low = mid + 1;
}
return M
}
var ipToInt = function (ip) { return new Buffer(ip.split('.')).readUInt32BE(0) }
exports.loadFile = function (file) {
if (data === null) {
loadFile(file);
}
}
exports.get = Get;
var ipFinder = require("./ip.js")
ipFinder.loadFile(__dirname+"/ipdatacloud.dat")
console.log(ipFinder.get("180.101.49.11"))