当前位置: 代码迷 >> 综合 >> Ping程序C++实现
  详细解决方案

Ping程序C++实现

热度:71   发布时间:2024-01-17 15:06:14.0

学习内容,参见《Windows网络编程》第13章原始套接字

 

Ping程序实现步骤

  1. 创建类型为SOCK_RAW的一个套接字,同时设定协议IPPROTO_ICMP。
  2. 创建并初始化ICMP头。
  3. 调用sendto或WSASendto,将ICMP请求发给远程主机。
  4. 调用recvfrom或WSARecvfrom,以接收任何ICMP响应。

ICMP简介

ICMP是(Internet ControlMessage Protocol)Internet控制报文协议。用于在IP主机、路由器之间传递控制消息。控制消息是指网络通不通、主机是否可达、路由是否可用等网络本身的消息。


系统自带ping程序,检测百度是否可访问。



自己实现ping程序,检测百度是否可访问。

要显示访问IP地址,该IP即为系统自带ping程序解析IP,如上图为119.75.218.77。


使用windows的Winsock 2编程,需要进行工程配置。

  • 工程右键Properties->ConfigurationProperties->Linker->Input->Additional Dependencies中添加ws2_32.lib。
  • Demo代码采用Multi-Byte方式,设置Properties->ConfigurationProperties->General->Character Set为Use Multi-Byte Character Set。

备注:所有关系到收发数据的缓冲都属于简单的char类型,这些函数没有Unicode版本。当字符集为Unicode时,需要进行字符串转换。


程序源码,MyPing.cpp。

// MyPing.cpp : Defines the entry point for the console application.
//#include "stdafx.h"
#include <winsock2.h>
#include <WS2tcpip.h>
#include <stdio.h>
#include <stdlib.h>#define ICMP_ECHO 8
#define ICMP_ECHOREPLY 0
#define ICMP_MIN 8 //Minimum 8-byte ICMP packet (header)#define DEF_PACKET_SIZE 32
#define MAX_PACKET 1024
#define MAX_IP_HDR_SIZE 60//IP header structure
typedef struct _iphdr
{unsigned int h_len:4;//Length of the headerunsigned int version:4;//Version of IPunsigned char tos;//Type of serviceunsigned short total_len;//Total length of the packetunsigned short ident;//Unique identifierunsigned short frag_and_flags;//Flagsunsigned char ttl;//Time to liveunsigned char proto;//Protocol (TCP,UDP,etc.)unsigned short checksum;//IP chec