套接字始终返回-1

问题描述:

我是网络编程的新手,我写了一个简单的代码只是为了获取一个捕获的数据包中的字节数,但我无法启动套接字(总是返回-1)这里是代码:套接字始终返回-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); 
} 

感谢

+10

也许你没有足够的权限来使用'SOCK_RAW'。什么是'errno'?系统调用失败时使用'perror'是个好主意。 –

+2

SOCK_RAW需要root权限。如果您只想发送数据包,请使用SOCK_STREAM(如TCP)或SOCK_DGRAM(如UDP)。 – JvO

+1

为什么不从'socket'获取'-1'后检查'errno',理由会更清楚? (你可以通过'strerror(errno)'得到错误字符串) – tomasz

您需要检查errno证实了这一点(这将是EACCES),但失败是因为你的有效用户不必使用SOCK_RAW类型的插槽许可。