Home > other >  The ICMP request and reply
The ICMP request and reply

Time:11-01

I want to imitate the ping, send ICMP request to a host, at the same time accept the reply, but block on the recvfrom, somehow, solving.
 # include & lt; Sys/types. H> 
#include
#include
#include
#include
#include
#include
#include

My own ICMP structure/* */
Struct myicmp
{
Unsigned char icmp_type;
Unsigned char icmp_code;
Unsigned short icmp_cksum;
Unsigned short icmp_id1;
Unsigned short icmp_seq1;
};

/* argv [1] can be either the hostname or IP address */
The main (int arg c, char * argv [])
{
Struct sockaddr_in address;
U_char sendpack [32].
Struct myicmp * icp;
Int Nbytes, sock, status, buf_len;
Struct sockaddr_in Current_Sockaddr;
Char buffer [100].
Struct hostent * host;

If (arg c!
=2){
Usage: printf (" % s & lt; The hostname | IP address> \ n ", argv [0]);
exit(1);
}

If ((host=gethostbyname () (const char * argv [1]))==NULL)
{
If ((address) sin_addr) s_addr=inet_addr (argv [1]))==1)
{
Printf (" % s: unknown host \ n ", argv [1]).
exit(1);
}
}
The else
{
Bcopy (host - & gt; H_addr_list [0], & amp; (address. Sin_addr. S_addr),
The host - & gt; H_length);
}

Memset (sendpack, 0 x0, sizeof (sendpack));
Memset (buffer, 0 x0, sizeof (buffer));

Icp=(struct myicmp *) sendpack;

Icp - & gt; Icmp_type=ICMP_ECHO;
Icp - & gt; Icmp_code=0;
Icp - & gt; Icmp_seq1=1;/* any abritrary sequence number */
Icp - & gt; Icmp_id1=123;/* any arbitrary id */

Address. Sin_family=AF_INET;

/* 1 is for ICMP protocol: the from/etc/separate protocols */
The sock=socket (AF_INET SOCK_RAW, 1);

Buf_len=sizeof (buffer);
Nbytes=sendto (sock, (const void *) sendpack, sizeof (sendpack), 0,
(struct sockaddr *) & amp; Address, sizeof (address));

Printf (" the Data is sent to % s \ n ", inet_ntoa (address. Sin_addr));
Printf (" No of bytes sent=% d \ n ", Nbytes);

Buf_len=sizeof (Current_Sockaddr);

Nbytes=recvfrom (sock, buffer, buf_len, 0,
(struct sockaddr *) & amp; Current_Sockaddr, & amp; Buf_len);

Printf (" Data received from % s \ n ", inet_ntoa (Current_Sockaddr. Sin_addr));

/* get the sequence - id: First 20 bytes are for IP header:
21 t byte is the sequence id */
Icp=(struct myicmp *) & amp; Buffer [20].
Printf (" Received sequence id is % d \ n ", icp - & gt; Icmp_seq1);

Printf (" No of bytes recd=% d \ n ", Nbytes);
}

CodePudding user response:

Caught a look, it may be a target host unreachable? Try 127.0.0.1 can receive the package,
  • Related