编辑代码

#include <stdio.h>
#include <stdint.h>
#include <arpa/inet.h>

// 结构体用于存储IP范围和对应的地理位置
struct IpLocation {
    uint32_t startIp;
    uint32_t endIp;
    const char* location;
};

// 查找IP地址对应的地理位置
const char* findLocation(const char* ip, struct IpLocation locations[], int numLocations) {
    struct in_addr addr;
    inet_pton(AF_INET, ip, &addr.s_addr);
    uint32_t ipToSearch = ntohl(addr.s_addr);

    for (int i = 0; i < numLocations; i++) {
        if (ipToSearch >= locations[i].startIp && ipToSearch <= locations[i].endIp) {
            return locations[i].location;
        }
    }

    return "未知地点";
}

int main() {
    struct IpLocation locations[] = {
        {ntohl(inet_addr("202.102.133.0")), ntohl(inet_addr("202.102.133.255")), "山东东营市"},
        {ntohl(inet_addr("202.102.135.0")), ntohl(inet_addr("202.102.136.255")), "山东烟台"},
        {ntohl(inet_addr("202.102.156.34")), ntohl(inet_addr("202.102.157.255")), "山东青岛"},
        {ntohl(inet_addr("202.102.48.0")), ntohl(inet_addr("202.102.48.255")), "江苏宿迁"},
        {ntohl(inet_addr("202.102.49.15")), ntohl(inet_addr("202.102.51.251")), "江苏泰州"},
        {ntohl(inet_addr("202.102.56.0")), ntohl(inet_addr("202.102.56.255")), "江苏连云港"},
    };

    const char* ipToLookup = "202.102.133.10";
    const char* location = findLocation(ipToLookup, locations, sizeof(locations) / sizeof(locations[0]));

    printf("IP地址 %s 对应的地理位置是:%s\n", ipToLookup, location);

    return 0;
}