根据 IP 和掩码C++打印所有 IP

Print all IPs based on IP and mask C++

本文关键字:IP 打印 掩码 根据 C++      更新时间:2023-10-16

我想打印给定掩码的所有可能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("%sn", inet_ntoa(x));
}

可以使用输入掩码按位AND输入 IP 地址以确定范围中的第一个 IP,并按位OR输入 IP 地址与掩码的反转来确定范围内的最后一个 IP。 然后,您可以遍历两者之间的值。

此外,inet_pton(AF_INET)期望指向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

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

auto ip = (ipaddress & subnetmask) | i;

此外,inet_pton的结果不是int而是struct in_addr所以 YMMV。最有可能的是,您应该改用inet_addr,因为它返回一个uint32_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("%sn", inet_ntoa(x));
}