Code source du PING

Code source du PING - C++ - Programmation

Marsh Posté le 27-12-2002 à 16:16:23    

Bonjour. je commence cette année la programmation,donc je cherche des ressoureces interéssantes pour progresser.
J'ai entendu dire que lire du code etait un bon moyen
de progresser. Dans ce cas ou peut on trouver du code
source a lire?
 
et ou pourais-je en particulier trouver le code
source du programe PING?
 
merci d'avance :)


---------------
http://www.core-tx.com
Reply

Marsh Posté le 27-12-2002 à 16:16:23   

Reply

Marsh Posté le 27-12-2002 à 17:21:20    

tu peux le trouvé dans msdn je crois
ca utilise ipx il me semble

Reply

Marsh Posté le 27-12-2002 à 17:27:24    

Sanglier04 a écrit :

tu peux le trouvé dans msdn je crois
ca utilise ipx il me semble

N'importe koi toi :heink:  
Tu peux utiliser les RAW sockets..
 

Code :
  1. // Module Name: Ping.c
  2. //
  3. // Description:
  4. //    This sample illustrates how an ICMP ping app can be written
  5. //    using the SOCK_RAW socket type and IPPROTO_ICMP protocol.
  6. //    By creating a raw socket, the underlying layer does not change
  7. //    the protocol header so that when we submit the ICMP header
  8. //    nothing is changed so that the receiving end will see an  
  9. //    ICMP packet. Additionally, we use the record route IP option
  10. //    to get a round trip path to the endpoint. Note that the size
  11. //    of the IP option header that records the route is limited to
  12. //    nine IP addresses.
  13. //
  14. // Compile:
  15. //     cl -o Ping Ping.c ws2_32.lib /Zp1
  16. //
  17. // Command Line Options/Parameters:
  18. //     Ping [host] [packet-size]
  19. //     
  20. //     host         String name of host to ping
  21. //     packet-size  Integer size of packet to send  
  22. //                      (smaller than 1024 bytes)
  23. //
  24. //#pragma pack(1)
  25. #define WIN32_LEAN_AND_MEAN
  26. #include <winsock2.h>
  27. #include <ws2tcpip.h>
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #define IP_RECORD_ROUTE  0x7
  31. //  
  32. // IP header structure
  33. //
  34. typedef struct _iphdr
  35. {
  36.     unsigned int   h_len:4;        // Length of the header
  37.     unsigned int   version:4;      // Version of IP
  38.     unsigned char  tos;            // Type of service
  39.     unsigned short total_len;      // Total length of the packet
  40.     unsigned short ident;          // Unique identifier
  41.     unsigned short frag_and_flags; // Flags
  42.     unsigned char  ttl;            // Time to live
  43.     unsigned char  proto;          // Protocol (TCP, UDP etc)
  44.     unsigned short checksum;       // IP checksum
  45.     unsigned int   sourceIP;
  46.     unsigned int   destIP;
  47. } IpHeader;
  48. #define ICMP_ECHO        8
  49. #define ICMP_ECHOREPLY   0
  50. #define ICMP_MIN         8 // Minimum 8-byte ICMP packet (header)
  51. //
  52. // ICMP header structure
  53. //
  54. typedef struct _icmphdr
  55. {
  56.     BYTE   i_type;
  57.     BYTE   i_code;                 // Type sub code
  58.     USHORT i_cksum;
  59.     USHORT i_id;
  60.     USHORT i_seq;
  61.     // This is not the standard header, but we reserve space for time
  62.     ULONG  timestamp;
  63. } IcmpHeader;
  64. //
  65. // IP option header - use with socket option IP_OPTIONS
  66. //
  67. typedef struct _ipoptionhdr
  68. {
  69.     unsigned char        code;        // Option type
  70.     unsigned char        len;         // Length of option hdr
  71.     unsigned char        ptr;         // Offset into options
  72.     unsigned long        addr[9];     // List of IP addrs
  73. } IpOptionHeader;
  74. #define DEF_PACKET_SIZE  32        // Default packet size
  75. #define MAX_PACKET       1024      // Max ICMP packet size
  76. #define MAX_IP_HDR_SIZE  60        // Max IP header size w/options
  77. BOOL  bRecordRoute;
  78. int   datasize;
  79. char *lpdest;
  80. //
  81. // Function: usage
  82. //
  83. // Description:
  84. //    Print usage information
  85. //
  86. void usage(char *progname)
  87. {
  88.     printf("usage: ping -r <host> [data size]\n" );
  89.     printf("       -r           record route\n" );
  90.     printf("        host        remote machine to ping\n" );
  91.     printf("        datasize    can be up to 1KB\n" );
  92.     ExitProcess(-1);
  93. }
  94. //  
  95. // Function: FillICMPData
  96. //
  97. // Description:
  98. //    Helper function to fill in various fields for our ICMP request
  99. //
  100. void FillICMPData(char *icmp_data, int datasize)
  101. {
  102.     IcmpHeader *icmp_hdr = NULL;
  103.     char       *datapart = NULL;
  104.     icmp_hdr = (IcmpHeader*)icmp_data;
  105.     icmp_hdr->i_type = ICMP_ECHO;        // Request an ICMP echo
  106.     icmp_hdr->i_code = 0;
  107.     icmp_hdr->i_id = (USHORT)GetCurrentProcessId();
  108.     icmp_hdr->i_cksum = 0;
  109.     icmp_hdr->i_seq = 0;
  110.  
  111.     datapart = icmp_data + sizeof(IcmpHeader);
  112.     //
  113.     // Place some junk in the buffer
  114.     //
  115.     memset(datapart,'E', datasize - sizeof(IcmpHeader));
  116. }
  117. //  
  118. // Function: checksum
  119. //
  120. // Description:
  121. //    This function calculates the 16-bit one's complement sum
  122. //    of the supplied buffer (ICMP) header
  123. //
  124. USHORT checksum(USHORT *buffer, int size)
  125. {
  126.     unsigned long cksum=0;
  127.     while (size > 1)
  128.     {
  129.         cksum += *buffer++;
  130.         size -= sizeof(USHORT);
  131.     }
  132.     if (size)
  133.     {
  134.         cksum += *(UCHAR*)buffer;
  135.     }
  136.     cksum = (cksum >> 16) + (cksum & 0xffff);
  137.     cksum += (cksum >>16);
  138.     return (USHORT)(~cksum);
  139. }
  140. //
  141. // Function: DecodeIPOptions
  142. //
  143. // Description:
  144. //    If the IP option header is present, find the IP options
  145. //    within the IP header and print the record route option
  146. //    values
  147. //
  148. void DecodeIPOptions(char *buf, int bytes)
  149. {
  150.     IpOptionHeader *ipopt = NULL;
  151.     IN_ADDR         inaddr;
  152.     int             i;
  153.     HOSTENT        *host = NULL;
  154.     ipopt = (IpOptionHeader *)(buf + 20);
  155.     printf("RR:   " );
  156.     for(i = 0; i < (ipopt->ptr / 4) - 1; i++)
  157.     {
  158.         inaddr.S_un.S_addr = ipopt->addr[i];
  159.         if (i != 0)
  160.             printf("      " );
  161.         host = gethostbyaddr((char *)&inaddr.S_un.S_addr,
  162.                     sizeof(inaddr.S_un.S_addr), AF_INET);
  163.         if (host)
  164.             printf("(%-15s) %s\n", inet_ntoa(inaddr), host->h_name);
  165.         else
  166.             printf("(%-15s)\n", inet_ntoa(inaddr));
  167.     }
  168.     return;
  169. }
  170. //
  171. // Function: DecodeICMPHeader
  172. //
  173. // Description:
  174. //    The response is an IP packet. We must decode the IP header to
  175. //    locate the ICMP data.
  176. //
  177. void DecodeICMPHeader(char *buf, int bytes,
  178.     struct sockaddr_in *from)
  179. {
  180.     IpHeader       *iphdr = NULL;
  181.     IcmpHeader     *icmphdr = NULL;
  182.     unsigned short  iphdrlen;
  183.     DWORD           tick;
  184.     static   int    icmpcount = 0;
  185.     iphdr = (IpHeader *)buf;
  186. // Number of 32-bit words * 4 = bytes
  187.     iphdrlen = iphdr->h_len * 4;
  188.     tick = GetTickCount();
  189.     if ((iphdrlen == MAX_IP_HDR_SIZE) && (!icmpcount))
  190.         DecodeIPOptions(buf, bytes);
  191.     if (bytes  < iphdrlen + ICMP_MIN)
  192.     {
  193.         printf("Too few bytes from %s\n",
  194.             inet_ntoa(from->sin_addr));
  195.     }
  196.     icmphdr = (IcmpHeader*)(buf + iphdrlen);
  197.     if (icmphdr->i_type != ICMP_ECHOREPLY)
  198.     {
  199.         printf("nonecho type %d recvd\n", icmphdr->i_type);
  200.         return;
  201.     }
  202.     // Make sure this is an ICMP reply to something we sent!
  203.     //
  204.     if (icmphdr->i_id != (USHORT)GetCurrentProcessId())
  205.     {
  206.         printf("someone else's packet!\n" );
  207.         return ;
  208.     }
  209.     printf("%d bytes from %s:", bytes, inet_ntoa(from->sin_addr));
  210.     printf(" icmp_seq = %d. ", icmphdr->i_seq);
  211.     printf(" time: %d ms", tick - icmphdr->timestamp);
  212.     printf("\n" );
  213.     icmpcount++;
  214.     return;
  215. }
  216. void ValidateArgs(int argc, char **argv)
  217. {
  218.     int                i;
  219.     bRecordRoute = FALSE;
  220.     lpdest = NULL;
  221.     datasize = DEF_PACKET_SIZE;
  222.    
  223.     for(i = 1; i < argc; i++)
  224.     {
  225.         if ((argv[i][0] == '-') || (argv[i][0] == '/'))
  226.         {
  227.             switch (tolower(argv[i][1]))
  228.             {
  229.                 case 'r':        // Record route option
  230.                     bRecordRoute = TRUE;
  231.                     break;
  232.                 default:
  233.                     usage(argv[0]);
  234.                     break;
  235.             }
  236.         }
  237.         else if (isdigit(argv[i][0]))
  238.             datasize = atoi(argv[i]);
  239.         else
  240.             lpdest = argv[i];
  241.     }
  242. }
  243.        
  244. //
  245. // Function: main
  246. //
  247. // Description:
  248. //    Setup the ICMP raw socket, and create the ICMP header. Add
  249. //    the appropriate IP option header, and start sending ICMP
  250. //    echo requests to the endpoint. For each send and receive,
  251. //    we set a timeout value so that we don't wait forever for a  
  252. //    response in case the endpoint is not responding. When we
  253. //    receive a packet decode it.
  254. //
  255. int main(int argc, char **argv)
  256. {
  257.     WSADATA            wsaData;
  258.     SOCKET             sockRaw = INVALID_SOCKET;
  259.     struct sockaddr_in dest,
  260.                        from;
  261.     int                bread,
  262.                        fromlen = sizeof(from),
  263.                        timeout = 1000,
  264.                        ret;
  265.     char              *icmp_data = NULL,
  266.                       *recvbuf = NULL;
  267.     unsigned int       addr = 0;
  268.     USHORT             seq_no = 0;
  269.     struct hostent    *hp = NULL;
  270.     IpOptionHeader     ipopt;
  271.     if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
  272.     {
  273.         printf("WSAStartup() failed: %d\n", GetLastError());
  274.         return -1;
  275.     }
  276.     ValidateArgs(argc, argv);
  277.     //
  278.     // WSA_FLAG_OVERLAPPED flag is required for SO_RCVTIMEO,  
  279.     // SO_SNDTIMEO option. If NULL is used as last param for  
  280.     // WSASocket, all I/O on the socket is synchronous, the  
  281.     // internal user mode wait code never gets a chance to  
  282.     // execute, and therefore kernel-mode I/O blocks forever.  
  283.     // A socket created via the socket function has the over-
  284.  // lapped I/O attribute set internally. But here we need  
  285.  // to use WSASocket to specify a raw socket.
  286.     //
  287.     // If you want to use timeout with a synchronous  
  288.     // nonoverlapped socket created by WSASocket with last  
  289.  // param set to NULL, you can set the timeout by using  
  290.  // the select function, or you can use WSAEventSelect and  
  291.  // set the timeout in the WSAWaitForMultipleEvents  
  292.  // function.
  293.     //
  294.     sockRaw = WSASocket (AF_INET, SOCK_RAW, IPPROTO_ICMP, NULL, 0,
  295.                          WSA_FLAG_OVERLAPPED);
  296.     if (sockRaw == INVALID_SOCKET)
  297.     {
  298.         printf("WSASocket() failed: %d\n", WSAGetLastError());
  299.         return -1;
  300.     }
  301.     if (bRecordRoute)
  302.     {
  303.         // Setup the IP option header to go out on every ICMP packet
  304.         //
  305.         ZeroMemory(&ipopt, sizeof(ipopt));
  306.         ipopt.code = IP_RECORD_ROUTE; // Record route option
  307.         ipopt.ptr  = 4;               // Point to the first addr offset
  308.         ipopt.len  = 39;              // Length of option header
  309.  
  310.         ret = setsockopt(sockRaw, IPPROTO_IP, IP_OPTIONS,
  311.             (char *)&ipopt, sizeof(ipopt));
  312.         if (ret == SOCKET_ERROR)
  313.         {
  314.             printf("setsockopt(IP_OPTIONS) failed: %d\n",
  315.                 WSAGetLastError());
  316.         }
  317.     }
  318.     // Set the send/recv timeout values
  319.     //
  320.     bread = setsockopt(sockRaw, SOL_SOCKET, SO_RCVTIMEO,
  321.                 (char*)&timeout, sizeof(timeout));
  322.     if(bread == SOCKET_ERROR)
  323.     {
  324.         printf("setsockopt(SO_RCVTIMEO) failed: %d\n",
  325.             WSAGetLastError());
  326.         return -1;
  327.     }
  328.     timeout = 1000;
  329.     bread = setsockopt(sockRaw, SOL_SOCKET, SO_SNDTIMEO,
  330.                 (char*)&timeout, sizeof(timeout));
  331.     if (bread == SOCKET_ERROR)
  332.     {
  333.         printf("setsockopt(SO_SNDTIMEO) failed: %d\n",
  334.             WSAGetLastError());
  335.         return -1;
  336.     }
  337.     memset(&dest, 0, sizeof(dest));
  338.     //
  339.     // Resolve the endpoint's name if necessary
  340.     //
  341.     dest.sin_family = AF_INET;
  342.     if ((dest.sin_addr.s_addr = inet_addr(lpdest)) == INADDR_NONE)
  343.     {
  344.         if ((hp = gethostbyname(lpdest)) != NULL)
  345.         {
  346.             memcpy(&(dest.sin_addr), hp->h_addr, hp->h_length);
  347.             dest.sin_family = hp->h_addrtype;
  348.             printf("dest.sin_addr = %s\n", inet_ntoa(dest.sin_addr));
  349.         }
  350.         else
  351.         {
  352.             printf("gethostbyname() failed: %d\n",
  353.                 WSAGetLastError());
  354.             return -1;
  355.         }
  356.     }       
  357.     //  
  358.     // Create the ICMP packet
  359.     //       
  360.     datasize += sizeof(IcmpHeader); 
  361.     icmp_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
  362.                   MAX_PACKET);
  363.     recvbuf = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
  364.                   MAX_PACKET);
  365.     if (!icmp_data)
  366.     {
  367.         printf("HeapAlloc() failed: %d\n", GetLastError());
  368.         return -1;
  369.     }
  370.     memset(icmp_data,0,MAX_PACKET);
  371.     FillICMPData(icmp_data,datasize);
  372.     //
  373.     // Start sending/receiving ICMP packets
  374.     //
  375.     while(1)
  376.     {
  377.         static int nCount = 0;
  378.         int        bwrote;
  379.                
  380.         if (nCount++ == 4)
  381.             break;
  382.                
  383.         ((IcmpHeader*)icmp_data)->i_cksum = 0;
  384.         ((IcmpHeader*)icmp_data)->timestamp = GetTickCount();
  385.         ((IcmpHeader*)icmp_data)->i_seq = seq_no++;
  386.         ((IcmpHeader*)icmp_data)->i_cksum =
  387.             checksum((USHORT*)icmp_data, datasize);
  388.         bwrote = sendto(sockRaw, icmp_data, datasize, 0,
  389.                      (struct sockaddr*)&dest, sizeof(dest));
  390.         if (bwrote == SOCKET_ERROR)
  391.         {
  392.             if (WSAGetLastError() == WSAETIMEDOUT)
  393.             {
  394.                 printf("timed out\n" );
  395.                 continue;
  396.             }
  397.             printf("sendto() failed: %d\n", WSAGetLastError());
  398.             return -1;
  399.         }
  400.         if (bwrote < datasize)
  401.         {
  402.             printf("Wrote %d bytes\n", bwrote);
  403.         }
  404.         bread = recvfrom(sockRaw, recvbuf, MAX_PACKET, 0,
  405.                     (struct sockaddr*)&from, &fromlen);
  406.         if (bread == SOCKET_ERROR)
  407.         {
  408.             if (WSAGetLastError() == WSAETIMEDOUT)
  409.             {
  410.                 printf("timed out\n" );
  411.                 continue;
  412.             }
  413.             printf("recvfrom() failed: %d\n", WSAGetLastError());
  414.             return -1;
  415.         }
  416.         DecodeICMPHeader(recvbuf, bread, &from);
  417.         Sleep(1000);
  418.     }
  419.     // Cleanup
  420.     //
  421.     if (sockRaw != INVALID_SOCKET)
  422.         closesocket(sockRaw);
  423.     HeapFree(GetProcessHeap(), 0, recvbuf);
  424.     HeapFree(GetProcessHeap(), 0, icmp_data);
  425.     WSACleanup();
  426.     return 0;
  427. }


 
