Search code examples
libpcapinet

Weird behavior of inet_ntoa


I was playing with libpcap and found a strange thing.

One part of the output is: "From: src_addr, To: dst_addr"

If I print with one statement, i.e. printf("From: %s, To: %s\n", inet_ntoa(ip_hdr->ip_src), inet_ntoa(ip_hdr->ip_dst)); The printed dst_addr is exactly the same as the printed src_addr. However, when I set a break point at this line and use gdb to examine the values stored in ip_src and ip_dst, they are different.

If written in two statements, i.e. printf("From: %s, ", inet_ntoa(ip_hdr->ip_src)); printf("To: %s\n", inet_ntoa(ip_hdr->ip_dst)); Then the problem disappeared and the src_addr and dst_addr in the output are different.


Solution

  • I have faced the same and it is because the function uses a static buffer. More explanation can be found in inet_ntoa problem (look on the third post).