c - 套接字总是返回-1

标签 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);
}

谢谢

最佳答案

您需要检查errno来确认这一点(它将是EACCES),但失败是因为您的有效用户没有使用套接字的权限输入SOCK_RAW

关于c - 套接字总是返回-1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20641341/

相关文章:

c - 在 C 中 ':' 是做什么的?

c - 我在哪里定义 C 中的 const 数组?

c - 根据 CERT 编码规则 POS49-C,访问共享结构中相邻成员时的竞争条件?

c - 对于 C 开发人员来说,学习 LISP 最快、最不痛苦的方法是什么?

c - 警告 : implicit declaration of function 'system'

c - 打印句子中每个单词的第一个字母

linux - 监听端口上的选择性多播组

c# - 使用 C# 在 Linux 防火墙后接收大型 UDP 数据包失败

c - 使用套接字传输文件服务器/客户端 linux C

php - 如何找出接收到的udp数据包的数据大小