Ah oui,  [:google] c'est bien parfois tu sais..

Reply

Marsh Posté le 27-12-2002 à 17:33:00    

+1 et d'accord avec toi mais donner le lien où tu as trouvé le code serait la moindre des choses ;)
 
:hello:

Reply

Marsh Posté le 27-12-2002 à 17:34:11    

Bah j'ai donné tous les mots clés, y'a qu'à les retapper dans google, raw socket ping c++ et ça se trouve en 1ère page :)
 
 :hello:


Message édité par *syl* le 27-12-2002 à 17:34:51
Reply

Marsh Posté le 27-12-2002 à 17:36:31    

au pasage une question :
#define WIN32_LEAN_AND_MEAN
j'ai jamais pigé ce que ca fesait. A quoi ca sert ?


---------------
FAQ fclc++ - FAQ C++ - C++ FAQ Lite
Reply

Marsh Posté le 27-12-2002 à 17:38:01    

1ère réponse dans google :

Citation :

It disables or enables some parts of typedefs in windows.h.


 
 :D

Reply

Marsh Posté le 27-12-2002 à 18:00:57    

merci pour ça:)
sinon pouriez vous me conseiller un site ou l'on trouve
des codes sources de programmes simples?


---------------
http://www.core-tx.com
Reply

Marsh Posté le 27-12-2002 à 18:01:46    

