Advertisement
Guest User

socket

a guest
Sep 6th, 2014
419
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.30 KB | None | 0 0
  1.     #include <errno.h>
  2.     #include <unistd.h>
  3.     #include <netdb.h>
  4.     #include <sys/socket.h>
  5.     #include <netinet/in.h>
  6.     #include <stdio.h>
  7.     #include <stdlib.h>
  8.     #include <netinet/ip_icmp.h>
  9.     #include <arpa/inet.h>
  10.     #include <string.h>
  11.      
  12.     char msg[300];
  13.      
  14.     int main()
  15.     {
  16.      
  17.       char adr[] = "127.0.0.1";
  18.      
  19.       int fd=socket(PF_INET,SOCK_DGRAM,IPPROTO_ICMP);
  20.       if (fd==-1) {
  21.         return -1;
  22.       }
  23.      
  24.       const size_t req_size=8;
  25.       struct icmphdr req;
  26.       req.type=8;
  27.       req.code=0;
  28.       req.checksum=0;
  29.       req.un.echo.id=htons(12);
  30.       req.un.echo.sequence=htons(1);
  31.      
  32.       struct sockaddr_in sin;
  33.       sin.sin_family = AF_INET;
  34.       sin.sin_addr.s_addr = inet_addr (adr);
  35.      
  36.       if (sendto(fd,&req,req_size,0,
  37.         (struct sockaddr *) &sin,sizeof(sin))==-1) {
  38.         return -1;
  39.       }
  40.      
  41.      
  42.       int  n = recv(fd, msg, sizeof(msg), 0);
  43.       if(n <= 0) {
  44.         printf("recv fail\n");
  45.         return -1;
  46.       }
  47.      
  48.      
  49.       struct icmphdr rcv_hdr;
  50.       memcpy(&rcv_hdr, msg, sizeof rcv_hdr);
  51.       if (rcv_hdr.type == ICMP_ECHOREPLY) {
  52.         printf("ICMP Reply, id=0x%x, sequence =  0x%x\n",
  53.             rcv_hdr.un.echo.id, rcv_hdr.un.echo.sequence);
  54.       } else {
  55.         printf("Got ICMP packet with type 0x%x ?!?\n", rcv_hdr.type);
  56.       }
  57.      
  58.       return 0;
  59.     }
  60.  
  61.  
  62.  
  63.    
  64.  
  65.     Program output:
  66.     $ ./test
  67.     ICMP Reply, id=0x400, sequence =  0x100
  68.      
  69.      
  70.      
  71.     Tcpdump output:
  72.     $ sudo tcpdump -i lo -X -v icmp
  73.     tcpdump: listening on lo, link-type EN10MB (Ethernet), capture size 65535 bytes
  74.     15:13:55.398941 IP (tos 0x0, ttl 64, id 37644, offset 0, flags [DF], proto ICMP (1), length 28)
  75.         localhost > localhost: ICMP echo request, id 4, seq 1, length 8
  76.             0x0000:  4500 001c 930c 4000 4001 a9d2 7f00 0001  E.....@.@.......
  77.             0x0010:  7f00 0001 0800 f7fa 0004 0001            ............
  78.     15:13:55.398958 IP (tos 0x0, ttl 64, id 37645, offset 0, flags [none], proto ICMP (1), length 28)
  79.         localhost > localhost: ICMP echo reply, id 4, seq 1, length 8
  80.             0x0000:  4500 001c 930d 0000 4001 e9d1 7f00 0001  E.......@.......
  81.             0x0010:  7f00 0001 0000 fffa 0004 0001            ............
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement