【发布时间】:2017-11-01 21:37:23
【问题描述】:
我想打印给定掩码的所有可能 IP。我有这个代码来获取它,但我似乎遗漏了一些东西,因为我无法获得 IP 列表。我的代码基于this other post。
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 netmask= 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));
}
【问题讨论】:
-
如果您知道您的代码是在 C++ 中,那么为什么还要添加 C?
-
编辑为包含 C 和 C++
-
回滚是因为 C 和 C++ 的答案会有很大不同。两者都想要,问两个问题。
-
考虑网络掩码:例如 1.200.17.64。上面的 for 循环不起作用。
-
@RichardCritten 这不是网络掩码。
标签: c++ network-programming ip netmask