我想使用多线程来捕获和处理IP数据包。一个线程只捕获并存储数据包,比如2秒,之后发送(使用管道)这个数据块到另一个线程,在那里将提取必要的信息。捕获ip数据包,使用RAW套接字和recvfrom(),但recvfrom()为每个循环迭代返回-1。我认为socket不捕获数据包但我找不到原因......任何帮助?这是代码...
void Capture()
{
int rbytes, Rsock;
struct sockaddr saddr;
unsigned char *buffer = (unsigned char *)malloc(65536); /* hold packet */
/* Create a raw socket that shall sniff */
Rsock=socket(AF_PACKET , SOCK_RAW , htons(ETH_P_IP));
if(Rsock < 0)
{
printf("Socket Error\n");
return;
}
while(1)
{
rbytes = recvfrom (Rsock , buffer , 65536 , 0 , &saddr ,(socklen_t *)sizeof saddr);
if(rbytes <=0 )
printf("failed to get packets!");
else
printf("Recv bytes %d: \n", rbytes);
}
}
并且main()是..
int main()
{
pthread_t tid;
int err = pthread_create(&(tid), NULL, (void*)&Capture, NULL);
if (err != 0){
printf("\ncan't create capturing thread :[%s]", strerror(err));
return 0;
}
else
printf("\nCapturing thread created!\n");
pthread_join(tid, NULL);
printf("Finished!!");
return 0;
}
答案 0 :(得分:1)
你最后的两个论点是错误的,
Button button = findViewById(R.something.something);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//perform your operation(s) here.
}
});
不要施放最后一个参数,你需要在实际指针中过去。您还需要传入指向特定sockaddr类型的指针,而不是指向rbytes = recvfrom (Rsock , buffer , 65536 , 0 , &saddr ,(socklen_t *)sizeof saddr);
的指针以及您可能需要转换的参数。
struct sockaddr
如果recvfrom返回-1,您可以检查struct sockaddr_storage saddr; //Or sockaddr_in if you are certain you
// only deal with IPv4...
socklen_t slen = sizeof saddr;
rbytes = recvfrom (Rsock , buffer , 65536 , 0 , (struct sockaddr*)&saddr ,&slen);
值以了解错误,或者只是打印错误,例如: errno