我是网络编程新手,我编写了一个简单的代码只是为了获取捕获的数据包中的字节数,但我无法启动套接字(总是返回-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
),但失败是因为您的有效用户没有使用套接字的权限输入SOCK_RAW
。
关于c - 套接字总是返回-1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20641341/