【发布时间】:2013-09-04 10:57:38
【问题描述】:
这个问题是this的下一步。
我将代码更改为使用 AF_PACKET 套接字,但这一次,我的应用程序需要处理大量流量。我决定使用 LSF 过滤器来减少我的应用程序的工作量。
这是我的新程序:
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;
}
根据this,我的套接字的初始化似乎是正确的。但是,最终的 setsockopt 失败并显示“协议不可用”。任何建议将不胜感激。
【问题讨论】:
-
使用
SOCK_RAW需要特定权限;您的应用程序是否以具有此权限的用户身份运行?如果是这样,您的系统是否还具有超出用户的权限(例如应用程序对精细控制功能的权限)? -
@mah 我以 root 身份运行这个程序。此外,如果我不将过滤器附加到我的套接字,我可以从该套接字接收数据包(实际上是很多数据包)。
标签: c linux sockets network-programming setsockopt