我正在嘗試循環子網中的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 *) ¤t_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;
}
這些總是IPv4地址嗎? – wallyk
是的..我現在假設。 –