ping的源代码

ping源代码完全解析(1) ping源代码完全解析--------------------------------------------------author:    Zero1,lingyi.pro#163.comdate:        2008-04-27--------------------------------------------------目录-------------1.相关知识2.相关数据结构3. 阅读详情
// Module Name: Ping.c
//
// Code by Rise
//
// Command Line Options/Parameters:
//        Ping [host] [packet-size]
//
//        host        String name of host to ping
//        packet-size    Integer size of packet to send (smaller than 1024 bytes)
//
//#pragma pack(1)

#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <stdlib.h>

#define IP_RECORD_ROUTE 0x7
//
// IP header structure
//
typedef struct _iphdr
{
    unsigned int    h_len:4;        // Length of the header
    unsigned int    version:4;        // Version of IP
    unsigned char     tos;            // Type of service
    unsigned short    total_len;        // Total length of the packet
    unsigned short    ident;            // Unique identifier
    unsigned short    frag_and_flags;    // Flags
    unsigned short    ttl;            // Time to live
    unsigned short    proto;            // Protocol (TCP, UDP, etc.)
    unsigned short    checksum;        // IP checksum
    
    unsigned int        sourceIP;
    unsigned int        destIP;
}IpHeader;

#define ICMP_ECHO        8
#define ICMP_ECHOREPLY    0
#define ICMP_MIN        8    // Minimun 8-byte ICMP packet (header)

//
// ICMP header structure
//
typedef struct _icmphdr
{
    BYTE        i_type;
    BYTE        i_code;        // Type sub code
    USHORT    i_cksum;
    USHORT    i_id;
    USHORT    i_seq;
    // This is not the standard header, but we reserve space for time
    ULONG timestamp;
}IcmpHeader;

//
// IP option header -- use with socket option IP_OPTIONS
//
typedef struct _ipoptionhdr
{
    unsigned char    code;        // Option type
    unsigned char    len;        // Length of option hdr
    unsigned char    prt;        // Offset into options
    unsigned long    addr[9];    // List of IP addrs
}IpOptionHeader;
#define DEF_PACKET_SIZE 32        // Default packet size
#define MAX_PACKET        1024    // Max ICMP packet size
#define MAX_IP_HDR_SIZE    60        // Max IP header size w/options

BOOL    bRecordRoute;
int        datasize;
char*    lpdest;

//
// Function: usage
//
// Description:
//        Print usage information
//
void usage(char* progname)
{
    printf("usage: ping -r <host> [data size]/n");
    printf("    -r        record route/n");
    printf("    host    remote machine to Ping/n");
    printf("    datasize    can be up to 1 KB/n");
    ExitProcess(-1);
}

//
// Function: FillICMPData
//
// Description:
//        Helper function to fill in various fields for our ICMP request
//
void FillICMPData(char* icmp_data, int datasize)
{
    IcmpHeader*    icmp_hdr = NULL;
    char*        datapart = NULL;
    
    icmp_hdr = (IcmpHeader*)icmp_data;
    icmp_hdr->i_type = ICMP_ECHO;        // Request an ICMP echo
    icmp_hdr->i_code = 0;
    icmp_hdr->i_id = (USHORT)GetCurrentProcessId();
    icmp_hdr->i_cksum = 0;
    icmp_hdr->i_seq = 0;
    
    datapart = icmp_data + sizeof(IcmpHeader);
    //
    // Place some junk in the buffer
    //
    memset(datapart, 'E', datasize - sizeof(IcmpHeader));
}

//
// Function: checksum
//
// Description:
//        This funcion calculates the 16-bit one's complement sum
//        of the supplied buffer (ICMP)header
//
USHORT checksum(USHORT* buffer, int size)
{
    unsigned long cksum = 0 ;
    
    while(size > 1)
    {
        cksum += *buffer++;
        size -= sizeof(USHORT);
    }
    if(size)
    {
        cksum += *(UCHAR*)buffer;
    }
    cksum = (cksum>>16)+(cksum&0xffff);
    cksum += (cksum>>16);
    return (USHORT)(~cksum);
}

