Skip to content

Commit 9850024

Browse files
JackyYinanakryiko
authored andcommitted
fix: sockfilter example output
When we have multiple calls to `inet_ntoa()`, this function might return the same char* even though the underlying string has been modified. We'll get the same string if we use this function in a row in a single printf function(because char* pointed to the same location). Signed-off-by: Jacky Yin <jjyyg1123@gmail.com>
1 parent aacf7f3 commit 9850024

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

examples/c/sockfilter.c

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,17 @@ static int libbpf_print_fn(enum libbpf_print_level level, const char *format, va
5656
return vfprintf(stderr, format, args);
5757
}
5858

59+
static inline void ltoa(uint32_t addr, char *dst)
60+
{
61+
snprintf(dst, 16, "%u.%u.%u.%u", (addr >> 24) & 0xFF, (addr >> 16) & 0xFF,
62+
(addr >> 8) & 0xFF, (addr & 0xFF));
63+
}
64+
5965
static int handle_event(void *ctx, void *data, size_t data_sz)
6066
{
6167
const struct so_event *e = data;
6268
char ifname[IF_NAMESIZE];
69+
char sstr[16] = {}, dstr[16] = {};
6370

6471
if (e->pkt_type != PACKET_HOST)
6572
return 0;
@@ -70,10 +77,11 @@ static int handle_event(void *ctx, void *data, size_t data_sz)
7077
if (!if_indextoname(e->ifindex, ifname))
7178
return 0;
7279

80+
ltoa(ntohl(e->src_addr), sstr);
81+
ltoa(ntohl(e->dst_addr), dstr);
82+
7383
printf("interface: %s\tprotocol: %s\t%s:%d(src) -> %s:%d(dst)\n", ifname,
74-
ipproto_mapping[e->ip_proto], inet_ntoa((struct in_addr){ e->src_addr }),
75-
ntohs(e->port16[0]), inet_ntoa((struct in_addr){ e->dst_addr }),
76-
ntohs(e->port16[1]));
84+
ipproto_mapping[e->ip_proto], sstr, ntohs(e->port16[0]), dstr, ntohs(e->port16[1]));
7785

7886
return 0;
7987
}

0 commit comments

Comments
 (0)