将过滤器附加到Linux - C中的原始套接字

时间:2021-12-06 23:57:49

That question is the next step of this.

这个问题是下一步。

I changed my code to use AF_PACKET socket, but this time, my application needs to deal with lots of traffic. I decided to use LPF filter in order to decrease the workload of my application.

我更改了代码以使用AF_PACKET套接字,但是这次,我的应用程序需要处理大量的流量。为了减少应用程序的工作量,我决定使用LPF过滤器。

Here is my new program:

这是我的新项目:

struct sock_fprog filter;
int i, lineCount = 0;
int sd;
char tcpdump_command[512];
FILE* tcpdump_output;
sprintf(tcpdump_command, "tcpdump \"udp && src %s && src port %d\" -ddd -s 1600", IP, PORT);
if ( (tcpdump_output = popen(tcpdump_command, "r")) == NULL ) {
    perror("Cannot compile filter using tcpdump.");
    return;
}
if ( fscanf(tcpdump_output, "%d\n", &lineCount) < 1 ) {
    printf("cannot read lineCount.\n");
    return;
}
filter.filter = calloc(sizeof(struct sock_filter)*lineCount,1);
filter.len = lineCount;
for ( i = 0; i < lineCount; i++ ) {
    if (fscanf(tcpdump_output, "%u %u %u %u\n", &(filter.filter[i].code), &(filter.filter[i].jt), &(filter.filter[i].jf), &(filter.filter[i].k)) < 4 ) {
        printf("error in reading line number: %d\n", (i+1));
        return;
    }
}
pclose(tcpdump_output);

sd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if ( sd == -1 )
{
    perror("error in opening sd\n");
    return;
}

if (setsockopt(sd, SOL_PACKET, SO_ATTACH_FILTER, &filter, sizeof(filter)) < 0 )
{
    perror("Cannot attach filter");
    return -5;
}

The initialization of my socket seems correct according to this. However, the final setsockopt fails with "protocol not available". Any suggestion would be highly appriciated.

根据这个,套接字的初始化看起来是正确的。然而,最终的setsockopt失败了,因为“协议不可用”。任何建议都将受到高度重视。

1 个解决方案

#1


2  

Use SOL_SOCKET, from kernel doc filter.txt

使用SOL_SOCKET,来自内核doc filter.txt

Ioctls-

ioctl -

setsockopt(sockfd, SOL_SOCKET, SO_ATTACH_FILTER, &Filter, sizeof(Filter));
setsockopt(sockfd, SOL_SOCKET, SO_DETACH_FILTER, &value, sizeof(value));
setsockopt(sockfd, SOL_SOCKET, SO_LOCK_FILTER, &value, sizeof(value));

#1


2  

Use SOL_SOCKET, from kernel doc filter.txt

使用SOL_SOCKET,来自内核doc filter.txt

Ioctls-

ioctl -

setsockopt(sockfd, SOL_SOCKET, SO_ATTACH_FILTER, &Filter, sizeof(Filter));
setsockopt(sockfd, SOL_SOCKET, SO_DETACH_FILTER, &value, sizeof(value));
setsockopt(sockfd, SOL_SOCKET, SO_LOCK_FILTER, &value, sizeof(value));