2012-10-03 95 views
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的將不會檢測到任何。

然而,如果數據報是通過執行

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

然後大量數據包的填充0的生成和由Wireshark的進行檢測。

爲什麼這樣的區別?

回答

1

您正在將垃圾放入標題中。設置零成功比設置2失敗更爲顯着。

相關問題