GOAL: write a BPF filter which allow just UDP packets from a specific src address and attach it to and UDP socket.
PROBLEM: if I execute the program and I try to send udp packets from a VM which has the correct src IP I don't receive none of them
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <linux/filter.h>
/* udp and src 192.168.56.101 */
struct sock_filter bpfcode[] = {
{ 0x28, 0, 0, 0x0000000c },
{ 0x15, 6, 0, 0x000086dd },
{ 0x15, 0, 5, 0x00000800 },
{ 0x30, 0, 0, 0x00000017 },
{ 0x15, 0, 3, 0x00000011 },
{ 0x20, 0, 0, 0x0000001a },
{ 0x15, 0, 1, 0xc0a83865 },
{ 0x6, 0, 0, 0x00040000 },
{ 0x6, 0, 0, 0x00000000 },
};
int main(void)
{
struct sock_fprog bpf = {
sizeof(bpfcode) / sizeof(struct sock_filter),
bpfcode
};
struct sockaddr_in src = {
.sin_family = AF_INET,
.sin_addr.s_addr = INADDR_ANY,
.sin_port = htons(1025)
};
char buf[1024];
ssize_t res;
int fd, ret;
fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (fd < 0) {
printf("error: socket\n");
exit(EXIT_FAILURE);
}
ret = setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &bpf, sizeof(bpf));
if (ret < 0) {
perror("error: setsockopt\n");
close(fd);
exit(EXIT_FAILURE);
}
ret = bind(fd, (struct sockaddr *)&src, sizeof(src));
if (ret < 0) {
printf("error: bind\n");
close(fd);
exit(EXIT_FAILURE);
}
res = recvfrom(fd, buf, sizeof(buf), 0, NULL, 0);
printf("res = %zi\n", res);
close(fd);
return 0;
}