Advertisement
Guest User

socket

a guest
Sep 6th, 2014
334
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.17 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. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement