0

看下面的代码示例

https://gist.github.com/3825444

/*
Testing arbitrary raw ip packets
works only if datagram is filled with 0
filling with anything else will not send any packets, or atleast wireshark does not detect anything
this is strange
*/

#include<stdio.h>
#include<string.h> //memset
#include<sys/socket.h>
#include<stdlib.h> //for exit(0);
#include<errno.h> //For errno - the error number
#include<netinet/tcp.h> //Provides declarations for tcp header
#include<netinet/ip.h>  //Provides declarations for ip header


int main (void)
{
    //Create a raw socket
    int s = socket (PF_INET, SOCK_RAW, IPPROTO_TCP);

    if(s < 0)
    {
        perror("socket");
    }

    //Datagram to represent the packet
    char datagram[4096] , source_ip[32];

    struct sockaddr_in sin;

    strcpy(source_ip , "192.168.1.2");

    sin.sin_family = AF_INET;
    sin.sin_port = htons(80);
    sin.sin_addr.s_addr = inet_addr ("1.2.3.4");

    memset (datagram, 2 , 4096);    /* zero out the buffer */

    //IP_HDRINCL to tell the kernel that headers are included in the packet
    int one = 1;
    const int *val = &one;
    if (setsockopt (s, IPPROTO_IP, IP_HDRINCL, val, sizeof (one)) < 0)
    {
        printf ("Error setting IP_HDRINCL. Error number : %d . Error message : %s \n" , errno , strerror(errno));
        exit(0);
    }

    //Uncommend the loop if you want to flood :)
    while (1)
    {
        //Send the packet
        if (sendto (s,      /* our socket */
                    datagram,   /* the buffer containing headers and data */
                    512,    /* total length of our datagram */
                    0,      /* routing flags, normally always 0 */
                    (struct sockaddr *) &sin,   /* socket addr, just like in */
                    sizeof (sin)) < 0)      /* a normal send() */
        {
            perror("sendto");
        }
        //Data send successfully
        else
        {
            printf ("Packet Send \n");
        }
    }

    return 0;
}

上述程序不会生成任何数据包,或者至少wireshark 不会检测到任何数据包。

但是,如果数据报通过执行填充为 0

memset (datagram, 0 , 4096); /* zero out the buffer */

然后会生成大量数据包并被wireshark检测到。

为什么会有这样的差异?

4

1 回答 1

1

您正在将垃圾放入标题中。设置零成功比设置 2 失败更值得注意。

于 2013-08-09T08:57:48.553 回答