MyPingip.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #pragma once
  2. #include <sys/socket.h>
  3. #include <netinet/in.h>
  4. #include <netinet/ip.h>
  5. #include <netinet/ip_icmp.h>
  6. #include <arpa/inet.h>
  7. #include <unistd.h>
  8. #include <sys/time.h>
  9. #include <cstring>
  10. #include <fcntl.h>
  11. #include <cerrno>
  12. #define REQ_DATASIZE 32 // Echo请求数据的大小
  13. class CMyPingip
  14. {
  15. public:
  16. CMyPingip(void);
  17. ~CMyPingip(void);
  18. public:
  19. bool PingFunction(const char* pstrHost);
  20. int WaitForEchoReply(int s);
  21. // ICMP回应的请求和回答函数
  22. int SendEchoRequest(int sock, struct sockaddr_in* dest_addr);
  23. long RecvEchoReply(int sock, struct sockaddr_in* from_addr, u_char* pTTL);
  24. unsigned short in_cksum(unsigned short* addr, int len);
  25. // 获取毫秒级时间戳
  26. long GetTickCount();
  27. protected:
  28. int m_sockfd; // 套接字文件描述符
  29. };
  30. // 自定义IP头结构(Linux下已经定义,但为了兼容性保留)
  31. typedef struct IP_HDR
  32. {
  33. u_char VIHL; // Version and IHL
  34. u_char TOS; // Type Of Service
  35. short TotLen; // 总长度
  36. short ID; // 标识
  37. short FlagOff; // 标记
  38. u_char TTL; // 生命期
  39. u_char Protocol; // 协议
  40. u_short Checksum; // 检查和
  41. struct in_addr iaSrc; // 源地址
  42. struct in_addr iaDst; // 目的地址
  43. } IPHDR, * PIPHDR;
  44. // ICMP头结构
  45. typedef struct IC_MPHDR
  46. {
  47. u_char Type; // 类型
  48. u_char Code; // 编码
  49. u_short Checksum; // 检查和
  50. u_short ID; // 标识
  51. u_short Seq; // 顺序
  52. char Data; // 数据
  53. } ICMPHDR, * PICMPHDR;
  54. // ICMP回应请求结构
  55. typedef struct ICMPECHOREQUEST
  56. {
  57. ICMPHDR icmpHdr;
  58. long dwTime;
  59. char cData[REQ_DATASIZE];
  60. } ECHOREQUEST, * PECHOREQUEST;
  61. // ICMP回应结构
  62. typedef struct ICMPECHOREPLY
  63. {
  64. IPHDR iphdr;
  65. ECHOREQUEST echorequest;
  66. char cFiller[256];
  67. } ECHOREPLY, * PECHOREPLY;