HelloWorld a écrit :

au pasage une question :
#define WIN32_LEAN_AND_MEAN
j'ai jamais pigé ce que ca fesait. A quoi ca sert ?


recherche google msdn, + pratique :
http://www.google.com/search?sourc [...] ND%5FMEAN+

Reply

Marsh Posté le 27-12-2002 à 18:02:53    

youdontcare>
"To see the list of header files specifically excluded from MFC builds, look at the definition of WIN32_LEAN_AND_MEAN in WINDOWS.H"
bon ben je vais faire une petite recherche dans les header windows alors ... :crazy:
 
sky99>ca depent quels genres de progs, et ce que tu entends par simple.
la msdn + sdk fournit plein de sources simples pour expliquer l'utilisation de certaines fonctions.


Message édité par HelloWorld le 27-12-2002 à 18:05:26

---------------
FAQ fclc++ - FAQ C++ - C++ FAQ Lite
Reply

Marsh Posté le 27-12-2002 à 18:02:53   

Reply

Marsh Posté le 27-12-2002 à 18:03:48    

Sky99 a écrit :

merci pour ça:)
sinon pouriez vous me conseiller un site ou l'on trouve
des codes sources de programmes simples?

question très vague ... tu peux par exemple downloader les sources de linux / freebsd et regarder les sources des commandes les plus simples ... chopper les sources de quake ... bref, y'a de quoi faire.

Reply

Marsh Posté le 27-12-2002 à 19:01:59    

merci pour ça:)
sinon pouriez vous me conseiller un site ou l'on trouve
des codes sources de programmes simples?


---------------
http://www.core-tx.com
Reply

Marsh Posté le 27-12-2002 à 19:12:15    

tain!!
 
les [][] c mal   :kaola: :pfff:


---------------
"-Dites 33. -Export!!" [:nokbilong]
Reply

Marsh Posté le 27-12-2002 à 19:12:55    

Sky99 a écrit :

merci pour ça:)
sinon pouriez vous me conseiller un site ou l'on trouve
des codes sources de programmes simples?


 
 
www.developpez.com doit avoir avoir des tuts avce des exemples


---------------
"-Dites 33. -Export!!" [:nokbilong]
Reply

Marsh Posté le 27-12-2002 à 19:31:58    

Nokbilong a écrit :

tain!!
 
les [][] c mal   :kaola: :pfff:  


ça veut dire quoi ça?
si c'est a propos des crochets dans le titre [C,C++]
je ne les ai pas mis, ils sont insérés automatiquement...


---------------
http://www.core-tx.com
Reply

Marsh Posté le 27-12-2002 à 19:34:00    

sinon pour les programmes,je pense que je pourrai me debrouiller avec ce que j'ai la...
 
merci beaucoup!


---------------
http://www.core-tx.com
Reply

Marsh Posté le 27-12-2002 à 19:39:17    

Sky99 a écrit :


ça veut dire quoi ça?
si c'est a propos des crochets dans le titre [C,C++]
je ne les ai pas mis, ils sont insérés automatiquement...


 
 
nop :)
 
pour les **char
y'a des [][]
perso j'aime pas :/
 
(je dis pas que c pas pratique dans certain cas hein)
mais c vraiment la chiotte pour lire le code je trouve
 
y'en a dans le code + haut


---------------
"-Dites 33. -Export!!" [:nokbilong]
Reply

Marsh Posté le 28-12-2002 à 00:01:22    

Le code d'iputils-ping :
 

