以下代码显示了分段错误

时间:2010-11-11 13:47:27

标签: c networking network-programming

为什么以下代码显示分段错误?

int CreateRawSocket(int protocol_to_sniff)
{
    int rawsock;

    if((rawsock = socket(PF_PACKET, SOCK_RAW, htons(protocol_to_sniff)))== -1)
    {
        perror("Error creating raw socket: ");
        exit(-1);
    }

    return rawsock;
}

int BindRawSocketToInterface(char *device, int rawsock, int protocol)
{

    struct sockaddr_ll sll;
    struct ifreq ifr;

    bzero(&sll, sizeof(sll));
     bzero(&ifr,sizeof(ifr));

    /* First Get the Interface Index  */

         char *t=(char*)ifr.ifr_name;
    strncpy(t, device, 1024);
    if((ioctl(rawsock, SIOCGIFINDEX, &ifr)) == -1)
    {
        printf("Error getting Interface index !\n");
        exit(-1);
    }

    /* Bind our raw socket to this interface */

    sll.sll_family = AF_PACKET;
    sll.sll_ifindex = ifr.ifr_ifindex;
    sll.sll_protocol = htons(protocol); 


    if((bind(rawsock, (struct sockaddr *)&sll, sizeof(sll)))== -1)
    {
        perror("Error binding raw socket to interface\n");
        exit(-1);
    }

    return 1;

}

void PrintPacketInHex(unsigned char *packet, int len)
{
    unsigned char *p = packet;

    printf("\n\n---------Packet---Starts----\n\n");

    while(len--)
    {
        printf("%.2x ", *p);
        p++;
    }

    printf("\n\n--------Packet---Ends-----\n\n");

}


main(int argc, char **argv)
{
    int raw;
    unsigned char packet_buffer[2048]; 
    int len;
    int packets_to_sniff;
    struct sockaddr_ll packet_info;
    int packet_info_size = sizeof(packet_info);

    /* create the raw socket */

    raw = CreateRawSocket(ETH_P_IP);

    /* Bind socket to interface */

    BindRawSocketToInterface(argv[1], raw, ETH_P_IP);

    /* Get number of packets to sniff from user */

    packets_to_sniff = atoi(argv[2]);

    /* Start Sniffing and print Hex of every packet */

    while(packets_to_sniff--)
    {
        if((len = recvfrom(raw, packet_buffer, 2048, 0, (struct sockaddr*)&packet_info, &packet_info_size)) == -1)
        {
            perror("Recv from returned -1: ");
            exit(-1);
        }
        else
        {
            /* Packet has been received successfully !! */

            PrintPacketInHex(packet_buffer, len);
        }
    }


    return 0;
}

2 个答案:

答案 0 :(得分:1)

如果没有提供足够的命令行参数,则会因为不检查argc而导致内存冲突。

答案 1 :(得分:1)

崩溃是由例程BindRawSocketToInterface中的这一行引起的:

strncpy(t, device, 1024);

在这里,您已要求strncpy将1024个字节写入char *t请注意strncpy使用指定的空字节数填充目标字符串,请参阅 man strncpy )。

但是t指向的数组不够大,即ifr.ifr_name[IFNAMSIZ]。在我的linux系统上,IFNAMSIZ只有16个。所以strncpy溢出并且会破坏它不应该触及的内存。

更改strncpy参数以匹配数组的正确大小,如下所示可以解决崩溃问题:

strncpy(t, device, IFNAMSIZ);