I’ve been working through a small tutorial on how to build a basic packet sniffer for Linux. I got everything working, and I now want to add IP-to-host mapping.
Everything was working before I added this function:
void IPtoHostname(char *ipaddress, char *hostname){
struct hostent *host;
in_addr_t ip = inet_addr(ipaddress);
if (!hostname){
puts("Can't allocate memory...");
exit(-1);
}
host = gethostbyaddr((char *)&ip, 32, AF_INET);
hostname = strdup(host->h_name);
}
This basically takes a string IP address (“192.168.28.18”) ipaddress and fills in that IP’s hostname (“who.cares.com”) into hostname.
What happens is that strlen REFUSES to give me anything (I know how strdup works, and I’ve tested this myself) and segfaults. I’ve used GDB, and the string ends in a null
character and it isn’t NULL.
I’ve also tested using a raw string assignment with a static struct:
void IPtoHostname(char *ipaddress, char *hostname){
static struct hostent *host;
in_addr_t ip = inet_addr(ipaddress);
if (!hostname){
puts("Can't allocate memory...");
exit(-1);
}
host = gethostbyaddr((char *)&ip, 32, AF_INET);
hostname = host->h_name;
}
And still no dice.
So, what’s up with strlen?
Wow… Never fight POSIX. I eventually wrote my function to this:
And it works!