#include <windows.h> #include <iphlpapi.h> #include <icmpapi.h> #include <stdio.h> #pragma comment(lib, "iphlpapi.lib") #pragma comment(lib, "ws2_32.lib") int doFlag; //////////////////////////////////////////////////////////////////////////////////////// int __stdcall handler(type) { puts("Ctrl-C pressed..\n"); doFlag = 0; Sleep(4000); return 0; } //////////////////////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { unsigned int err, ipaddr, i, j, min, max, sum; HANDLE hIcmp; char* lpMsgBuf; PICMP_ECHO_REPLY pRepl; SYSTEMTIME st; struct in_addr raddr; char snd[32] = "PINGPINGPINGPINGPINGPINGPINGPIN"; char repl[sizeof(ICMP_ECHO_REPLY) + sizeof(snd)] = {0}; // printf("%08X", _rdrand32_step(111)); if(2 != argc) { printf("Usage: %s IPAddress\n", argv[0]); return -1; } ipaddr = inet_addr(argv[1]); hIcmp = IcmpCreateFile(); if(INVALID_HANDLE_VALUE == hIcmp) { printf("IcmpCreateFile() error..\n"); return -1; } doFlag = 1; SetConsoleCtrlHandler((PHANDLER_ROUTINE)handler, TRUE); for(min = 0xffffffff, max = sum = j = i = 0; doFlag; ++i) { GetLocalTime(&st); printf("%04d.%02d.%02d %02d:%02d:%02d ", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); if(IcmpSendEcho(hIcmp, ipaddr, snd, sizeof(snd), NULL, repl, sizeof(repl), 1000)) { ++j; pRepl = (PICMP_ECHO_REPLY)repl; raddr.S_un.S_addr = pRepl->Address; if(!pRepl->RoundTripTime) { // pRepl->RoundTripTime = 1; printf("time<1ms %s\n", inet_ntoa(raddr)); } else printf("time=%ldms %s\n", pRepl->RoundTripTime, inet_ntoa(raddr)); sum += pRepl->RoundTripTime; if(pRepl->RoundTripTime < min) min = pRepl->RoundTripTime; if(pRepl->RoundTripTime > max) max = pRepl->RoundTripTime; } else { err = GetLastError(); // printf("ICMP error 0x%08x ", err); FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),(LPTSTR)&lpMsgBuf, 0, NULL); printf("Err: 0x%08x, %s", err, lpMsgBuf); LocalFree(lpMsgBuf); } Sleep(1000); } IcmpCloseHandle(hIcmp); printf("Packets: Sent = %d, Received = %d, Lost = %d, <%.0f%% loss>\n", i, j, i - j, ((float)i - (float)j) / (float)i * 100); // if(!min) // ++min; printf("Round trip times: Min = %dms, Max = %dms, Average = %.0fms\n", min, max, (float)sum / j); return 0; } |