Reference:https://github.com/davidgatti/How-to-Deconstruct-Ping-with-C-and-NodeJS
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<arpa/inet.h> 4 #include<sys/socket.h> 5 #include<fcntl.h> 6 #include<unistd.h> 7 #include<netdb.h> 8 9 int32_t checksum(uint16_t * buf,int32_t len); 10 int main(int argc,char * argv[]){ 11 int s = socket(PF_INET,SOCK_RAW,1); 12 if(s <= 0){ 13 perror("Socker error"); 14 exit(0); 15 } 16 typedef struct{ 17 uint8_t type; 18 uint8_t code; 19 uint16_t chksum; 20 uint16_t identifier; 21 uint16_t sequence_number; 22 uint32_t data; 23 }icmp_hdr_t; 24 icmp_hdr_t pckt; 25 pckt.type = 8; 26 pckt.code = 0; 27 pckt.chksum = 0; 28 pckt.identifier = getpid(); 29 printf("My pid:%04X\n\n", pckt.identifier); 30 pckt.sequence_number = 1; 31 pckt.data = 0; 32 pckt.chksum = checksum((uint16_t * )&pckt,sizeof(pckt)); 33 struct sockaddr_in addr; 34 addr.sin_family=AF_INET; 35 addr.sin_port = 0; 36 addr.sin_addr.s_addr = inet_addr(argv[1]); 37 int actionSendResult = sendto(s,&pckt,sizeof(pckt),0,(struct sockaddr *)&addr,sizeof(addr)); 38 if(actionSendResult<=0){ 39 perror("Ping Error"); 40 exit(0); 41 } 42 unsigned int resAddressSize; 43 unsigned char res[100]=""; 44 struct sockaddr resAddress; 45 typedef struct{ 46 uint8_t type; 47 uint8_t code; 48 uint16_t chksum; 49 uint16_t identifier; 50 uint16_t sequence_number; 51 }icmp_response_t; 52 int ressponse = recvfrom(s,res,sizeof(res),0,&resAddress,&resAddressSize); 53 if(ressponse>0){ 54 icmp_response_t * echo_response; 55 echo_response = (icmp_response_t * )&res[20]; 56 printf("Response looks like:\n"); 57 for(int i=0;i<ressponse;i++) printf("%02hhX ",res[i]); 58 printf("\n\n" ); 59 printf("type:%02hhX,code:%02hhX,chksum:%04X\nidentifier:%04X,sequence:%04X\n\n",echo_response->type,echo_response->code,echo_response->chksum,echo_response->identifier,echo_response->sequence_number ); 60 exit(0); 61 } 62 else{ 63 perror("Response Error"); 64 exit(0); 65 } 66 return 0; 67 } 68 int32_t checksum(uint16_t * buf,int32_t len){ 69 int32_t nleft=len; 70 int32_t sum=0; 71 uint16_t * w=buf; 72 uint16_t answer=0; 73 while (nleft>1) { 74 sum+=*w++; 75 nleft-=2; 76 } 77 if(nleft==1){ 78 sum+=*(uint8_t * )w; 79 } 80 sum=(sum>>16)+(sum&0xFFFF); 81 sum+=(sum>>16); 82 answer=~sum; 83 return answer;}
Ping Can not Touch
Wireshark has catch nothing but recvfrom() get blows response
My pid:10F5
Response looks like:
45 [C0] [00 3C] [3D BD] 00 00 40 01 [E3 77]
区分服务领域 1100 Identification HeaderCheckSum
[AC 10 00 56] [AC 10 00 56] 03 01 FC FE 00 00 00 00
Host Unreachable
45 00 [00 20]:32 [05 DB] 40 00 40 01 [DC 54]
[AC 10 00 56] [AC 10 00 37]
08 00 16 0E [F5 10] EC E0 00 00 00 00
type:03,code:01,chksum:FEFC
identifier:0000,sequence:0000
_________________________________________
|___type____|___code____|____checksum_______|
|____identifier___|____sequence_number________|
|________________data_____________________|
the package include ac100037 all about:
ARP: Who has 172.16.0.55? Tell 172.16.0.86