Code :
  1. /*
  2. * Copyright (c) 1989 The Regents of the University of California.
  3. * All rights reserved.
  4. *
  5. * This code is derived from software contributed to Berkeley by
  6. * Mike Muuss.
  7. *
  8. * Redistribution and use in source and binary forms, with or without
  9. * modification, are permitted provided that the following conditions
  10. * are met:
  11. * 1. Redistributions of source code must retain the above copyright
  12. *    notice, this list of conditions and the following disclaimer.
  13. * 2. Redistributions in binary form must reproduce the above copyright
  14. *    notice, this list of conditions and the following disclaimer in the
  15. *    documentation and/or other materials provided with the distribution.
  16. * 3. All advertising materials mentioning features or use of this software
  17. *    must display the following acknowledgement:
  18. * This product includes software developed by the University of
  19. * California, Berkeley and its contributors.
  20. * 4. Neither the name of the University nor the names of its contributors
  21. *    may be used to endorse or promote products derived from this software
  22. *    without specific prior written permission.
  23. *
  24. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  25. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  26. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  27. * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  28. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  29. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  30. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  31. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  32. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  33. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  34. * SUCH DAMAGE.
  35. */
  36. #ifndef lint
  37. char copyright[] =
  38. "@(#) Copyright (c) 1989 The Regents of the University of California.\n\
  39. All rights reserved.\n";
  40. #endif /* not lint */
  41. /*
  42. *   P I N G . C
  43. *
  44. * Using the InterNet Control Message Protocol (ICMP) "ECHO" facility,
  45. * measure round-trip-delays and packet loss across network paths.
  46. *
  47. * Author -
  48. * Mike Muuss
  49. * U. S. Army Ballistic Research Laboratory
  50. * December, 1983
  51. *
  52. * Status -
  53. * Public Domain.  Distribution Unlimited.
  54. * Bugs -
  55. * More statistics could always be gathered.
  56. * This program has to run SUID to ROOT to access the ICMP socket.
  57. */
  58. #include "ping_common.h"
  59. #include <netinet/ip.h>
  60. #include <netinet/ip_icmp.h>
  61. #define MAXIPLEN 60
  62. #define MAXICMPLEN 76
  63. #define NROUTES  9  /* number of record route slots */
  64. #define TOS_MAX  255  /* 8-bit TOS field */
  65. static int ts_type;
  66. static int nroute = 0;
  67. static __u32 route[10];
  68. struct sockaddr_in whereto; /* who to ping */
  69. int optlen = 0;
  70. int settos = 0;   /* Set TOS, Precendence or other QOS options */
  71. int icmp_sock;   /* socket file descriptor */
  72. u_char outpack[0x10000];
  73. int maxpacket = sizeof(outpack);
  74. static int broadcast_pings = 0;
  75. static char *pr_addr(__u32);
  76. static void pr_options(unsigned char * cp, int hlen);
  77. static void pr_iph(struct iphdr *ip);
  78. static void usage(void) __attribute__((noreturn));
  79. static u_short in_cksum(const u_short *addr, int len, u_short salt);
  80. static void pr_icmph(__u8 type, __u8 code, __u32 info, struct icmphdr *icp);
  81. static int parsetos(char *str);
  82. static struct {
  83. struct cmsghdr cm;
  84. struct in_pktinfo ipi;
  85. } cmsg = { {sizeof(struct cmsghdr) + sizeof(struct in_pktinfo), SOL_IP, IP_PKTINFO},
  86.    {0, }};
  87. int cmsg_len;
  88. struct sockaddr_in source;
  89. char *device;
  90. int pmtudisc = -1;
  91. int
  92. main(int argc, char **argv)
  93. {
  94. struct hostent *hp;
  95. int ch, hold, packlen;
  96. int socket_errno;
  97. u_char *packet;
  98. char *target, hnamebuf[MAXHOSTNAMELEN];
  99. char rspace[3 + 4 * NROUTES + 1]; /* record route space */
  100. icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
  101. socket_errno = errno;
  102. uid = getuid();
  103. setuid(uid);
  104. source.sin_family = AF_INET;
  105. preload = 1;
  106. while ((ch = getopt(argc, argv, COMMON_OPTSTR "bRT:" )) != EOF) {
  107.  switch(ch) {
  108.  case 'b':
  109.          broadcast_pings = 1;
  110.   break;
  111.  case 'Q':
  112.   settos = parsetos(optarg);
  113.   if (settos &&
  114.       (setsockopt(icmp_sock, IPPROTO_IP, IP_TOS,
  115.     (char *)&settos, sizeof(int)) < 0)) {
  116.    perror("ping: error setting QOS sockopts" );
  117.    exit(2);
  118.   }
  119.   break;
  120.  case 'R':
  121.   if (options & F_TIMESTAMP) {
  122.    fprintf(stderr, "Only one of -T or -R may be used\n" );
  123.    exit(2);
  124.   }
  125.   options |= F_RROUTE;
  126.   break;
  127.  case 'T':
  128.   if (options & F_RROUTE) {
  129.    fprintf(stderr, "Only one of -T or -R may be used\n" );
  130.    exit(2);
  131.   }
  132.   options |= F_TIMESTAMP;
  133.   if (strcmp(optarg, "tsonly" ) == 0)
  134.    ts_type = IPOPT_TS_TSONLY;
  135.   else if (strcmp(optarg, "tsandaddr" ) == 0)
  136.    ts_type = IPOPT_TS_TSANDADDR;
  137.   else if (strcmp(optarg, "tsprespec" ) == 0)
  138.    ts_type = IPOPT_TS_PRESPEC;
  139.   else {
  140.    fprintf(stderr, "Invalid timestamp type\n" );
  141.    exit(2);
  142.   }
  143.   break;
  144.  case 'I':
  145.  {
  146.   char dummy;
  147.   int i1, i2, i3, i4;
  148.   if (sscanf(optarg, "%u.%u.%u.%u%c",
  149.       &i1, &i2, &i3, &i4, &dummy) == 4) {
  150.    __u8 *ptr;
  151.    ptr = (__u8*)&source.sin_addr;
  152.    ptr[0] = i1;
  153.    ptr[1] = i2;
  154.    ptr[2] = i3;
  155.    ptr[3] = i4;
  156.    options |= F_STRICTSOURCE;
  157.   } else {
  158.    device = optarg;
  159.   }
  160.   break;
  161.  }
  162.  case 'M':
  163.   if (strcmp(optarg, "do" ) == 0)
  164.    pmtudisc = IP_PMTUDISC_DO;
  165.   else if (strcmp(optarg, "dont" ) == 0)
  166.    pmtudisc = IP_PMTUDISC_DONT;
  167.   else if (strcmp(optarg, "want" ) == 0)
  168.    pmtudisc = IP_PMTUDISC_WANT;
  169.   else {
  170.    fprintf(stderr, "ping: wrong value for -M: do, dont, want are valid ones.\n" );
  171.    exit(2);
  172.   }
  173.   break;
  174.  case 'V':
  175.   printf("ping utility, iputils-ss%s\n", SNAPSHOT);
  176.   exit(0);
  177.  COMMON_OPTIONS
  178.   common_options(ch);
  179.   break;
  180.  default:
  181.   usage();
  182.  }
  183. }
  184. argc -= optind;
  185. argv += optind;
  186. if (argc == 0)
  187.  usage();
  188. if (argc > 1) {
  189.  if (options & F_RROUTE)
  190.   usage();
  191.  else if (options & F_TIMESTAMP) {
  192.   if (ts_type != IPOPT_TS_PRESPEC)
  193.    usage();
  194.   if (argc > 5)
  195.    usage();
  196.  } else {
  197.   if (argc > 10)
  198.    usage();
  199.   options |= F_SOURCEROUTE;
  200.  }
  201. }
  202. while (argc > 0) {
  203.  target = *argv;
  204.  bzero((char *)&whereto, sizeof(whereto));
  205.  whereto.sin_family = AF_INET;
  206.  if (inet_aton(target, &whereto.sin_addr) == 1) {
  207.   hostname = target;
  208.   if (argc == 1)
  209.    options |= F_NUMERIC;
  210.  } else {
  211.   hp = gethostbyname(target);
  212.   if (!hp) {
  213.    fprintf(stderr, "ping: unknown host %s\n", target);
  214.    exit(2);
  215.   }
  216.   memcpy(&whereto.sin_addr, hp->h_addr, 4);
  217.   strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1);
  218.   hnamebuf[sizeof(hnamebuf) - 1] = 0;
  219.   hostname = hnamebuf;
  220.  }
  221.  if (argc > 1)
  222.   route[nroute++] = whereto.sin_addr.s_addr;
  223.  argc--;
  224.  argv++;
  225. }
  226. if (source.sin_addr.s_addr == 0) {
  227.  int alen;
  228.  struct sockaddr_in dst = whereto;
  229.  int probe_fd = socket(AF_INET, SOCK_DGRAM, 0);
  230.  if (probe_fd < 0) {
  231.   perror("socket" );
  232.   exit(2);
  233.  }
  234.  if (device) {
  235.   struct ifreq ifr;
  236.   memset(&ifr, 0, sizeof(ifr));
  237.   strncpy(ifr.ifr_name, device, IFNAMSIZ-1);
  238.   if (setsockopt(probe_fd, SOL_SOCKET, SO_BINDTODEVICE, device, strlen(device)+1) == -1) {
  239.    if (IN_MULTICAST(ntohl(dst.sin_addr.s_addr))) {
  240.     struct ip_mreqn imr;
  241.     if (ioctl(probe_fd, SIOCGIFINDEX, &ifr) < 0) {
  242.      fprintf(stderr, "ping: unknown iface %s\n", device);
  243.      exit(2);
  244.     }
  245.     memset(&imr, 0, sizeof(imr));
  246.     imr.imr_ifindex = ifr.ifr_ifindex;
  247.     if (setsockopt(probe_fd, SOL_IP, IP_MULTICAST_IF, &imr, sizeof(imr)) == -1) {
  248.      perror("ping: IP_MULTICAST_IF" );
  249.      exit(2);
  250.     }
  251.    }
  252.   }
  253.  }
  254.  if (settos &&
  255.      setsockopt(probe_fd, IPPROTO_IP, IP_TOS, (char *)&settos, sizeof(int)) < 0)
  256.   perror("Warning: error setting QOS sockopts" );
  257.  dst.sin_port = htons(1025);
  258.  if (nroute)
  259.   dst.sin_addr.s_addr = route[0];
  260.  if (connect(probe_fd, (struct sockaddr*)&dst, sizeof(dst)) == -1) {
  261.   if (errno == EACCES) {
  262.    if (broadcast_pings == 0) {
  263.     fprintf(stderr, "Do you want to ping broadcast? Then -b\n" );
  264.     exit(2);
  265.    }
  266.    fprintf(stderr, "WARNING: pinging broadcast address\n" );
  267.    if (setsockopt(probe_fd, SOL_SOCKET, SO_BROADCAST,
  268.            &broadcast_pings, sizeof(broadcast_pings)) < 0) {
  269.     perror ("can't set broadcasting" );
  270.     exit(2);
  271.    }
  272.    if (connect(probe_fd, (struct sockaddr*)&dst, sizeof(dst)) == -1) {
  273.     perror("connect" );
  274.     exit(2);
  275.    }
  276.   } else {
  277.    perror("connect" );
  278.    exit(2);
  279.   }
  280.  }
  281.  alen = sizeof(source);
  282.  if (getsockname(probe_fd, (struct sockaddr*)&source, &alen) == -1) {
  283.   perror("getsockname" );
  284.   exit(2);
  285.  }
  286.  source.sin_port = 0;
  287.  close(probe_fd);
  288. } while (0);
  289. if (whereto.sin_addr.s_addr == 0)
  290.  whereto.sin_addr.s_addr = source.sin_addr.s_addr;
  291. if (icmp_sock < 0) {
  292.  errno = socket_errno;
  293.  perror("ping: icmp open socket" );
  294.  exit(2);
  295. }
  296. if (device) {
  297.  struct ifreq ifr;
  298.  memset(&ifr, 0, sizeof(ifr));
  299.  strncpy(ifr.ifr_name, device, IFNAMSIZ-1);
  300.  if (ioctl(icmp_sock, SIOCGIFINDEX, &ifr) < 0) {
  301.   fprintf(stderr, "ping: unknown iface %s\n", device);
  302.   exit(2);
  303.  }
  304.  cmsg.ipi.ipi_ifindex = ifr.ifr_ifindex;
  305.  cmsg_len = sizeof(cmsg);
  306. }
  307. if (broadcast_pings || IN_MULTICAST(ntohl(whereto.sin_addr.s_addr))) {
  308.  if (uid) {
  309.   if (interval < 1000) {
  310.    fprintf(stderr, "ping: broadcast ping with too short interval.\n" );
  311.    exit(2);
  312.   }
  313.   if (pmtudisc >= 0 && pmtudisc != IP_PMTUDISC_DO) {
  314.    fprintf(stderr, "ping: broadcast ping does not fragment.\n" );
  315.    exit(2);
  316.   }
  317.  }
  318.  if (pmtudisc < 0)
  319.   pmtudisc = IP_PMTUDISC_DO;
  320. }
  321. if (pmtudisc >= 0) {
  322.  if (setsockopt(icmp_sock, SOL_IP, IP_MTU_DISCOVER, &pmtudisc, sizeof(pmtudisc)) == -1) {
  323.   perror("ping: IP_MTU_DISCOVER" );
  324.   exit(2);
  325.  }
  326. }
  327. if ((options&F_STRICTSOURCE) &&
  328.     bind(icmp_sock, (struct sockaddr*)&source, sizeof(source)) == -1) {
  329.  perror("bind" );
  330.  exit(2);
  331. }
  332. if (1) {
  333.  struct icmp_filter filt;
  334.  filt.data = ~((1<<ICMP_SOURCE_QUENCH)|
  335.         (1<<ICMP_DEST_UNREACH)|
  336.         (1<<ICMP_TIME_EXCEEDED)|
  337.         (1<<ICMP_PARAMETERPROB)|
  338.         (1<<ICMP_REDIRECT)|
  339.         (1<<ICMP_ECHOREPLY));
  340.  if (setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, (char*)&filt, sizeof(filt)) == -1)
  341.   perror("WARNING: setsockopt(ICMP_FILTER)" );
  342. }
  343. hold = 1;
  344. if (setsockopt(icmp_sock, SOL_IP, IP_RECVERR, (char *)&hold, sizeof(hold)))
  345.  fprintf(stderr, "WARNING: your kernel is veeery old. No problems.\n" );
  346. /* record route option */
  347. if (options & F_RROUTE) {
  348.         bzero(rspace, sizeof(rspace));
  349.  rspace[0] = IPOPT_NOP;
  350.  rspace[1+IPOPT_OPTVAL] = IPOPT_RR;
  351.  rspace[1+IPOPT_OLEN] = sizeof(rspace)-1;
  352.  rspace[1+IPOPT_OFFSET] = IPOPT_MINOFF;
  353.  optlen = 40;
  354.  if (setsockopt(icmp_sock, IPPROTO_IP, IP_OPTIONS, rspace, sizeof(rspace)) < 0) {
  355.   perror("ping: record route" );
  356.   exit(2);
  357.  }
  358. }
  359. if (options & F_TIMESTAMP) {
  360.         bzero(rspace, sizeof(rspace));
  361.  rspace[0] = IPOPT_TIMESTAMP;
  362.  rspace[1] = (ts_type==IPOPT_TS_TSONLY ? 40 : 36);
  363.  rspace[2] = 5;
  364.  rspace[3] = ts_type;
  365.  if (ts_type == IPOPT_TS_PRESPEC) {
  366.   int i;
  367.   rspace[1] = 4+nroute*8;
  368.   for (i=0; i<nroute; i++)
  369.    *(__u32*)&rspace[4+i*8] = route[i];
  370.  }
  371.  if (setsockopt(icmp_sock, IPPROTO_IP, IP_OPTIONS, rspace, rspace[1]) < 0) {
  372.   rspace[3] = 2;
  373.   if (setsockopt(icmp_sock, IPPROTO_IP, IP_OPTIONS, rspace, rspace[1]) < 0) {
  374.    perror("ping: ts option" );
  375.    exit(2);
  376.   }
  377.  }
  378.  optlen = 40;
  379. }
  380. if (options & F_SOURCEROUTE) {
  381.         int i;
  382.         bzero(rspace, sizeof(rspace));
  383.  rspace[0] = IPOPT_NOOP;
  384.  rspace[1+IPOPT_OPTVAL] = (options & F_SO_DONTROUTE) ? IPOPT_SSRR
  385.   : IPOPT_LSRR;
  386.  rspace[1+IPOPT_OLEN] = 3 + nroute*4;
  387.  rspace[1+IPOPT_OFFSET] = IPOPT_MINOFF;
  388.  for (i=0; i<nroute; i++)
  389.   *(__u32*)&rspace[4+i*4] = route[i];
  390.  if (setsockopt(icmp_sock, IPPROTO_IP, IP_OPTIONS, rspace, 4 + nroute*4) < 0) {
  391.   perror("ping: record route" );
  392.   exit(2);
  393.  }
  394.  optlen = 40;
  395. }
  396. /* Estimate memory eaten by single packet. It is rough estimate.
  397.  * Actually, for small datalen's it depends on kernel side a lot. */
  398. hold = datalen + 8;
  399. hold += ((hold+511)/512)*(optlen + 20 + 16 + 64 + 160);
  400. sock_setbufs(icmp_sock, hold);
  401. if (broadcast_pings) {
  402.  if (setsockopt(icmp_sock, SOL_SOCKET, SO_BROADCAST,
  403.          &broadcast_pings, sizeof(broadcast_pings)) < 0) {
  404.   perror ("ping: can't set broadcasting" );
  405.   exit(2);
  406.  }
  407.         }
  408. if (options & F_NOLOOP) {
  409.  int loop = 0;
  410.  if (setsockopt(icmp_sock, IPPROTO_IP, IP_MULTICAST_LOOP,
  411.       &loop, 1) == -1) {
  412.   perror ("ping: can't disable multicast loopback" );
  413.   exit(2);
  414.  }
  415. }
  416. if (options & F_TTL) {
  417.  int ittl = ttl;
  418.  if (setsockopt(icmp_sock, IPPROTO_IP, IP_MULTICAST_TTL,
  419.       &ttl, 1) == -1) {
  420.   perror ("ping: can't set multicast time-to-live" );
  421.   exit(2);
  422.  }
  423.  if (setsockopt(icmp_sock, IPPROTO_IP, IP_TTL,
  424.       &ittl, sizeof(ittl)) == -1) {
  425.   perror ("ping: can't set unicast time-to-live" );
  426.   exit(2);
  427.  }
  428. }
  429. if (datalen > 0xFFFF - 8 - optlen - 20) {
  430.  if (uid || datalen > sizeof(outpack)-8) {
  431.   fprintf(stderr, "Error: packet size %d is too large. Maximum is %d\n", datalen, 0xFFFF-8-20-optlen);
  432.   exit(2);
  433.  }
  434.  /* Allow small oversize to root yet. It will cause EMSGSIZE. */
  435.  fprintf(stderr, "WARNING: packet size %d is too large. Maximum is %d\n", datalen, 0xFFFF-8-20-optlen);
  436. }
  437. if (datalen >= sizeof(struct timeval)) /* can we time transfer */
  438.  timing = 1;
  439. packlen = datalen + MAXIPLEN + MAXICMPLEN;
  440. if (!(packet = (u_char *)malloc((u_int)packlen))) {
  441.  fprintf(stderr, "ping: out of memory.\n" );
  442.  exit(2);
  443. }
  444. printf("PING %s (%s) ", hostname, inet_ntoa(whereto.sin_addr));
  445. if (device || (options&F_STRICTSOURCE))
  446.  printf("from %s %s: ", inet_ntoa(source.sin_addr), device ?: "" );
  447. printf("%d(%d) bytes of data.\n", datalen, datalen+8+optlen+20);
  448. setup(icmp_sock);
  449. main_loop(icmp_sock, packet, packlen);
  450. }
  451. int receive_error_msg()
  452. {
  453. int res;
  454. char cbuf[512];
  455. struct iovec  iov;
  456. struct msghdr msg;
  457. struct cmsghdr *cmsg;
  458. struct sock_extended_err *e;
  459. struct icmphdr icmph;
  460. struct sockaddr_in target;
  461. int net_errors = 0;
  462. int local_errors = 0;
  463. int saved_errno = errno;
  464. iov.iov_base = &icmph;
  465. iov.iov_len = sizeof(icmph);
  466. msg.msg_name = (void*)⌖
  467. msg.msg_namelen = sizeof(target);
  468. msg.msg_iov = &iov;
  469. msg.msg_iovlen = 1;
  470. msg.msg_flags = 0;
  471. msg.msg_control = cbuf;
  472. msg.msg_controllen = sizeof(cbuf);
  473. res = recvmsg(icmp_sock, &msg, MSG_ERRQUEUE|MSG_DONTWAIT);
  474. if (res < 0)
  475.  goto out;
  476. e = NULL;
  477. for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
  478.  if (cmsg->cmsg_level == SOL_IP) {
  479.   if (cmsg->cmsg_type == IP_RECVERR)
  480.    e = (struct sock_extended_err *)CMSG_DATA(cmsg);
  481.  }
  482. }
  483. if (e == NULL)
  484.  abort();
  485. if (e->ee_origin == SO_EE_ORIGIN_LOCAL) {
  486.  local_errors++;
  487.  if (options & F_QUIET)
  488.   goto out;
  489.  if (options & F_FLOOD)
  490.   write(STDOUT_FILENO, "E", 1);
  491.  else if (e->ee_errno != EMSGSIZE)
  492.   fprintf(stderr, "ping: local error: %s\n", strerror(e->ee_errno));
  493.  else
  494.   fprintf(stderr, "ping: local error: Message too long, mtu=%u\n", e->ee_info);
  495.  nerrors++;
  496. } else if (e->ee_origin == SO_EE_ORIGIN_ICMP) {
  497.  struct sockaddr_in *sin = (struct sockaddr_in*)(e+1);
  498.  if (res < sizeof(icmph) ||
  499.      target.sin_addr.s_addr != whereto.sin_addr.s_addr ||
  500.      icmph.type != ICMP_ECHO ||
  501.      icmph.un.echo.id != ident) {
  502.   /* Not our error, not an error at all. Clear. */
  503.   saved_errno = 0;
  504.   goto out;
  505.  }
  506.  acknowledge(ntohs(icmph.un.echo.sequence));
  507.  if (!working_recverr) {
  508.   struct icmp_filter filt;
  509.   working_recverr = 1;
  510.   /* OK, it works. Add stronger filter. */
  511.   filt.data = ~((1<<ICMP_SOURCE_QUENCH)|
  512.          (1<<ICMP_REDIRECT)|
  513.          (1<<ICMP_ECHOREPLY));
  514.   if (setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, (char*)&filt, sizeof(filt)) == -1)
  515.    perror("\rWARNING: setsockopt(ICMP_FILTER)" );
  516.  }
  517.  net_errors++;
  518.  nerrors++;
  519.  if (options & F_QUIET)
  520.   goto out;
  521.  if (options & F_FLOOD) {
  522.   write(STDOUT_FILENO, "\bE", 2);
  523.  } else {
  524.   printf("From %s icmp_seq=%u ", pr_addr(sin->sin_addr.s_addr), ntohs(icmph.un.echo.sequence));
  525.   pr_icmph(e->ee_type, e->ee_code, e->ee_info, NULL);
  526.   fflush(stdout);
  527.  }
  528. }
  529. out:
  530. errno = saved_errno;
  531. return net_errors ? : -local_errors;
  532. }
  533. /*
  534. * pinger --
  535. *  Compose and transmit an ICMP ECHO REQUEST packet.  The IP packet
  536. * will be added on by the kernel.  The ID field is our UNIX process ID,
  537. * and the sequence number is an ascending integer.  The first 8 bytes
  538. * of the data portion are used to hold a UNIX "timeval" struct in VAX
  539. * byte-order, to compute the round-trip time.
  540. */
  541. int send_probe()
  542. {
  543. struct icmphdr *icp;
  544. int cc;
  545. int i;
  546. icp = (struct icmphdr *)outpack;
  547. icp->type = ICMP_ECHO;
  548. icp->code = 0;
  549. icp->checksum = 0;
  550. icp->un.echo.sequence = htons(ntransmitted+1);
  551. icp->un.echo.id = ident;   /* ID */
  552. CLR((ntransmitted+1) % mx_dup_ck);
  553. if (timing) {
  554.  if (options&F_LATENCY) {
  555.   static volatile int fake_fucked_egcs = sizeof(struct timeval);
  556.   struct timeval tmp_tv;
  557.   gettimeofday(&tmp_tv, NULL);
  558.   /* egcs is crap or glibc is crap, but memcpy  
  559.      does not copy anything, if len is constant! */
  560.   memcpy(icp+1, &tmp_tv, fake_fucked_egcs);
  561.  } else {
  562.   memset(icp+1, 0, sizeof(struct timeval));
  563.  }
  564. }
  565. cc = datalen + 8;   /* skips ICMP portion */
  566. /* compute ICMP checksum here */
  567. icp->checksum = in_cksum((u_short *)icp, cc, 0);
  568. if (timing && !(options&F_LATENCY)) {
  569.  static volatile int fake_fucked_egcs = sizeof(struct timeval);
  570.         struct timeval tmp_tv;
  571.  gettimeofday(&tmp_tv, NULL);
  572.  /* egcs is crap or glibc is crap, but memcpy  
  573.     does not copy anything, if len is constant! */
  574.  memcpy(icp+1, &tmp_tv, fake_fucked_egcs);
  575.  icp->checksum = in_cksum((u_short *)(icp+1), fake_fucked_egcs, ~icp->checksum);
  576. }
  577.         do {
  578.  static struct iovec iov = {outpack, 0};
  579.  static struct msghdr m = { &whereto, sizeof(whereto),
  580.         &iov, 1, &cmsg, 0, 0 };
  581.  m.msg_controllen = cmsg_len;
  582.  iov.iov_len = cc;
  583.  i = sendmsg(icmp_sock, &m, confirm);
  584.  confirm = 0;
  585. } while (0);
  586. return (cc == i ? 0 : i);
  587. }
  588. /*
  589. * parse_reply --
  590. * Print out the packet, if it came from us.  This logic is necessary
  591. * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
  592. * which arrive ('tis only fair).  This permits multiple copies of this
  593. * program to be run without having intermingled output (or statistics!).
  594. */
  595. int
  596. parse_reply(struct msghdr *msg, int cc, void *addr, struct timeval *tv)
  597. {
  598. struct sockaddr_in *from = addr;
  599. __u8 *buf = msg->msg_iov->iov_base;
  600. struct icmphdr *icp;
  601. struct iphdr *ip;
  602. int hlen;
  603. int csfailed;
  604. /* Check the IP header */
  605. ip = (struct iphdr *)buf;
  606. hlen = ip->ihl*4;
  607. if (cc < hlen + 8 || ip->ihl < 5) {
  608.  if (options & F_VERBOSE)
  609.   fprintf(stderr, "ping: packet too short (%d bytes) from %s\n", cc,
  610.    pr_addr(from->sin_addr.s_addr));
  611.  return 1;
  612. }
  613. /* Now the ICMP part */
  614. cc -= hlen;
  615. icp = (struct icmphdr *)(buf + hlen);
  616. csfailed = in_cksum((u_short *)icp, cc, 0);
  617. if (icp->type == ICMP_ECHOREPLY) {
  618.  if (icp->un.echo.id != ident)
  619.   return 1;   /* 'Twas not our ECHO */
  620.  if (gather_statistics((__u8*)(icp+1), cc,
  621.          ntohs(icp->un.echo.sequence),
  622.          ip->ttl, 0, tv, pr_addr(from->sin_addr.s_addr)))
  623.   return 0;
  624. } else {
  625.  /* We fall here when a redirect or source quench arrived.
  626.   * Also this branch processes icmp errors, when IP_RECVERR
  627.   * is broken. */
  628.   
  629.         switch (icp->type) {
  630.  case ICMP_ECHO:
  631.   /* MUST NOT */
  632.   return 1;
  633.  case ICMP_SOURCE_QUENCH:
  634.  case ICMP_REDIRECT:
  635.  case ICMP_DEST_UNREACH:
  636.  case ICMP_TIME_EXCEEDED:
  637.  case ICMP_PARAMETERPROB:
  638.   {
  639.    struct iphdr * iph = (struct  iphdr *)(&icp[1]);
  640.    struct icmphdr *icp1 = (struct icmphdr*)((unsigned char *)iph + iph->ihl*4);
  641.    int error_pkt;
  642.    if (cc < 8+sizeof(struct iphdr)+8 ||
  643.        cc < 8+iph->ihl*4+8)
  644.     return 1;
  645.    if (icp1->type != ICMP_ECHO ||
  646.        iph->daddr != whereto.sin_addr.s_addr ||
  647.        icp1->un.echo.id != ident)
  648.     return 1;
  649.    error_pkt = (icp->type != ICMP_REDIRECT &&
  650.          icp->type != ICMP_SOURCE_QUENCH);
  651.    if (error_pkt) {
  652.     acknowledge(ntohs(icp1->un.echo.sequence));
  653.     if (working_recverr) {
  654.      return 0;
  655.     } else {
  656.      static int once;
  657.      /* Sigh, IP_RECVERR for raw socket
  658.       * was broken until 2.4.9. So, we ignore
  659.       * the first error and warn on the second.
  660.       */
  661.      if (once++ == 1)
  662.       fprintf(stderr, "\rWARNING: kernel is not very fresh, upgrade is recommended.\n" );
  663.      if (once == 1)
  664.       return 0;
  665.     }
  666.    }
  667.    nerrors+=error_pkt;
  668.    if (options&F_QUIET)
  669.     return !error_pkt;
  670.    if (options & F_FLOOD) {
  671.     if (error_pkt)
  672.      write(STDOUT_FILENO, "\bE", 2);
  673.     return !error_pkt;
  674.    }
  675.    printf("From %s: icmp_seq=%u ",
  676.           pr_addr(from->sin_addr.s_addr),
  677.           ntohs(icp1->un.echo.sequence));
  678.    if (csfailed)
  679.     printf("(BAD CHECKSUM)" );
  680.    pr_icmph(icp->type, icp->code, ntohl(icp->un.gateway), icp);
  681.    return !error_pkt;
  682.   }
  683.         default:
  684.   /* MUST NOT */
  685.   break;
  686.  }
  687.  if ((options & F_FLOOD) && !(options & (F_VERBOSE|F_QUIET))) {
  688.   if (!csfailed)
  689.    write(STDOUT_FILENO, "!E", 2);
  690.   else
  691.    write(STDOUT_FILENO, "!EC", 3);
  692.   return 0;
  693.  }
  694.  if (!(options & F_VERBOSE) || uid)
  695.   return 0;
  696.  printf("From %s: ", pr_addr(from->sin_addr.s_addr));
  697.  if (csfailed) {
  698.   printf("(BAD CHECKSUM)\n" );
  699.   return 0;
  700.  }
  701.  pr_icmph(icp->type, icp->code, ntohl(icp->un.gateway), icp);
  702.  return 0;
  703. }
  704. if (!(options & F_FLOOD)) {
  705.  pr_options(buf + sizeof(struct iphdr), hlen);
  706.  if (options & F_AUDIBLE)
  707.   putchar('\a');
  708.  putchar('\n');
  709.  fflush(stdout);
  710. }
  711. return 0;
  712. }
  713. u_short
  714. in_cksum(const u_short *addr, register int len, u_short csum)
  715. {
  716. register int nleft = len;
  717. const u_short *w = addr;
  718. register u_short answer;
  719. register int sum = csum;
  720. /*
  721.  *  Our algorithm is simple, using a 32 bit accumulator (sum),
  722.  *  we add sequential 16 bit words to it, and at the end, fold
  723.  *  back all the carry bits from the top 16 bits into the lower
  724.  *  16 bits.
  725.  */
  726. while (nleft > 1)  {
  727.  sum += *w++;
  728.  nleft -= 2;
  729. }
  730. /* mop up an odd byte, if necessary */
  731. if (nleft == 1)
  732.  sum += htons(*(u_char *)w << 8);
  733. /*
  734.  * add back carry outs from top 16 bits to low 16 bits
  735.  */
  736. sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
  737. sum += (sum >> 16);   /* add carry */
  738. answer = ~sum;    /* truncate to 16 bits */
  739. return (answer);
  740. }
  741. /*
  742. * pr_icmph --
  743. * Print a descriptive string about an ICMP header.
  744. */
  745. void pr_icmph(__u8 type, __u8 code, __u32 info, struct icmphdr *icp)
  746. {
  747. switch(type) {
  748. case ICMP_ECHOREPLY:
  749.  printf("Echo Reply\n" );
  750.  /* XXX ID + Seq + Data */
  751.  break;
  752. case ICMP_DEST_UNREACH:
  753.  switch(code) {
  754.  case ICMP_NET_UNREACH:
  755.   printf("Destination Net Unreachable\n" );
  756.   break;
  757.  case ICMP_HOST_UNREACH:
  758.   printf("Destination Host Unreachable\n" );
  759.   break;
  760.  case ICMP_PROT_UNREACH:
  761.   printf("Destination Protocol Unreachable\n" );
  762.   break;
  763.  case ICMP_PORT_UNREACH:
  764.   printf("Destination Port Unreachable\n" );
  765.   break;
  766.  case ICMP_FRAG_NEEDED:
  767.   printf("Frag needed and DF set (mtu = %u)\n", info);
  768.   break;
  769.  case ICMP_SR_FAILED:
  770.   printf("Source Route Failed\n" );
  771.   break;
  772.  case ICMP_PKT_FILTERED:
  773.   printf("Packet filtered\n" );
  774.   break;
  775.  default:
  776.   printf("Dest Unreachable, Bad Code: %d\n", code);
  777.   break;
  778.  }
  779.  if (icp && (options & F_VERBOSE))
  780.   pr_iph((struct iphdr*)(icp + 1));
  781.  break;
  782. case ICMP_SOURCE_QUENCH:
  783.  printf("Source Quench\n" );
  784.  if (icp && (options & F_VERBOSE))
  785.   pr_iph((struct iphdr*)(icp + 1));
  786.  break;
  787. case ICMP_REDIRECT:
  788.  switch(code) {
  789.  case ICMP_REDIR_NET:
  790.   printf("Redirect Network" );
  791.   break;
  792.  case ICMP_REDIR_HOST:
  793.   printf("Redirect Host" );
  794.   break;
  795.  case ICMP_REDIR_NETTOS:
  796.   printf("Redirect Type of Service and Network" );
  797.   break;
  798.  case ICMP_REDIR_HOSTTOS:
  799.   printf("Redirect Type of Service and Host" );
  800.   break;
  801.  default:
  802.   printf("Redirect, Bad Code: %d", code);
  803.   break;
  804.  }
  805.  if (icp)
  806.   printf("(New nexthop: %s)\n", pr_addr(icp->un.gateway));
  807.  if (icp && (options & F_VERBOSE))
  808.   pr_iph((struct iphdr*)(icp + 1));
  809.  break;
  810. case ICMP_ECHO:
  811.  printf("Echo Request\n" );
  812.  /* XXX ID + Seq + Data */
  813.  break;
  814. case ICMP_TIME_EXCEEDED:
  815.  switch(code) {
  816.  case ICMP_EXC_TTL:
  817.   printf("Time to live exceeded\n" );
  818.   break;
  819.  case ICMP_EXC_FRAGTIME:
  820.   printf("Frag reassembly time exceeded\n" );
  821.   break;
  822.  default:
  823.   printf("Time exceeded, Bad Code: %d\n", code);
  824.   break;
  825.  }
  826.  if (icp && (options & F_VERBOSE))
  827.   pr_iph((struct iphdr*)(icp + 1));
  828.  break;
  829. case ICMP_PARAMETERPROB:
  830.  printf("Parameter problem: pointer = %u\n", icp ? (ntohl(icp->un.gateway)>>24) : info);
  831.  if (icp && (options & F_VERBOSE))
  832.   pr_iph((struct iphdr*)(icp + 1));
  833.  break;
  834. case ICMP_TIMESTAMP:
  835.  printf("Timestamp\n" );
  836.  /* XXX ID + Seq + 3 timestamps */
  837.  break;
  838. case ICMP_TIMESTAMPREPLY:
  839.  printf("Timestamp Reply\n" );
  840.  /* XXX ID + Seq + 3 timestamps */
  841.  break;
  842. case ICMP_INFO_REQUEST:
  843.  printf("Information Request\n" );
  844.  /* XXX ID + Seq */
  845.  break;
  846. case ICMP_INFO_REPLY:
  847.  printf("Information Reply\n" );
  848.  /* XXX ID + Seq */
  849.  break;
  850. #ifdef ICMP_MASKREQ
  851. case ICMP_MASKREQ:
  852.  printf("Address Mask Request\n" );
  853.  break;
  854. #endif
  855. #ifdef ICMP_MASKREPLY
  856. case ICMP_MASKREPLY:
  857.  printf("Address Mask Reply\n" );
  858.  break;
  859. #endif
  860. default:
  861.  printf("Bad ICMP type: %d\n", type);
  862. }
  863. }
  864. void pr_options(unsigned char * cp, int hlen)
  865. {
  866. int i, j;
  867. int optlen, totlen;
  868. unsigned char * optptr;
  869. static int old_rrlen;
  870. static char old_rr[MAX_IPOPTLEN];
  871. totlen = hlen-sizeof(struct iphdr);
  872. optptr = cp;
  873. while (totlen > 0) {
  874.  if (*optptr == IPOPT_EOL)
  875.   break;
  876.  if (*optptr == IPOPT_NOP) {
  877.   totlen--;
  878.   optptr++;
  879.   printf("\nNOP" );
  880.   continue;
  881.  }
  882.  cp = optptr;
  883.  optlen = optptr[1];
  884.  if (optlen < 2 || optlen > totlen)
  885.   break;
  886.  switch (*cp) {
  887.  case IPOPT_SSRR:
  888.  case IPOPT_LSRR:
  889.   printf("\n%cSRR: ", *cp==IPOPT_SSRR ? 'S' : 'L');
  890.   j = *++cp;
  891.   i = *++cp;
  892.   i -= 4;
  893.   cp++;
  894.   if (j > IPOPT_MINOFF) {
  895.    for (;;) {
  896.     __u32 address;
  897.     memcpy(&address, cp, 4);
  898.     cp += 4;
  899.     if (address == 0)
  900.      printf("\t0.0.0.0" );
  901.     else
  902.      printf("\t%s", pr_addr(address));
  903.     j -= 4;
  904.     putchar('\n');
  905.     if (j <= IPOPT_MINOFF)
  906.      break;
  907.    }
  908.   }
  909.   break;
  910.  case IPOPT_RR:
  911.   j = *++cp;  /* get length */
  912.   i = *++cp;  /* and pointer */
  913.   if (i > j)
  914.    i = j;
  915.   i -= IPOPT_MINOFF;
  916.   if (i <= 0)
  917.    continue;
  918.   if (i == old_rrlen
  919.       && !bcmp((char *)cp, old_rr, i)
  920.       && !(options & F_FLOOD)) {
  921.    printf("\t(same route)" );
  922.    i = ((i + 3) / 4) * 4;
  923.    cp += i;
  924.    break;
  925.   }
  926.   old_rrlen = i;
  927.   bcopy((char *)cp, old_rr, i);
  928.   printf("\nRR: " );
  929.   cp++;
  930.   for (;;) {
  931.    __u32 address;
  932.    memcpy(&address, cp, 4);
  933.    cp += 4;
  934.    if (address == 0)
  935.     printf("\t0.0.0.0" );
  936.    else
  937.     printf("\t%s", pr_addr(address));
  938.    i -= 4;
  939.    putchar('\n');
  940.    if (i <= 0)
  941.     break;
  942.   }
  943.   break;
  944.  case IPOPT_TS:
  945.  {
  946.   int stdtime = 0, nonstdtime = 0;
  947.   __u8 flags;
  948.   j = *++cp;  /* get length */
  949.   i = *++cp;  /* and pointer */
  950.   if (i > j)
  951.    i = j;
  952.   i -= 5;
  953.   if (i <= 0)
  954.    continue;
  955.   flags = *++cp;
  956.   printf("\nTS: " );
  957.   cp++;
  958.   for (;;) {
  959.    long l;
  960.    if ((flags&0xF) != IPOPT_TS_TSONLY) {
  961.     __u32 address;
  962.     memcpy(&address, cp, 4);
  963.     cp += 4;
  964.     if (address == 0)
  965.      printf("\t0.0.0.0" );
  966.     else
  967.      printf("\t%s", pr_addr(address));
  968.     i -= 4;
  969.     if (i <= 0)
  970.      break;
  971.    }
  972.    l = *cp++;
  973.    l = (l<<8) + *cp++;
  974.    l = (l<<8) + *cp++;
  975.    l = (l<<8) + *cp++;
  976.    if  (l & 0x80000000) {
  977.     if (nonstdtime==0)
  978.      printf("\t%ld absolute not-standard", l&0x7fffffff);
  979.     else
  980.      printf("\t%ld not-standard", (l&0x7fffffff) - nonstdtime);
  981.     nonstdtime = l&0x7fffffff;
  982.    } else {
  983.     if (stdtime==0)
  984.      printf("\t%ld absolute", l);
  985.     else
  986.      printf("\t%ld", l - stdtime);
  987.     stdtime = l;
  988.    }
  989.    i -= 4;
  990.    putchar('\n');
  991.    if (i <= 0)
  992.     break;
  993.   }
  994.   if (flags>>4)
  995.    printf("Unrecorded hops: %d\n", flags>>4);
  996.   break;
  997.  }
  998.  default:
  999.   printf("\nunknown option %x", *cp);
  1000.   break;
  1001.  }
  1002.  totlen -= optlen;
  1003.  optptr += optlen;
  1004. }
  1005. }
  1006. /*
  1007. * pr_iph --
  1008. * Print an IP header with options.
  1009. */
  1010. void pr_iph(struct iphdr *ip)
  1011. {
  1012. int hlen;
  1013. u_char *cp;
  1014. hlen = ip->ihl << 2;
  1015. cp = (u_char *)ip + 20;  /* point to options */
  1016. printf("Vr HL TOS  Len   ID Flg  off TTL Pro  cks      Src      Dst Data\n" );
  1017. printf(" %1x  %1x  %02x %04x %04x",
  1018.        ip->version, ip->ihl, ip->tos, ip->tot_len, ip->id);
  1019. printf("   %1x %04x", ((ip->frag_off) & 0xe000) >> 13,
  1020.        (ip->frag_off) & 0x1fff);
  1021. printf("  %02x  %02x %04x", ip->ttl, ip->protocol, ip->check);
  1022. printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->saddr));
  1023. printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->daddr));
  1024. printf("\n" );
  1025. pr_options(cp, hlen);
  1026. }
  1027. /*
  1028. * pr_addr --
  1029. * Return an ascii host address as a dotted quad and optionally with
  1030. * a hostname.
  1031. */
  1032. char *
  1033. pr_addr(__u32 addr)
  1034. {
  1035. struct hostent *hp;
  1036. static char buf[4096];
  1037. if ((options & F_NUMERIC) ||
  1038.     !(hp = gethostbyaddr((char *)&addr, 4, AF_INET)))
  1039.  sprintf(buf, "%s", inet_ntoa(*(struct in_addr *)&addr));
  1040. else
  1041.  snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name,
  1042.    inet_ntoa(*(struct in_addr *)&addr));
  1043. return(buf);
  1044. }
  1045. /* Set Type of Service (TOS) and other Quality of Service relating bits */
  1046. int parsetos(char *str)
  1047. {
  1048.         const char *cp;
  1049.         int tos;
  1050.         char *ep;
  1051.         /* handle both hex and decimal values */
  1052.         if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) {
  1053.  cp = str + 2;
  1054.  tos = (int)strtol(cp, &ep, 16);
  1055.         } else
  1056.                 tos = (int)strtol(str, &ep, 10);
  1057.         /* doesn't look like decimal or hex, eh? */
  1058.         if (*ep != '\0') {
  1059.          fprintf(stderr, "ping: \"%s\" bad value for TOS\n", str);
  1060.          exit(2);
  1061.         }
  1062.         if (tos > TOS_MAX) {
  1063.          fprintf(stderr, "ping: the decimal value of TOS bits must be 0-254 (or zero)\n" );
  1064.          exit(2);
  1065.         }
  1066. return(tos);
  1067. }
  1068. #include <linux/filter.h>
  1069. void install_filter(void)
  1070. {
  1071. static int once;
  1072. static struct sock_filter insns[] = {
  1073.  BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0), /* Skip IP header. F..g BSD... Look into ping6. */
  1074.  BPF_STMT(BPF_LD|BPF_H|BPF_IND, 4), /* Load icmp echo ident */
  1075.  BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 0xAAAA, 0, 1), /* Ours? */
  1076.  BPF_STMT(BPF_RET|BPF_K, ~0U), /* Yes, it passes. */
  1077.  BPF_STMT(BPF_LD|BPF_B|BPF_IND, 0), /* Load icmp type */
  1078.  BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, ICMP_ECHOREPLY, 1, 0), /* Echo? */
  1079.  BPF_STMT(BPF_RET|BPF_K, 0xFFFFFFF), /* No. It passes. */
  1080.  BPF_STMT(BPF_RET|BPF_K, 0) /* Echo with wrong ident. Reject. */
  1081. };
  1082. static struct sock_fprog filter = {
  1083.  sizeof insns / sizeof(insns[0]),
  1084.  insns
  1085. };
  1086. if (once)
  1087.  return;
  1088. once = 1;
  1089. /* Patch bpflet for current identifier. */
  1090. insns[2] = (struct sock_filter)BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, __constant_htons(ident), 0, 1);
  1091. if (setsockopt(icmp_sock, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter)))
  1092.  perror("WARNING: failed to install socket filter\n" );
  1093. }
  1094. void usage(void)
  1095. {
  1096. fprintf(stderr,
  1097. "Usage: ping [-LRUbdfnqrvVaA] [-c count] [-i interval] [-w deadline]\n"
  1098. "            [-p pattern] [-s packetsize] [-t ttl] [-I interface or address]\n"
  1099. "            [-M mtu discovery hint] [-S sndbuf]\n"
  1100. "            [ -T timestamp option ] [ -Q tos ] [hop1 ...] destination\n" );
  1101. exit(2);
  1102. }


 
