0

我想打印给定掩码的所有可能 IP。我有这个代码来获取它,但我似乎遗漏了一些东西,因为我无法获得 IP 列表。我将我的代码建立在另一篇文章中。

unsigned int ipaddress, subnetmask;     

inet_pton(AF_INET, b->IpAddressList.IpAddress.String, &ipaddress);
inet_pton(AF_INET, b->IpAddressList.IpMask.String, &subnetmask);

for (unsigned int i = 1; i<(~subnetmask); i++) {
    auto ip = ipaddress & (subnetmask + i);
}

示例:ipaddress= 172.22.0.65 网络掩码= 255.255.252.0

我预计:

172.22.0.1
172.22.0.2
172.22.0.3
172.22.0.4
...

更新:我试过这段代码,但它也不起作用:

char* ip = "172.22.0.65";
char* netmask = "255.255.252.0";

struct in_addr ipaddress, subnetmask;

inet_pton(AF_INET, ip, &ipaddress);
inet_pton(AF_INET, netmask, &subnetmask);

unsigned long first_ip = ntohl(ipaddress.s_addr & subnetmask.s_addr);
unsigned long last_ip = ntohl(ipaddress.s_addr | ~(subnetmask.s_addr));

for (unsigned long ip = first_ip; ip <= last_ip; ++ip) {
    unsigned long theip = htonl(ip);
    struct in_addr x = { theip };
    printf("%s\n", inet_ntoa(x));
}
4

2 回答 2

3

您正在使用更改的主机部分添加(基本上是ored )子网掩码的 IP 地址。这里的优先级是错误的。您应该使用带有网络掩码IP 地址来获取网络部分,然后是那里主机部分:

auto ip = (ipaddress & subnetmask) | i;

此外,无论如何,结果都不inet_pton是YMMV。最有可能的是,您应该改用它,因为它返回一个:intstruct in_addrinet_addruint32_t

ip_address = inet_addr("127.0.0.1");

但话又说回来,您的代码期望127是最重要的字节,它不在 LSB 系统上。因此,您需要将这些地址与 交换一次,ntohl然后再与htonl.

因此我们得到类似的东西:

uint32_t ipaddress;
uint32_t subnetmask;

ipaddress = ntohl(inet_addr(b->IpAddressList.IpAddress.String));
subnetmask = ntohl(inet_addr(b->IpAddressList.IpMask.String));

for (uint32_t i = 1; i<(~subnetmask); i++) {
    uint32_t ip = (ipaddress & subnetmask) | i;
    struct in_addr x = { htonl(ip) };
    printf("%s\n", inet_ntoa(x));
}
于 2017-05-31T23:37:42.630 回答
3

您可以AND将输入 IP 地址与输入掩码按位确定范围内的第一个 IP,并将OR输入 IP 地址与掩码的倒数按位确定范围内的最后一个 IP。然后,您可以遍历其间的值。

此外,inet_pton(AF_INET)需要一个指向 a 的指针struct in_addr,而不是一个unsigned int.

试试这个:

struct in_addr ipaddress, subnetmask;

inet_pton(AF_INET, b->IpAddressList.IpAddress.String, &ipaddress);
inet_pton(AF_INET, b->IpAddressList.IpMask.String, &subnetmask);

unsigned long first_ip = ntohl(ipaddress.s_addr & subnetmask.s_addr);
unsigned long last_ip = ntohl(ipaddress.s_addr | ~(subnetmask.s_addr));

for (unsigned long ip = first_ip; ip <= last_ip; ++ip) {
    unsigned long theip = htonl(ip);
    // use theip as needed...
}

例如:

172.22.0.65 & 255.255.252.0 = 172.22.0.0
172.22.0.65 | 0.0.3.255 = 172.22.3.255
于 2017-05-31T23:42:41.303 回答