Linux下实现ping功能

时间:2023-03-09 20:27:20
Linux下实现ping功能

实现ping功能,就肯定要用到ping命令,那么在Linux下ping命令为:

ping [-dfnqrRv][-c<完成次数>][-i<间隔秒数>][-I<网络界面>][-l<前置载入>][-p<范本样式>][-s<数据包大小>][-t<存活数值>][主机名称或IP地址]

ping命令说明
PING()                System Manager's Manual: iputils                PING(8)

NAME
       ping, ping6 - send ICMP ECHO_REQUEST to network hosts

SYNOPSIS
       ping  [-LRUbdfnqrvVaAB] [-c count] [-m mark] [-i interval] [-l preload]
       [-p pattern] [-s packetsize] [-t ttl] [-w deadline] [-F flowlabel]  [-I
       interface]  [-M  hint] [-N nioption] [-Q tos] [-S sndbuf] [-T timestamp
       option] [-W timeout] [hop ...] destination

       ping [-dfnqrRv][-c<完成次数>][-i<间隔秒数>][-I<网络界面>][-l<前置载入>]
       [-p<范本样式>][-s<数据包大小>][-t<存活数值>][主机名称或IP地址] 

DESCRIPTION
       ping uses the ICMP protocol's mandatory ECHO_REQUEST datagram to elicit
       an  ICMP  ECHO_RESPONSE from a host or gateway.  ECHO_REQUEST datagrams
       (``pings'') have an IP and ICMP header, followed by  a  struct  timeval
       and  then  an  arbitrary  number  of ``pad'' bytes used to fill out the
       packet.

       ping6 can also send Node Information Queries (RFC4620).

OPTIONS
       -a     Audible ping.

       -b     Allow pinging a broadcast address.允许ping一个广播地址

       -B     Do not allow ping to  change  source  address  of  probes.   The
              address is bound to one selected when ping starts.

       -m mark
              use  mark to tag the packets going out. This is useful for vari‐
              ety of reasons within the kernel such as using policy routing to
              select specific outbound processing.

       -c count
              Stop  after  sending  count  ECHO_REQUEST packets. With deadline
              option, ping waits for count ECHO_REPLY packets, until the time‐
              out expires.打印语句

       -d     Set  the SO_DEBUG option on the socket being used.  Essentially,
              this socket option is not used by Linux kernel.

       -F flow label
              Allocate and  bit flow  label  on  echo  request  packets.
              (Only  ping6).  If  value  is zero, kernel allocates random flow
              label.

       -f     Flood ping. For  every  ECHO_REQUEST  sent  a  period  ``.''  is
              printed,  while  for  ever  ECHO_REPLY  received  a backspace is
              printed.  This provides a rapid display of how many packets  are
              being  dropped.   If  interval is not given, it sets interval to
              zero and outputs packets as fast as they come back or  one  hun‐
              dred  times  per second, whichever is more.  Only the super-user
              may use this option with zero interval.

       -i interval
              Wait interval seconds between sending each packet.  The  default
              is  to  wait for one second between each packet normally, or not
              to wait in flood mode. Only super-user may set interval to  val‐
              ues less 0.2 seconds.

       -I interface address
              Set  source address to specified interface address. Argument may
              be numeric IP address or name of device. When pinging IPv6 link-
              local address this option is required.

       -l preload
              If  preload is specified, ping sends that many packets not wait‐
              ing for reply.  Only the super-user may select preload more than
              .

       -L     Suppress  loopback of multicast packets.  This flag only applies
              if the ping destination is a multicast address.

       -n     Numeric output only.  No attempt will be made to lookup symbolic
              names for host addresses.

       -p pattern
              You may specify up to  ``pad'' bytes to fill  out  the  packet
              you send.  This is useful for diagnosing data-dependent problems
              in a network.  For example, -p ff will cause the sent packet  to
              be filled with all ones.

       -D     Print  timestamp  (unix  time + microseconds as in gettimeofday)
              before each line.

       -q     Quiet output.  Nothing is displayed except the summary lines  at
              startup time and when finished.

       -R     Record   route.    Includes   the  RECORD_ROUTE  option  in  the
              ECHO_REQUEST packet and displays the route  buffer  on  returned
              packets.   Note that the IP header is only large enough for nine
              such routes.  Many hosts ignore or discard this option.

       -r     Bypass the normal routing tables and send directly to a host  on
              an  attached  interface.   If  the  host  is  not on a directly-
              attached network, an error is returned.  This option can be used
              to  ping  a  local  host  through an interface that has no route
              through it provided the option -I is also used.

       -s packetsize
              Specifies the number of data bytes to be sent.  The  default  is
              ,  which translates into  ICMP data bytes when combined with
              the  bytes of ICMP header data.

       -S sndbuf
              Set socket sndbuf. If not specified, it is  selected  to  buffer
              not more than one packet.

       -t ttl Set the IP Time to Live.

       -T timestamp option
              Set  special  IP  timestamp  options.   timestamp  option may be
              either  tsonly  (only  timestamps),  tsandaddr  (timestamps  and
              addresses) or tsprespec host1 [host2 [host3 [host4]]] (timestamp
              prespecified hops).

       -U     Print  full  user-to-user  latency (the old behaviour). Normally
              ping prints network round trip time, which can be different f.e.
              due to DNS failures.

       -v     Verbose output.

       -V     Show version and exit.

       -w deadline
              Specify  a  timeout, in seconds, before ping exits regardless of
              how many packets have been sent or received. In this  case  ping
              does  not  stop after count packet are sent, it waits either for
              deadline expire or until count probes are answered or  for  some
              error notification from network.

       -W timeout
              Time to wait for a response, in seconds. The option affects only
              timeout in absense of any responses, otherwise  ping  waits  for
              two RTTs.

那么用C语言实现ping过程如下:

 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
 #include <errno.h>
 #include <error.h>

 #define error_exit(_errmsg) error(EXIT_FAILURE , errno, _errmsg)

 int ping_ip(const char * ip)
 {

     FILE * fp = NULL;
     ] = {};
     ;
     char * pstr = NULL;
     ] = {};
     sprintf(_ip, "ping -c 1 %s > ./ping.txt",ip);
     system("sudo touch ./ping.txt");
     system("chmod 777 ./ping.txt");
     system(_ip);

     fp = fopen("./ping.txt","r");
     if(fp == NULL)
     {
         error_exit("fopen");
     }

     , fp) > )
     {
         line++;
         )
         {
             if((pstr = strstr(buffer, "64 bytes from")) != NULL)
             {
                 while(strstr(pstr, "ttl=64"))
                 {
                     printf("net is ok\n");
                     ;
                 }
             }
             else
             {
                 printf("net is error\n");
                 ;
             }
         }
         memset(buffer,  ,);
     }
     ;
 }

 int main(int argc, const char *argv[])
 {
     ping_ip("192.168.123.24");
     ;
 }