//
// Function: DecodeIPOptions
//
// Description:
//        If the IP option header is present. find the IP options
//        within the IP header and print the record route option
//        values
//
void DecodeIPOptions(char*buf,int bytes)
{
    IpOptionHeader* ipopt = NULL;
    IN_ADDR    inaddr;
    int     i;
    HOSTENT *host = NULL;
    
    ipopt = (IpOptionHeader*)(buf + 20);
    
    printf("RR:    ");
    for(i=0;i<(ipopt->prt/4)-1;i++)
    {
        inaddr.S_un.S_addr = ipopt->addr[i];
        if(i != 0 )
            printf("    ");
        host = gethostbyaddr((char*)&inaddr.S_un.S_addr, sizeof(inaddr.S_un.S_addr), AF_INET);
        if(host)
            printf("(%-15s) %s/n", inet_ntoa(inaddr), host->h_name);
        else
            printf("(%-15s)/n", inet_ntoa(inaddr));
    }
    return;
}

//
// Function: DecodeICMPHeader
//
// Description:
//        The response is an IP packet. We must decode the IP header to locate the ICMP data.
//
void DecodeICMPHeader(char* buf, int bytes, struct sockaddr_in *from)
{
    IpHeader*    iphdr = NULL;
    IcmpHeader*    icmphdr = NULL;
    unsigned short iphdrlen;
    DWORD        tick;
    static int    icmpcount = 0;
    
    iphdr = (IpHeader*)buf;
    // Number of 32-bit words * 4 = bytes
    iphdrlen = iphdr->h_len * 4;
    tick = GetTickCount();
    
    if((iphdrlen == MAX_IP_HDR_SIZE)&&(!icmpcount))
        DecodeIPOptions(buf,bytes);
    if(bytes < iphdrlen + ICMP_MIN)
    {
        printf("Too Few bytes from %s/n",inet_ntoa(from->sin_addr));
    }
    icmphdr = (IcmpHeader*)(buf + iphdrlen);
    
    if(icmphdr->i_type != ICMP_ECHOREPLY)
    {
        printf("nonecho type %d recvd/n", icmphdr->i_type);
        return;
    }
    // Make sure this is an ICMP reply to something we sent!
    //
    if(icmphdr->i_id != (USHORT)GetCurrentProcessId())
    {
        printf("someone else's packet!/n");
        return;
    }
    printf("%d bytes from %s:", bytes, inet_ntoa(from->sin_addr));
    printf(" icmp->seq = %d.", icmphdr->i_seq);
    printf(" time: %d ms", tick-icmphdr->timestamp);
    printf("/n");
    
    icmpcount++;
    return;
}

void ValidateArgs(int argc, char **argv)
{
    int i;
    bRecordRoute = FALSE;
    lpdest = NULL;
    datasize = DEF_PACKET_SIZE;
    
    for(i = 1; i < argc; i++)
    {
        if((argv[i][0] == '-')||(argv[i][0] == '/'))
        {
            switch(tolower(argv[i][1]))
            {
                case 'r':        // Record route option
                    bRecordRoute = TRUE;
                    break;
                default:
                    usage(argv[0]);
                    break;
            }
        }
        else if(isdigit(argv[i][0]))
            datasize = atoi(argv[i]);
        else
            lpdest = argv[i];
    }
}

//
// Function: main
//
// Description
//        Set up the ICMP raw socket, and create the ICMP header. Add
//        the appropriate IP ooption header, and start sending ICMP
//        echo requests to the endpoint. For each send and receive.
//        we set a timeout value so that we don't wait forever for a
//        response in case the endpoint is not responding. When we
//        receive a packet. decode it.
//
int main(int argc, char** argv)
{
    WSADATA    wsaData;
    SOCKET    sockRaw = INVALID_SOCKET;
    struct sockaddr_in dest, from;
    int        bread, fromlen = sizeof(from), timeout = 1000, ret;
    char    *icmp_data = NULL, *recvbuf = NULL;
    unsigned int addr = 0;
    USHORT    seq_no = 0;
    struct hostent *hp = NULL;
    IpOptionHeader ipopt;
    
    if(WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
    {
        printf("WSAStartup() failed: %d/n", GetLastError());
        return -1;
    }
    ValidateArgs(argc,argv);
    sockRaw = WSASocket(AF_INET, SOCK_RAW, IPPROTO_ICMP, NULL, 0, WSA_FLAG_OVERLAPPED);
    if(sockRaw == INVALID_SOCKET)
    {
        printf("WSASocket() failed: %d/n", WSAGetLastError());
        return -1;
    }
    if(bRecordRoute)
    {
        // Setup the IP option header to go out on every ICMP packet
        //
        ZeroMemory(&ipopt, sizeof(ipopt));
        ipopt.code = IP_RECORD_ROUTE;    // Record route option
        ipopt.prt  = 4;                    // Point to the first addr offset
        ipopt.len  = 39;                // Length of option header
        
        ret = setsockopt(sockRaw, IPPROTO_IP, IP_OPTIONS, (char*)&ipopt, sizeof(ipopt));
        if(ret == SOCKET_ERROR)
        {
            printf("setsockopt(IP_OPTIONs) failed: %d/n",WSAGetLastError());
        }
    }
    // Set the send/recv timeout values
    //
    bread = setsockopt(sockRaw, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));
    if(bread == SOCKET_ERROR)
    {
        printf("setsockopt(SO_RCVTIME0)failed: %d/n", WSAGetLastError());
        return -1;
    }
    timeout = 1000;
    bread = setsockopt(sockRaw, SOL_SOCKET, SO_SNDTIMEO, (char*)&timeout, sizeof(timeout));
    if(bread == SOCKET_ERROR)
    {
        printf("setsockopt(SO_SNDTIME0) failed: %d/n", WSAGetLastError());
        return -1;
    }
    memset(&dest, 0, sizeof(dest));
    //
    // Resolve the endpoint`s name if necessary
    //
    dest.sin_family = AF_INET;
    if((dest.sin_addr.s_addr = inet_addr(lpdest)) == INADDR_NONE)
    {
        if((hp = gethostbyname(lpdest)) != NULL)
        {
            memcpy(&(dest.sin_addr), hp->h_addr, hp->h_length);
            dest.sin_family = hp->h_addrtype;
            printf("dest.sin_addr = %s/n", inet_ntoa(dest.sin_addr));
        }
        else
        {
            printf("gethostbyname() failed: %d/n",WSAGetLastError());
            return -1;
        }
    }
    
    //
    // Create the ICMP packet
    //
    datasize += sizeof(IcmpHeader);
    icmp_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, MAX_PACKET);
    recvbuf = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, MAX_PACKET);
    if(!icmp_data)
    {
        printf("HeapAlloc() failed: %d/n",GetLastError());
        return -1;
    }
    memset(icmp_data, 0, MAX_PACKET);
    FillICMPData(icmp_data, datasize);
    //
    // Start sending/receiving ICMP packets
    //
    while(1)
    {
        static int nCount = 0;
        int bwrote;
        
        if(nCount++ ==4)
            break;
        ((IcmpHeader*)icmp_data)->i_cksum = 0;
        ((IcmpHeader*)icmp_data)->timestamp = GetTickCount();
        ((IcmpHeader*)icmp_data)->i_seq = seq_no++;
        ((IcmpHeader*)icmp_data)->i_cksum = checksum((USHORT*)icmp_data, datasize, 0, (struct sockaddr*)&dest, sizeof(dest));
        
        bwrote = sendto(sockRaw, icmp_data, datasize, 0, (struct sockaddr*)&dest, sizeof(dest));
        if(bwrote == SOCKET_ERROR)
        {
            if(WSAGetLastError() == WSAETIMEDOUT)
            {
                printf("timed out/n");
                continue;
            }
            printf("recvfrom() failed: %d/n", WSAGetLastError());
            return -1;
        }
        if(bwrote < datasize)
        {
            printf("Wrote %d bytes/n", bwrote);
        }
        bread = recvfrom(sockRaw, recvbuf, MAX_PACKET, 0, (struct sockaddr*)&from, &fromlen);
        if(bread == SOCKET_ERROR)
        {
            if(WSAGetLastError() == WSAETIMEDOUT)
            {
                printf("timed out/n");
                continue;
            }
            printf("recvfrom() failed: %d/n", WSAGetLastError());
        }
        DecodeICMPHeader(recvbuf, bread, &from);
        
        Sleep(1000);
    }
    
    //Cleanup
    //
    if(sockRaw != INVALID_SOCKET)
        closesocket(sockRaw);
    HeapFree(GetProcessHeap(), 0, recvbuf);
    HeapFree(GetProcessHeap(), 0, icmp_data);
    
    WSACleanup();
    return 0;
}
C语言实现cmd中的ping(附完整源码) 阅读详情

相关推荐

MFC实现网络诊断工具:ping源代码分析

Microsoft Foundation Classes(MFC)库是一个用于创建Windows应用程序的C++类库,由微软提供,是微软Visual C++开发环境的一部分。MFC旨在封装Win32 API的复杂性,提供更为方便、面向对象的编程接口,以简化Windows桌面应用程序的开发。通过MFC,开发者可以使用类和对象来处理窗口、菜单、控件等GUI元素,并实现消息处理、事件响应等功能。

weixin_30820933的博客 1123

ping源码分析(超详细,多图,带背景分析)

ping源码分析 1. 背景知识简介 1.1 ping简介 ​ Ping是Windows、Unix和Linux系统下的一个命令。ping也属于一个通信协议,是TCP/IP协议的一部分。利用“ping”命令可以检查网络是否连通,可以很好地帮助我们分析和判定网络故障。ping程序是基于ICMP协议实现的。 ​ Ping命令常见格式:ping [-t] [-a] [-n count] [-l...

weixin_38371073的博客 7704

自己实现的ping源码

自己实现的ping源码,C语言实现的,可自行编译修改运行。

ping命令源代码

内容简介: 编写自己的一个ping程序,可以说是许多人迈出网络编程的第一步吧!!这个ping程序的源代码经过我的修改和调试,基本上可以取代windows中自带的ping程序. 各个模块后都有我的详细注释和修改日志,希望能够对大家的学习有所帮助!! /* 本程序的主要源代码来自MSDN网站, 笔者只是做了一些改进和注释! 另外需要注意的是在Build之前,必须加入ws2_32.lib库文件,否...

qq_42577465的博客 3463

单细胞测序流程(十)KEGG通路富集分析与可视化圈图实战解析

本文详细解析了单细胞测序数据分析中KEGG通路富集分析与可视化圈图的完整实战流程。从差异表达基因列表出发,通过R语言进行KEGG富集分析,并利用Perl脚本进行基因ID转换,最终使用GOplot包绘制高级可视化圈图,帮助研究者将基因列表转化为有意义的生物学故事。

i7j8k9l的博客 410

CTransformers: 高效的Python语言模型绑定库

CTransformers是一个为C/C++实现的Transformer模型提供Python绑定的开源库。它基于GGML库构建,旨在为开发者提供一种高效且易用的方式来在Python中使用各种流行的语言模型。支持多种流行的语言模型,如GPT-2、LLaMA、Falcon等提供统一的简单API接口支持GPU加速(CUDA和Metal)与Hugging Face Transformers和LangChain集成支持流式输出和嵌入计算。

helloaiworld的博客 1270

IPV6下的ping源代码

IPV6下的ping源代码,摘至iputils源代码中 /* * * Modified for AF_INET6 by Pedro Roque * * * * Original copyright notice included bellow */ /* * Copyright (c) 1989 The Regents of the University

Jieen的专栏 6518

用STM32F407做个USB声卡:从CubeMX配置到播放录音全功能实战(附源码)

本文详细介绍了如何使用STM32F407开发板实现USB音频设备的全功能实战,包括CubeMX配置、硬件连接、音频流处理和性能优化。通过双缓冲DMA机制和音频数据处理流程,开发者可以构建高质量的USB声卡系统,适用于录音和播放场景。附源码,助力快速上手STM32音频开发。

weixin_30301449的博客 519

用vb来Ping的源代码

 Option Explicit Public Const IP_STATUS_BASE = 11000Public Const IP_SUCCESS = 0Public Const IP_BUF_TOO_SMALL = (11000 + 1)Public Const IP_DEST_NET_UNREACHABLE = (11000 + 2)Public Const IP_DEST_HOST_UN

寒风雨(lanman)的专栏 1932

[RK3568 Android11] 开发之默认授予系统预置的APP权限

目录 一、系统预置的APP权限 二、默认授予系统预置的APP权限 一、系统预置的APP权限 1、在打开系统预置的APP时,都会弹窗提示,并且需要人工确定授予权限; 2、有些客户对定制有需求,需要系统预置的APP自动默认授予权限; 二、默认授予系统预置的APP权限 注意此方法只对系统预置的APP起效果,后期手动安装的APP无效; 修改文件: frameworks/base/services/core/java/com/android/server/pm/per...

~未来可期~ 5061

31、Labview如何搭建程序框架?--状态机到数据采集等常用框架

本文废话不多,直接列举几种框架搭建方式,为了尽量向大家提供干货,本文直接从简介和手把手教搭建框架两方面来讲解,本文提到五种经典框架模式,学会这五种就很够了,分别是:状态机框架(State Machine)、生产者-消费者框架(Producer-Consumer)、主-从框架(Master-Slave)、事件驱动框架(Event-Driven)、分层架构(Layered Architecturep)。这个框架是基于状态机结构的。顾名思义“状态机”就是个“切换程序状态的机器”。本质是一个。

关注我,更多技术问题欢迎私聊~ 3109

ping程序C++源代码

C++实现的ping源代码

wq897387的专栏 754

Veritas NetBackup8.1.1客户端安装

1.在客户机打开安装包运行Browser 2.选择NetBackup Client Software Installation 3.下一步 4.接受,下一步 5.我选择自定义安装,下一步 6.我选择安装到D盘 7.默认下一步 8.使用域管理账户 9.输入服务器安装了服务端的那一台名称 10.输入服务端生成的令牌,选择“I recognize the fingerprint for this host.Proceed with the certificate deploymen”下一步

万物皆可学 2万+

ping程序的C语言源代码

PING程序的C语言源代码

wq897387的专栏 1982

Python爬虫实战:携程/飞猪酒店信息爬取与动态价格分析

在当今数字化旅游时代,酒店预订平台的复杂筛选条件和动态定价机制为数据分析和价格监控带来了巨大挑战。本文将深入探讨如何使用最新的Python爬虫技术来抓取携程和飞猪平台的酒店信息,处理复杂的筛选条件,并解析动态价格数据。本文详细介绍了如何使用最新的Python爬虫技术来抓取携程和飞猪平台的酒店信息。通过结合httpxplaywrightparsel强大的反反爬虫能力:通过浏览器指纹伪装、请求签名、智能延迟等技术应对各种反爬措施高效的数据解析:使用CSS选择器和XPath精确提取所需信息灵活的数据存储。

2201_76125261的博客 419

matlab 一维相位解缠

一维相位解缠算法的matlab代码实现。

点云侠的博客 376

python实现ping的源代码

http://www.lisdn.com/?viewnews-16173

wdt3385的专栏 938

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

微软ping程序源代码完整版

微软ping程序源代码完整版 作者:侯志江 编写自己的一个ping程序,可以说是许多人迈出网络编程的第一步吧!!这个ping程序的源代码经过我的修改和调试,基本上可以取代windows中自带的ping程序. 各个模块后都有我的详细注释和修改日志,希望能够对大家的学习有所帮助!! /* 本程序的主要源代码来自MSDN网站, 笔者只是做了一些改进和注释! 另外需要注意的是在Build之前,必须...

weixin_30377461的博客 344

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

[VC]微软ping程序源代码完整版

[VC]微软ping程序源代码完整版内容简介: 编写自己的一个ping程序,可以说是许多人迈出网络编程的第一步吧!!这个ping程序的源代码经过我的修改和调试,基本上可以取代windows中自带的ping程序. 各个模块后都有我的详细注释和修改日志,希望能够对大家的学习有所帮助!!/* 本程序的主要源代码来自MSDN网站, 笔者只是做了一些改进和注释! 另外需要注意的是在Build之前,必须加

miaoshengwu Blog 1946
上一篇: Resources for Developers of USB Devices in the
下一篇: LAB:互联网出口备份
iiprogram
博客等级 码龄25年 1068粉丝 1515原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址