我想打印給定掩碼的所有可能的IP。我有這個代碼來得到它,但似乎我失去了一些東西,因爲我無法得到IP列表。我的代碼是this other post。打印基於IP和掩碼C++的所有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);
}
例如:ip地址= 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));
}
如果你知道你的代碼是在** C++ **那你爲什麼還加** C **? –
編輯爲包含C和C++ – user1618465
因爲C和C++的答案會有顯着差異而回滾。想要兩個,問兩個問題。 – user4581301