我是网络编程的新手,我写了一个简单的代码只是为了在捕获的数据包中获取一定数量的字节,但是我无法启动套接字(总是返回-1),这是代码:
#include<stdio.h>
#include<arpa/inet.h>
#include<string.h>
#include<stdlib.h>
#include<sys/ioctl.h>
#include<sys/socket.h>
#include<net/if.h>
//#include<netinet/either.h>
#define ETHER_TYPE 0x0800
void main()
{
struct ifreq ifopts;
ssize_t numbytes=0;
int sockfd;
char ifname="eth0";
uint8_t buf[1024];
if((sockfd=socket(AF_INET,SOCK_RAW,0))<0)
{
printf("couldnt start socket \nsockfd = %d\n",sockfd);
exit(1);
}
strncpy(ifopts.ifr_name,ifname,sizeof(ifname)-1);
ioctl(sockfd,SIOCSIFFLAGS,&ifopts);
ifopts.ifr_flags |= IFF_PROMISC;
ioctl(sockfd,SIOCSIFFLAGS,&ifopts);
if((setsockopt(sockfd,SOL_SOCKET,SO_BINDTODEVICE,ifname,sizeof(ifname)-1))<0)
printf("couldnt bind \n");
numbytes=recvfrom(sockfd,buf,1024,0,NULL,NULL);
printf("got packet with size %d",numbytes);
}
谢谢
您将需要进行检查errno
以确认这一点(将是EACCES
),但是失败是因为您的有效用户无权使用type的套接字SOCK_RAW
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句