首页 > 解决方案 > 分段错误,创建套接字

问题描述

当我尝试定义套接字时,我不断收到分段错误。这是与代码有关的问题吗?我一直在使用打印语句进行调试,但我还没有找到问题所在。一些打印语句永远不会运行。

代码文件摘录

#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

任何帮助表示赞赏。

标签: csocketsnetworking

解决方案


推荐阅读