Linux:c language through ICMP LAN internal host is alive

Source: Internet
Author: User
Tags socket error

ICMP protocol

ICMP (Internet Control Message, inter-protocol) is an error-control mechanism provided for gateways and target hosts, so that they can report errors to the sender of the message source when they encounter errors.

The ICMP protocol is an IP layer protocol, but because error reporting may also go through several subnets when sent to the source of the message, it involves routing problems, so the ICMP packets are sent via IP protocol.

The data for the ICMP datagram needs a level two encapsulation before it is sent: the ICMP header is added first to form an ICMP packet, and the IP header is added to form an IP datagram.

  main.cpp :

#include <stdio.h>#include<stdlib.h>#include<string.h>#include<strings.h>#include<signal.h>#include<sys/time.h>#include<arpa/inet.h>#include<sys/types.h>#include<sys/socket.h>#include<unistd.h>#include<netinet/inch.h>#include<netinet/ip.h>#include<netinet/ip_icmp.h>#include<netdb.h>#include<setjmp.h>#include<errno.h>#include<sys/Select.h>#include<fcntl.h>#definePacket_size 4096/*algorithms for calculating checksums*/unsigned ShortCal_chksum (unsigned Short*ADDR,intLen) {    intsum=0; intNleft =Len; unsigned Short*w =addr; unsigned ShortAnswer =0; /*Add the ICMP header binary data in 2-byte increments.*/     while(Nleft >1) {sum+ = *w++; Nleft-=2; }    /** If the ICMP header is an odd number of bytes, the last byte is left. * Consider the last byte as a high byte of 2 bytes of data, * the low byte of this 2 byte data is 0, continue to accumulate*/    if(Nleft = =1){        * (unsignedChar*) (&answer) = * (unsignedChar*) W; Sum+ = answer;/*This converts the answer into an int integer*/} sum= (Sum >> -) + (Sum &0xFFFF);/*high-Low add*/sum+ = (sum >> -);/*The overflow bit is also added to sum when the previous step overflows*/Answer= ~sum;/*Note Type conversions, now with a checksum of 16 bits*/    returnanswer;}intLivetestChar*IP) {    CharSendpacket[packet_size];/*Packets Sent*/    CharRecvpacket[packet_size];/*Packets Received*/pid_t pid; intDatalen = About;/*length of data in an ICMP packet*/    structProtoent *Protocol; Protocol= Getprotobyname ("ICMP"); intSOCKFD; intSize = -*1024x768; if((SOCKFD = socket (af_inet, Sock_raw, Protocol->p_proto) <0) {perror ("Socket Error"); } setsockopt (SOCKFD, Sol_socket, So_rcvbuf,&size,sizeof(size)); structsockaddr_in dest_addr; Bzero (&AMP;DEST_ADDR,sizeof(DEST_ADDR)); Dest_addr.sin_family=af_inet; Dest_addr.sin_addr.s_addr=inet_addr (IP); //send packet;    intpacksize; structICMP *ICMP; structTimeval *Tval; ICMP= (structicmp*) Sendpacket; ICMP->icmp_type = Icmp_echo;/*Types of ICMP*/ICMP->icmp_code =0;/*Encoding of ICMP*/ICMP->icmp_cksum =0;/*Checksum of ICMP*/ICMP->icmp_seq =1;/*order number of ICMP*/ICMP->icmp_id = pid;/*the ICMP designator*/packsize=8+ Datalen;/*ICMP8 byte header plus the length of the data (datalen=56), packsize =*/Tval= (structTimeval *) icmp->icmp_data;/*get a pointer to the last part of the data in the ICMP structure*/gettimeofday (Tval, NULL);/*fill in the last data portion of the ICMP structure with the time sent*/ICMP->icmp_cksum = Cal_chksum ((unsigned Short*) ICMP, packsize);/*fills the sender's checksum*/    if(SendTo (SOCKFD, Sendpacket, Packsize,0, (structSOCKADDR *) &dest_addr,sizeof(DEST_ADDR)) <0) {perror ("sendto Error"); } printf ("send%d, send done\n",1 ); intN; structSockaddr_in from; intFromlen =sizeof( from);    Fcntl (SOCKFD, F_SETFL, O_nonblock); structTimeval Timeo = {1,0}; Fd_setSet; Fd_zero (&Set); Fd_set (SOCKFD,&Set); //read, write;    intretval =Select(sockfd+1, &Set, NULL, NULL, &Timeo); if(RetVal = =-1) {printf ("Select error\n"); return 0; }Else if(RetVal = =0) {printf ("timeout\n"); return 0; }Else{        if(Fd_isset (SOCKFD, &Set) {printf ("Host is live\n"); return 1; }    }    //n = recvfrom (SOCKFD, recvpacket,sizeof (Recvpacket), 0, (struct sockaddr *) &from, (socklen_t *) &fromlen); //if (n<0) {//perror ("Recvfrom error"); //}else{//printf ("%d\n", N); // }    //return 0;}intMainintargcChar*argv[]) {printf ("%d\n", Livetest (argv[1])); return 0;}

Reference:

Using the C language to implement the PING program function: http://www.ibm.com/developerworks/cn/linux/network/ping/index.html

NONO
Source: http://www.cnblogs.com/diligenceday/
QQ: 287101329
: 18101055830

Linux:c language through ICMP LAN internal host is alive

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.