Trying to write a handler for a packet sniffer. I’m having issues with casting and inet_ntoa(). Code is as follows:
uint32_t *iphdr_srcaddr = malloc(sizeof(uint32_t));
if (*packet_ethertype == ETHERTYPE_IP) { /* IPv4 */
// copy packet data to vars
memcpy(iphdr_srcaddr, packet+26, 4);
// change to host-byte-order
*iphdr_srcaddr = ntohl(*iphdr_srcaddr);
struct in_addr *test;
test = (struct in_addr*) iphdr_srcaddr;
printf("uint32_t: %u\n", *iphdr_srcaddr); // Gives the correct long integer for the address
printf("struct in_addr: %u\n", test->s_addr); // Gives the correct long integer through the cast
char *test2;
test2 = inet_ntoa(*test);
}
Now if I try to printf("%s\n", test) I get SEGV. I’m sure I’m mixing up pointers, values and doing some sort of stupid casting. Error received during run below:
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff787ec61 in __strlen_sse2 () from /lib/libc.so.6
Compilation warning as well, I’m sure this is pointing me in the correct direction, but I’m not sure what to it means and how I can fix it:
mypcap.c: In function ‘handle_sniffed’:
mypcap.c:61:15: warning: assignment makes pointer from integer without a cast [enabled by default]
This refers to the line test2 = inet_ntoa(*test);
The warning probably indicates that you don’t have a correct prototype in scope for
inet_ntoa()(because you haven’t included the right header). This means that the compiler assumes it has a return type ofint.You’re also passing
testtoprintf()when you should be passingtest2.In addition:
malloc()to allocate a singleuint32_t;ntohl()becauseinet_ntoa()expects its input in network byte order; andinet_ntoa()is out of date –inet_ntop()should be used in new code.Try: