Windows和Linux 平台下都有一个使用非常频繁的工具: ping
此工具主要是检验网络中两节点间传递的数据包是否可达,计算耗时等,其原理是使用ICMP协议发送echo,并得到目的主机的回显。
以下是实现了最基本ping 功能的C程序,一共有三个文件:
icmphd.h —— 定义报文结构
icmphd.c ——实现其声明的函数
main.c —— 主函数入口
编译环境:
操作系统: win7 sp1
CPU :x86_64
编译器:
1) MinGW-GCC version 4.8.1 (tdm64-2)
2) Microsoft Visual Studio Ultimate 2012 version 11.0.50727.1 RTMREL
注:若使用的是MinGW-GCC,则编译时连接库: -lwsock32,否则因为编译器对函数的默认调用规则不同,无法在Windows SDK中找到
导出的符号(符号不匹配)。运行与调试时使用管理员权限,否则发送时报错,WinSock Error Code = 10013
源代码:
icmphd.h
/*
author : ez
date : 2014/10/20
describe : -
*/
#ifndef _ICMPHD_H_
# define _ICMPHD_H_
#include <stdint.h>
# define DEF_DATA_LEN 0x10
// random number
// # define DEF_IDENTIFY 0x0003
#pragma pack (1)
struct iphd {
uint8_t m_cVersionAndHeaderLen;
uint8_t m_cTypeOfService;
uint16_t m_sTotalLenOfPacket;
uint16_t m_sPacketID;
uint16_t m_sSliceinfo;
uint8_t m_cTTL;
uint8_t m_cTypeOfProtocol;
uint16_t m_sCheckSum;
uint32_t m_uiSourIp;
uint32_t m_uiDestIp;
};
struct icmphd {
uint8_t type;
uint8_t code;
uint16_t chksum;
uint16_t identifier;
uint16_t seqnum; // big-endian
};
struct icmppk {
struct icmphd hd;
uint8_t data [DEF_DATA_LEN];
};
#pragma pack ()
# define ICMPHD_SIZE (sizeof (struct icmphd))
# define ICMPPK_SIZE (sizeof (struc