ping实现

ping实现,目前只是实现发不能收,后续完善;

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip_icmp.h>
#include <string.h>

struct my_ping_t {
        struct icmphdr icmp_head;
        char data[64];
};

unsigned short in_cksum(unsigned short *addr,int len) {
        int nleft=len;
        int sum=0;
        unsigned short *w=addr;
        unsigned short answer=0;

        while(nleft>1) {
                sum+=*w++;
                nleft-=2;
        }
        if(nleft==1) {
                *(unsigned char *)(&answer)=*(unsigned char *)w;
                sum+=answer;
        }
        sum=(sum>>16)+(sum & 0xffff);
        sum+=(sum>>16);
        answer=~sum;

        return answer;
}

int main() {
        int sd;
        struct sockaddr_in his_end;
        struct my_ping_t mypacket;
        int i;

        sd=socket(PF_INET,SOCK_RAW,IPPROTO_ICMP);
        if(sd==-1) {
                fprintf(stderr,"socket() error.\n");
                exit(-1);
        }

        his_end.sin_family=AF_INET;
        his_end.sin_port=0;
        his_end.sin_addr.s_addr=inet_addr("127.0.0.1");

        mypacket.icmp_head.type=ICMP_ECHO;
        mypacket.icmp_head.code=0;
        mypacket.icmp_head.un.echo.id=getpid();
        memset(mypacket.data,1,64);
        for(i=0;i<10;i++) {
                mypacket.icmp_head.checksum=0;
                mypacket.icmp_head.un.echo.sequence=htons(i+1);
                mypacket.icmp_head.checksum=in_cksum((unsigned short *)&mypacket,sizeof(mypacket));
                sendto(sd,&mypacket,sizeof(mypacket),0,(struct sockaddr *)&his_end,sizeof(his_end));
                sleep(1);
        }

        close(sd);

        exit(0);
}

你可能感兴趣的:(ping实现)