c - 分段错误,创建套接字
问题描述
当我尝试定义套接字时,我不断收到分段错误。这是与代码有关的问题吗?我一直在使用打印语句进行调试,但我还没有找到问题所在。一些打印语句永远不会运行。
代码文件摘录
#include<netinet/in.h>
#include<errno.h>
#include<netdb.h>
#include<stdio.h> //For standard things
#include<stdlib.h> //malloc
#include<string.h> //strlen
#include<netinet/ip_icmp.h> //Provides declarations for icmp header
#include<netinet/udp.h> //Provides declarations for udp header
#include<netinet/tcp.h> //Provides declarations for tcp header
#include<netinet/ip.h> //Provides declarations for ip header
#include<netinet/if_ether.h> //For ETH_P_ALL
#include<net/ethernet.h> //For ether_header
#include<sys/socket.h>
#include<arpa/inet.h>
#include<sys/ioctl.h>
#include<sys/time.h>
#include<sys/types.h>
#include<unistd.h>
FILE *logfile = 0;
struct sockaddr_in source,dest;
int tcp=0,udp=0,icmp=0,others=0,igmp=0,total=0,i,j;
int useLog = 0;
int main()
{
int saddr_size , data_size;
struct sockaddr saddr;
unsigned char *buffer = (unsigned char *) malloc(65536); //Its Big!
if (useLog == 1){
printf("Using Log File");
logfile=fopen("log.txt","w");
}
if(!logfile)
{
printf("Unable to create log.txt file. \n");
}
printf("Starting...\n");
//Create Socket
printf("Here I Am0");
int sock_raw = socket( AF_PACKET , SOCK_RAW , htons(ETH_P_ALL)) ;
//Bind to interface
printf("Here I Am1");
setsockopt(sock_raw , SOL_SOCKET , SO_BINDTODEVICE , "wlan0" , strlen("wlan0")+ 1 );
printf("Here I Am2");
预期输出
该程序可以创建套接字并且可以运行附加的打印语句。
实际输出:
gcc test.c && sudo ./a.out
Unable to create log.txt file.
Starting...
Segmentation fault
任何帮助表示赞赏。
解决方案
推荐阅读
- sql - 两个表的sql视图
- java - 如何使用 Spring Data 通过哈希查询 DynamoDB 表
- java - 在junit中断言arrayList内容时出现断言错误
- node.js - 使用 ajax 从网络服务器获取响应
- python - 如何从互联网访问 jupyter-kernel-gateway Rest api?
- nginx - 文件夹中博客的 nginx 重写解决了永久链接而不是文件
- laravel - Laravel 的范围问题
- javascript - 在 Vue.js 中选择不显示选项
- android - 编号选择器在 Recyclerview 中不起作用
- google-sheets - 修改脚本以在每次进行编辑时将数据验证从列表和编辑该数据验证的时间戳复制到新行