2015-11-06 11 views
-1

我正在嘗試循環子網中的IP地址,以便將它們與主機的DNS名稱一起打印出來。我有網絡掩碼和一個屬於它的IP地址。因爲我需要使用一些「網絡功能:inet_addr和gethostbyaddr」我將地址存儲在一個char數組中,但現在我不知道如何使用二進制地址來循環網絡中的所有主機,複雜的格式之間的轉換..任何建議來解決這個問題?用於在IP地址上循環的二進制和點分十進制轉換

int main(int argc, char* argv[]) 
{ 
    struct hostent *hostPtr; // holds the IP addresses, aliases ... etc 
    char* addr_ptr; 

    char network_mask[] = "255.255.255.0"; 
    char ip_addr_dot[] = "165.95.11.15"; 
    u_long ip_addr_long = = inet_addr(ip_addr_dot);//dotted decimal ip to binary; 
    u_long network_mask_long = inet_addr(network_mask); //dotted decimal network mask to binary; 
    u_long network_address_long = = ip_addr_long & network_mask_long; // binary network address 

    u_long starting_address = network_address_long + 1; //must be a binary operation 
    u_long current_address = starting_address; 
    int no_of_hosts; // how to find it 

    // This is the way I think I need to approach it, unless there is a better way for doing that .. 
    /* for(int i = 0; i < no_of_hosts; i++){ 
     current_address += 1; // must be done in binary 
     addr_ptr = (char *) &current_address; 
     hostPtr = gethostbyaddr(addr_ptr, 4, AF_INET); 

     if (hostPtr == NULL){ 

       printf(" Host %s not found\n", ip_addr_dot); 
     } 
     else { 

       printf("The IP address %s:\t", inet_ntoa(*addr_ptr)); 
       printf("The official name of the site is: %s\n", hostPtr->h_name); 

     } 
    }*/ 

    return 0; 

} 
+0

這些總是IPv4地址嗎? – wallyk

+0

是的..我現在假設。 –

回答

-1

scanf是你的朋友:

#include <stdio.h> 
... 
scanf(ipString, "%u.%u.%u.%u", &a, &b, &c, &d); 
__uint32_t ip=(a<<24)|(b<<16)|(c<<8)|d; 

scanf()功能是抗這些printf函數。它能夠轉換和解釋字符串。

如果您將此字符串到ip的轉換分隔成單獨的函數,那麼最好。

0

這可以讓你的主機的子網的最大數量:

u_long no_of_hosts = (network_address_long | ~network_mask_long) - network_address_long - 1; 

你的起始地址,迭代應該直截了當。 我想與大家分享我寫給得到一個無符號INT32點分十進制串一些老的C函數(在你的代碼u_long):

void Int2DotDec(u_long ip, char* buf) 
{ u_long b0 = ip & 0xFF, remain = ip >> 8; 
    u_long b1 = remain & 0xFF; remain = remain >> 8; 
    u_long b2 = remain & 0xFF; remain = remain >> 8; 
    u_long b3 = remain & 0xFF; 
    snprintf(buf, 16, "%d.%d.%d.%d", b3, b2, b1, b0); 
} 

PS:較真原諒我的,這個C風格的事情是舊東西,併爲我工作得很好。只需正確調整buf參數(char buf[16])即可。