tcp_metrics/load_bpf.c
2024-07-03 21:40:01 +02:00

75 lines
2.0 KiB
C

#include <stdio.h>
#include <bpf/bpf.h>
#include <bpf/libbpf.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "common.h"
static void clean_obj(struct bpf_object *obj){
printf("Cleaning\n");
bpf_object__close(obj);
}
int main(void){
const char *fileObj = "tp_tcp.o";
struct bpf_object *obj;
struct bpf_program *program;
struct bpf_map *map;
struct reset s_reset;
int err;
int map_fd;
long long stats;
int keys = 0;
obj = bpf_object__open_file(fileObj, NULL);
if (!obj){
printf("Failed to open %s\n", fileObj);
return -1;
}
//LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
map_fd = bpf_create_map(BPF_MAP_TYPE_HASH, sizeof(int), sizeof(struct reset), 4096, BPF_ANY);
printf("Create map: %d\n", map_fd);
err = bpf_object__load(obj);
printf("Object loaded: %d\n", err);
if (err){
printf("Failed to load object\n");
return -1;
}
program = bpf_object__find_program_by_name(obj, "tcp_retransmit");
if (!program){
printf("Failed to find the program\n");
return -1;
}
map = bpf_object__find_map_by_name(obj, "tcp_reset_stats");
if (!map){
printf("Failed to get the map\n");
clean_obj(obj);
return -1;
}
map_fd = bpf_object__find_map_fd_by_name(obj, "tcp_reset_stats");
printf("Map fd: %d\n", map_fd);
struct bpf_link *link = bpf_program__attach(program);
if (!link){
printf("Failed to attach the program\n");
return -1;
}
while(1){
int e = bpf_map_lookup_elem(map_fd, &keys, &s_reset);
if (e == 0){
//printf("%lld\n", stats);
struct in_addr *src = (struct in_addr*)&s_reset.saddr;
struct in_addr *dest = (struct in_addr*)&s_reset.daddr;
printf("Sport: %d; dport: %d %s %s\n", s_reset.sport, s_reset.dport, inet_ntoa(*src), inet_ntoa(*dest));
}
}
return 0;
}