2017-05-31 29 views
0

我想打印給定掩碼的所有可能的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)); 
} 
+0

如果你知道你的代碼是在** C++ **那你爲什麼還加** C **? –

+0

編輯爲包含C和C++ – user1618465

+0

因爲C和C++的答案會有顯着差異而回滾。想要兩個,問兩個問題。 – user4581301

回答

2

可以按位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 
+0

嗨,它抱怨「錯誤C2678:二進制'&':找不到操作符,它需要一個類型爲'ULONG'的左操作數'(或沒有可接受的轉換)「在計算'first_ip'和'last_ip'的行處。嘗試更改'subnetmask.s_addr'的子網掩碼,但循環不提供期望的IP – user1618465

+0

我忘記在子網掩碼上應用s_addr,並且在生成的IP上應用'ntohl()'和'htonl() 。我修好了。 –

+0

我更新了問題中的代碼,因爲您的代碼現在似乎也無法正常工作。我設置IP和網絡掩碼,以便您可以測試它是否正常工作。謝謝! – user1618465

3

你是 IP地址與子網掩碼增加了(基本上存在)與變化的主機部分。這裏的優先順序是錯誤的。你應該與子網掩碼的IP地址,以獲得網絡一部分,那麼主機部分有:

auto ip = (ipaddress & subnetmask) | i; 

而且,inet_pton的結果不是intstruct 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("%s\n", inet_ntoa(x)); 
} 
+0

使用您的代碼IP 172.0.0.0始終打印。 ipaddress是0xac160040和subnermask是0xfffffc00。我在帖子中使用的例子的正確結果是https://pastebin.com/x4MYei7H – user1618465