套接字总是返回-1

时间:2013-12-17 17:55:18

标签: c sockets

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

感谢

1 个答案:

答案 0 :(得分:2)

您需要检查errno以确认这一点(它将是EACCES),但失败的原因是您的有效用户无权使用SOCK_RAW类型的套接字