我试图遍历子网中的ip地址,将它们与主机的DNS名称一起打印出来。我有网络掩码和属于它的IP地址。因为我需要使用一些"网络功能:inet_addr和gethostbyaddr"我将地址存储在char数组中,但是现在我不知道如何使用二进制地址来遍历网络中的所有主机,而不会在格式之间进行非常复杂的转换。有任何建议可以解决这个问题吗?
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;
}
答案 0 :(得分:0)
这可以获得子网上的最大主机数:
u_long no_of_hosts = (network_address_long | ~network_mask_long) - network_address_long - 1;
你有起始地址,迭代应该是直截了当的。 让我与大家分享一些旧的C函数,我写的是从无符号的int32(代码中的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);
}
p.s:纯粹主义者原谅我,这个C风格的东西是老东西,对我来说效果很好。只需正确调整buf参数(char buf[16]
)。
答案 1 :(得分:-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转换分隔为单独的函数。