ftp://ftp.inr.ac.ru/ip-routing/
Ou apt-get source iputils-ping quand on a un système décent... oups.


Message édité par Jar Jar le 28-12-2002 à 00:02:55

---------------
« No question is too silly to ask, but, of course, some are too silly to answer. » -- Perl book
Reply

Marsh Posté le 28-12-2002 à 05:15:00    

merci pour la souce jarjar :)
pour le apt-get source ça marche avec toutes les distros ou c'est seulement pour deb?


---------------
http://www.core-tx.com
Reply

Marsh Posté le 28-12-2002 à 09:34:58    

de toutes façon tu peux avoir toutes les sources de tout les progs GPL de tes distro linux donc ça doit pas être bien dur à trouver ...  ;)


---------------
-@- When code matters more than commercials -@-
Reply

Marsh Posté le 28-12-2002 à 09:58:24    

Yep.
Je viens de telecharger 1.4Go de sources sur RedHat :o) :) :o)


---------------
FAQ fclc++ - FAQ C++ - C++ FAQ Lite
Reply

Marsh Posté le 28-12-2002 à 13:34:12    

Sky99 a écrit :

pour le apt-get source ça marche avec toutes les distros ou c'est seulement pour deb?

C'est la syntaxe Debian, mais j'imagine que Mandrake et Redhat ont des équivalents.


---------------
« No question is too silly to ask, but, of course, some are too silly to answer. » -- Perl book
Reply

Marsh Posté le    

Reply

Sujets relatifs:

Leave a Replay

Make sure you enter the(*)required information where indicate.HTML code is not allowed