根据 IP 和掩码C++打印所有 IP
Print all IPs based on IP and mask C++
我想打印给定掩码的所有可能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));
}
相关文章:
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 如何在c++中打印目录
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何将结构插入到集合中并打印集合的成员
- 在循环C++中指定字符串之后,不会打印该字符串
- 以螺旋方式打印矩阵的程序.(工作不好)
- 从控制台中删除最后打印的元素
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何仅使用对象名称打印特定于对象的成员
- 回溯C++不打印函数,因此文件
- 在一定长度后从数组中打印时缺少整数
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 在gem5中打印文件中的所有cache_blocks
- 根据 IP 和掩码C++打印所有 IP
- 如何从连接到共享打印对象的客户端的服务器获取所有IP(或用户名)
- 创建一个控制台应用程序,打开TCP/IP连接并用C++、C#或Java打印输入的字符串