簡體   English   中英

原始套接字不發送包含任意數據的數據包

[英]Raw socket not sending packets containing arbitrary data

以下面的代碼示例

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檢測到。

為什么會有這樣的差異?

您正在將垃圾放入標頭中。 設置零比設置2的失敗更成功。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM