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的博客 7702

自己实现的ping源码

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

ping命令源代码

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

qq_42577465的博客 3463

通讯模块_三菱IQ-R PLC串口通讯模块RJ71C24进行Modbus-RTU通讯

在日常的选型中,很多电气工程师咨询我,三菱iQ-R系列有没有Modbus通讯模块,我在这里可以肯定的回复您,这个肯定是有的;我们共有三种可以选择分别是RJ71C24、RJ71C24-R2、RJ71C24-R4。RJ71C24系列支持MC协议通信、通信协议通信、无顺序协议通信、双向协议通信全、MODBUS通信。当我帮助他们选型之后,他们在使用的时候,又是一头雾水。那么今天我抽一些时间讲解一RJ71...

weixin_39878549的博客 9274

Excel地理探测器实战:5分钟搞定空间分异性分析(附完整数据集)

本文详细介绍了如何使用Excel地理探测器插件进行空间分异性分析。通过5分钟实战教程,手把手指导数据格式准备、软件操作及四大探测器(分异及因子、交互作用、风险区、生态探测器)的结果解读,帮助规划师、研究者快速验证地理因素对现象分布的影响,大幅降低GIS分析门槛。

peace的博客 608

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的专栏 6516

半导体物理-Si晶体生长方向<2>

Si(硅)晶体的生长方向是一个重要的概念,尤其在半导体工业中。这个概念涉及到晶体在生长过程中原子排列的方向,对晶体的性质和应用有重大影响。让我为您详细解释:理解Si晶体的生长方向对于半导体材料的研究和应用非常重要,它直接影响了最终器件的性能和制造工艺。在实际应用中,选择适当的生长方向可以优化器件性能,提高产品质量。

m0_37606066的博客 3001

用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)的专栏 1931

【同花顺公式编辑教程】第4章 功能函数

本章节主要给出大部分能够运行且常用的同花顺指标编辑器提供的函数。其中,计算类函数不作演示,绘图类函数提供示例及示例运行结果。

LiaoYi2016218的博客 2万+

从RadixTree到哈希表:深入对比SGLang和vLLM的Prefix Cache实现差异

本文深入对比了SGLang与vLLM在大语言模型推理服务中实现Prefix Cache(前缀缓存)的两种核心方案。SGLang采用基于Radix Tree的RadixAttention,支持任意长度前缀的精确匹配与灵活复用;vLLM则采用基于哈希表的方案,深度集成于PagedAttention,实现简洁但要求块级精确对齐。文章剖析了二者在设计哲学、内存管理、适用场景及集群级优化(如Prefix Cache Aware Routing)上的关键差异,为高性能LLM服务的技术选型提供决策依据。

blockchain9miner的博客 957

ping程序C++源代码

C++实现的ping源代码

wq897387的专栏 754

从“氛围编程“到“智能体工程“:AI编程范式的认知跃迁与工程实践

摘要: 2026年,ClaudeCode负责人鲍里斯·切尔尼提出用“智能体工程”(Agent Engineering)替代流行的“氛围编程”(Vibe Coding),认为后者过于主观,无法体现AI编程的系统化与工程化本质。智能体工程强调记忆系统、工具编排、任务分解、可观测性等核心技术,将AI编程从“玄学辅助”升级为可度量、可规模化的工程学科。本文通过对比术语差异、构建知识体系,并结合代码实例(如带记忆系统的代码生成Agent和可观测性系统),展示了智能体工程的实际应用。行业案例(如ClaudeCode的并

yyq916的博客 1062

ping程序的C语言源代码

PING程序的C语言源代码

wq897387的专栏 1981

干货满满!AI应用架构师分享AI驱动虚拟展示干货

虚拟展示(Virtual Presentation):用数字技术将物理对象/场景转化为可交互的虚拟内容(比如3D文物、虚拟试衣间);AI驱动(AI-Powered):通过AI技术实现实时交互、智能决策、个性化生成,让虚拟内容“活”起来;AI驱动虚拟展示:以用户体验为核心,将“3D渲染+AI理解+实时数据”融合,形成“感知-决策-反馈”的闭环系统。前端交互层是用户直接体验到的部分,再厉害的AI和渲染,只要前端交互烂,用户都会跑。我见过很多团队为了“炫技”做了复杂的AI功能,结果用户不会用。

AI大模型应用之禅 539

AI智算-K8s如何利用GPFS分布式并行文件存储加速训练or推理

GPFS(General Parallel File System,通用并行文件系统)是由 IBM 开发的高性能分布式文件系统,最初设计于 1990 年代,用于满足高性能计算(HPC)环境对大规模数据存储和访问的需求。GPFS 现已广泛应用于企业级存储、云计算、大数据分析、人工智能和媒体处理等领域。它以其高性能、可扩展性和可靠性著称,能够支持从小型集群到超大规模系统的各种部署场景。

Kason_iWiki 1132

python实现ping的源代码

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

wdt3385的专栏 936

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

微软ping程序源代码完整版

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

weixin_30377461的博客 344

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

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

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

miaoshengwu Blog 1944

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

上一篇: 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、付费专栏及课程。

余额充值