std::vector<double> Pinger::runPingProcessInstance(const uint16_t requestCount, const double delay){ std::vector<double> result; this->progressMutex.lock(); this->progress = 0; this->progressMutex.unlock(); double progressStep = 1.0 / requestCount; WSADATA wsaData; int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if(iResult != 0) throw std::runtime_error("WSAStartup failed"); PDNS_RECORD dnsResultPtr; DNS_STATUS dnsStatus = DnsQuery_UTF8(this->host.c_str(), DNS_TYPE_A, DNS_QUERY_STANDARD, nullptr, &dnsResultPtr, nullptr); if(dnsStatus != DNS_RCODE_NOERROR) throw std::runtime_error("DnsQuery error"); IP4_ADDRESS ip = dnsResultPtr->Data.A.IpAddress; HANDLE hIcmp = IcmpCreateFile(); if(hIcmp == INVALID_HANDLE_VALUE) throw std::runtime_error("IcmpCreateFile error"); char SendData[32]; DWORD ReplySize = sizeof(ICMP_ECHO_REPLY) + sizeof(SendData); LPVOID ReplyBuffer = reinterpret_cast<LPVOID>(malloc(ReplySize)); if(ReplyBuffer == nullptr) throw std::runtime_error("malloc error"); std::chrono::duration<int, std::milli> pingDelay(static_cast<int>(delay * 1000)); for(uint32_t i = 0; i < requestCount && this->stopFlag == false; ++i){ auto lastTime = std::chrono::high_resolution_clock::now(); DWORD resIcmp = IcmpSendEcho(hIcmp, ip, SendData, sizeof(SendData), nullptr, ReplyBuffer, ReplySize, 1000); if(resIcmp == 0) throw std::runtime_error("IcmpSendEcho error"); PICMP_ECHO_REPLY pReply = reinterpret_cast<PICMP_ECHO_REPLY>(ReplyBuffer); result.push_back(pReply->RoundTripTime); this->progressMutex.lock(); if(this->progress + progressStep <= 1.0){//если шагов больше чем requestCount - не переполняем счетчик this->progress += progressStep; } this->progressMutex.unlock(); if(i < requestCount) std::this_thread::sleep_until(lastTime + pingDelay); } if(this->stopFlag == false){ this->progressMutex.lock(); this->progress = 1.0; this->progressMutex.unlock(); } return result; }
void Refresh() { *BUFFER = '\0'; Ping[0].clear(); hIcmpFile = IcmpCreateFile(); ReplySize = sizeof(ICMP_ECHO_REPLY) + sizeof(BUFFER); ReplyBuffer = static_cast<VOID*>(malloc(ReplySize)); dwRetVal = IcmpSendEcho(hIcmpFile, EUW, BUFFER, sizeof(BUFFER), nullptr, ReplyBuffer, ReplySize, 1000); auto pEchoReply = static_cast<PICMP_ECHO_REPLY>(ReplyBuffer); Ping[0] << pEchoReply->RoundTripTime; }
DWORD WINAPI NetworkThreadProc(void* pParam) { // NOTE: Do not use CRT functions (since thread was created by CreateThread())! MeasureData* measure = (MeasureData*)pParam; const DWORD bufferSize = sizeof(ICMP_ECHO_REPLY) + 32; BYTE buffer[bufferSize]; double value = 0.0; HANDLE hIcmpFile = IcmpCreateFile(); if (hIcmpFile != INVALID_HANDLE_VALUE) { IcmpSendEcho(hIcmpFile, measure->destAddr, NULL, 0, NULL, buffer, bufferSize, measure->timeout); IcmpCloseHandle(hIcmpFile); ICMP_ECHO_REPLY* reply = (ICMP_ECHO_REPLY*)buffer; value = (reply->Status != IP_SUCCESS) ? measure->timeoutValue : reply->RoundTripTime; if (!measure->finishAction.empty()) { RmExecute(measure->skin, measure->finishAction.c_str()); } } HMODULE module = NULL; EnterCriticalSection(&g_CriticalSection); if (measure->threadActive) { measure->value = value; measure->threadActive = false; } else { // Thread is not attached to an existing measure any longer, so delete // unreferenced data. delete measure; DWORD flags = GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT; GetModuleHandleEx(flags, (LPCWSTR)DllMain, &module); } LeaveCriticalSection(&g_CriticalSection); if (module) { // Decrement the ref count and possibly unload the module if this is // the last instance. FreeLibraryAndExitThread(module, 0); } return 0; }
int ping(unsigned int host, int *timeout, int *err, int packetcount) { HANDLE icmp; int status = 0; ICMP_ECHO_REPLY *reply; int replylen; int i; if((icmp = IcmpCreateFile()) != INVALID_HANDLE_VALUE) { replylen = sizeof(ICMP_ECHO_REPLY) + 32; if((reply = malloc(replylen))) { for(i = 0; i < packetcount; ++i) { if(IcmpSendEcho( icmp, (IPAddr)htonl(host), NULL, 0, NULL, reply, (DWORD)replylen, (DWORD)*timeout)) { if(reply->Status == IP_SUCCESS) { *timeout = reply->RoundTripTime; status = 1; } } if(status) { break; } } free(reply); } IcmpCloseHandle(icmp); } else { *err = 1; } return status; }
long _stdcall ping(char *error, char *host) { IPAddr ip; WORD w = MAKEWORD(1,1); WSADATA wsadata; strset(error, 0); WSAStartup(w, &wsadata); hostent* phostent; if( host[0] <= '9') ip = (IPAddr)inet_addr(host); else { phostent = gethostbyname(host); if(!phostent) { strcpy(error, "Unable to resolve host name."); return -1; } ip = *(DWORD*)(*phostent->h_addr_list); } HANDLE icmphandle = IcmpCreateFile(); char reply[sizeof(icmp_echo_reply)+8]; icmp_echo_reply* iep = (icmp_echo_reply*)&reply; iep->RoundTripTime = 0xffffffff; IcmpSendEcho(icmphandle,ip,0,0,NULL,reply,sizeof(icmp_echo_reply)+8,PING_TIMEOUT); IcmpCloseHandle(icmphandle); WSACleanup(); if(iep->RoundTripTime == PING_TIMEOUT) { strcpy(error, "Timeout."); return -1; } return iep->RoundTripTime; }
bool TMain::Ping(String HostName) { bool Result; HANDLE hIcmpFile; unsigned long ipaddr; DWORD dwRetVal; char SendData[32] = "Data Buffer"; LPVOID ReplyBuffer; DWORD ReplySize; ipaddr = inet_addr(AnsiString(HostName).c_str()); Result = ipaddr != INADDR_NONE; if (Result) { hIcmpFile = IcmpCreateFile(); Result = hIcmpFile != INVALID_HANDLE_VALUE; if (Result) { ReplySize = sizeof(ICMP_ECHO_REPLY)+sizeof(SendData); ReplyBuffer = (VOID*) malloc(ReplySize); Result = ReplyBuffer != NULL; if (Result) { dwRetVal = IcmpSendEcho(hIcmpFile, ipaddr, SendData, sizeof(SendData), NULL, ReplyBuffer, ReplySize, 1000); Result = dwRetVal != 0; if (Result) { PICMP_ECHO_REPLY pEchoReply = (PICMP_ECHO_REPLY) ReplyBuffer; Result = pEchoReply->Status == IP_SUCCESS; } } IcmpCloseHandle(hIcmpFile); } } return Result; }
Duration IcmpImpl::ping(const IpAddressV4& address, const Duration& timeout) { HANDLE icmpHandle = IcmpCreateFile(); Expect(icmpHandle != INVALID_HANDLE_VALUE, Throw(Win32Error, "Failed to create ICMP handler")); ByteArray request(32); IPAddr addr = address.toInt(); ByteArray response(sizeof(ICMP_ECHO_REPLY) + request.getCapacity()); DWORD retval = IcmpSendEcho(icmpHandle, addr, &request[0], request.getCapacity(), nullptr, &response[0], response.getCapacity(), timeout.asMilliseconds()); Expect(retval > 0, Throw(Win32Error, "Failed to send ICMP request")); const ICMP_ECHO_REPLY* reply = reinterpret_cast<const ICMP_ECHO_REPLY*>(response.getBuffer()); Duration duration = Duration::milliseconds(reply->RoundTripTime); IcmpCloseHandle(icmpHandle); return duration; }
DWORD CIcmpEcho::PingHost(unsigned long ulIP, int iPingTimeout) { //Task 1: Open ICMP Handle //Task 2: Create Structure to receive ping reply //Task 3: SendPing (SendEcho) //Task 4: Close ICMP Handle //Task 5: Return RoundTripTime unsigned long ip = ulIP; HANDLE icmphandle = IcmpCreateFile(); char reply[sizeof(icmp_echo_reply)+8]; icmp_echo_reply* iep=(icmp_echo_reply*)&reply; iep->RoundTripTime = 0xffffffff; IcmpSendEcho(icmphandle,ip,0,0,NULL,reply,sizeof(icmp_echo_reply)+8,iPingTimeout); IcmpCloseHandle(icmphandle); return iep->RoundTripTime; }
int main(int argc, char **argv){ if( argc<2){ printf("Usage: %s <ip address>\n", argv[0]); return 1; } if( IsDebuggerPresent()){ HANDLE iphlpapi=LoadLibrary("iphlpapi.dll"); if( !iphlpapi){ perror("iphlpapi.dll"); return 1; } FARPROC IcmpSendEcho=GetProcAddress(iphlpapi, "IcmpSendEcho"); FARPROC IcmpCreateFile=GetProcAddress(iphlpapi, "IcmpCreateFile"); FARPROC IcmpCloseHandle=GetProcAddress(iphlpapi, "IcmpCloseHandle"); if( (IcmpSendEcho && IcmpCreateFile && IcmpCloseHandle)==0){ perror("icmp functions"); return 1; } unsigned long ipaddr=INADDR_NONE, params[2]; HANDLE hIcmpFile; char data[32], *reply; int replySize=sizeof(ICMP_ECHO_REPLY)+sizeof(data); if( (ipaddr=inet_addr(argv[1]))==INADDR_NONE){ perror("Illegal IP address!"); return 1; } if( (hIcmpFile=(HANDLE)IcmpCreateFile())==INVALID_HANDLE_VALUE){ perror("IcmpCreateFile"); return 1; } reply=(char *)malloc(replySize); ZeroMemory(data, sizeof(data)); params[0]=PARAM; params[1]=(unsigned long)GetProcAddress(iphlpapi, "IcmpSendEcho2Ex"); RaiseException(EXCEPTION_BREAKPOINT, 0, 2, params); puts("Exception raised!"); IcmpSendEcho(hIcmpFile, ipaddr, data, sizeof(data), NULL, reply, replySize, 1000); puts("This line should never be shown..."); IcmpCloseHandle(hIcmpFile); return 0; } PROCESS_INFORMATION pi; STARTUPINFO si; HANDLE hProcess, hThread; DEBUG_EVENT debugEvent; EXCEPTION_RECORD *ExceptionRecord=&debugEvent.u.Exception.ExceptionRecord; CONTEXT context; FARPROC IcmpSendEcho2Ex=NULL; char path[256], args[512], originalByte[1]; ZeroMemory(?, sizeof(PROCESS_INFORMATION)); ZeroMemory(&si, sizeof(STARTUPINFO)); ZeroMemory(&debugEvent, sizeof(DEBUG_EVENT)); ZeroMemory(&context, sizeof(CONTEXT)); ZeroMemory(path, sizeof(path)); ZeroMemory(args, sizeof(args)); si.cb=sizeof(STARTUPINFO); si.dwFlags=STARTF_USESHOWWINDOW; si.wShowWindow=SW_HIDE; context.ContextFlags=CONTEXT_FULL | CONTEXT_DEBUG_REGISTERS; GetModuleFileName(NULL, path, sizeof(path)-1); snprintf(args, sizeof(args)-1, "%s %s", path, argv[1]); if( !CreateProcess( NULL, args, NULL, NULL, FALSE, DEBUG_PROCESS, NULL, NULL, &si, ? )){ perror("CreateProcess"); return 1; } if( (hProcess=OpenProcess(PROCESS_ALL_ACCESS, FALSE, pi.dwProcessId))==NULL){ perror("OpenProcess"); return 1; } HANDLE kernel32=LoadLibrary("kernel32.dll"); FARPROC DebugSetProcessKillOnExit=GetProcAddress(kernel32, "DebugSetProcessKillOnExit"); FARPROC DebugActiveProcessStop=GetProcAddress(kernel32, "DebugActiveProcessStop"); FARPROC OpenThread=GetProcAddress(kernel32, "OpenThread"); CloseHandle(kernel32); DebugSetProcessKillOnExit(TRUE); while(WaitForDebugEvent(&debugEvent, INFINITE) && debugEvent.dwDebugEventCode!=EXIT_PROCESS_DEBUG_EVENT){ if( debugEvent.dwDebugEventCode==EXCEPTION_DEBUG_EVENT && ExceptionRecord->ExceptionCode==EXCEPTION_BREAKPOINT){ if( ExceptionRecord->NumberParameters>1 && ExceptionRecord->ExceptionInformation[0]==PARAM){ IcmpSendEcho2Ex=(FARPROC)ExceptionRecord->ExceptionInformation[1]; printf("IcmpSendEcho2Ex %p\n", IcmpSendEcho2Ex); if( !BreakpointSet(hProcess, IcmpSendEcho2Ex, &originalByte)){ perror("BreakpointSet"); break; } } else if( ExceptionRecord->ExceptionAddress==IcmpSendEcho2Ex){ printf("EIP %p\n", IcmpSendEcho2Ex); if( !BreakpointRetrieve(hProcess, IcmpSendEcho2Ex, &originalByte)){ perror("BreakpointRetrieve"); break; } if((hThread=(HANDLE)OpenThread(THREAD_ALL_ACCESS, FALSE, debugEvent.dwThreadId))==NULL) puts("OpenThread"); if(!GetThreadContext(hThread, &context)) puts("GetThreadContext"); context.Eip -= 1; if(!SetThreadContext(hThread, &context)) puts("SetThreadContext"); CreateThread(NULL, 0, (void *)Terminate, hProcess, 0, NULL); } } else if( debugEvent.dwDebugEventCode==EXCEPTION_DEBUG_EVENT){ puts("Exception!"); DebugActiveProcessStop(debugEvent.dwProcessId); break; } ContinueDebugEvent(debugEvent.dwProcessId, debugEvent.dwThreadId, DBG_CONTINUE); ZeroMemory(&debugEvent, sizeof(DEBUG_EVENT)); } return 0; }
bool Ping(std::wstring sServerIP) { // Obtain an ICMP handle. HANDLE hIcmp = IcmpCreateFile(); if (!hIcmp) { _ASSERTE (0 && L" IGPing::Ping() Failed - ICMP error"); return false; } // Parse the IP address in the Edit. size_t szNextDot = sServerIP.find (L'.'); int addr1 = ::_wtoi (sServerIP.substr (0, szNextDot++).c_str()); size_t szNextNum = szNextDot; szNextDot = sServerIP.find (L'.', szNextNum); int addr2 = ::_wtoi (sServerIP.substr (szNextNum, szNextDot++).c_str()); szNextNum = szNextDot; szNextDot = sServerIP.find (L'.', szNextNum); int addr3 = ::_wtoi (sServerIP.substr (szNextNum, szNextDot++).c_str()); szNextNum = szNextDot; szNextDot = sServerIP.find (L'.', szNextNum); int addr4 = ::_wtoi (sServerIP.substr (szNextNum, szNextDot).c_str()); // Make an int out of the IP address. int addr = MAKELONG( MAKEWORD(addr1, addr2), MAKEWORD(addr3, addr4)); // Allocate a buffer for the reply info. int size = sizeof(icmp_echo_reply) + 8; char* buff = new char[size]; bool bSuccess = false; // Send the echo request three times to // emulate what the PING program does. for (int i=0;i<3;i++) { // Call IcmpSendEcho(). DWORD res = IcmpSendEcho(hIcmp, addr, 0, 0, 0, buff, size, 1500); // Prepare to report the status. icmp_echo_reply reply; memcpy(&reply, buff, sizeof(reply)); if (!res) { //sServerIP += ErrorStrings[reply.Status - 11000]; _ASSERTE (0 && L" IGPing::Ping() Failed - ICMP error"); continue; } // If the status is non-zero then show the // corresponding error message from the // ErrorStrings array to the user. if (reply.Status > 0) {/* sServerIP += IGPING_ERROR; sServerIP += L" - "; sServerIP += ErrorStrings[reply.Status - 11000];*/ _ASSERTE (0 && L" IGPing::Ping() Failed - ICMP error"); continue; } else { // Build a string to report the results. /* std::string rtt = reply.RoundTripTime; std::string ttl = reply.Options.Ttl; std::string S = "Reply from " + IPEdit->Text + " time=" + rtt +"ms TTL=" + ttl + "ms";*/ bSuccess = true; break; } // Pause a second and then loop. Sleep(1000); } // Close the ICMP handle. IcmpCloseHandle(hIcmp); return bSuccess; }
int __cdecl main(int argc, char **argv) { // Declare and initialize variables HANDLE hIcmpFile; unsigned long ipaddr = INADDR_NONE; DWORD dwRetVal = 0; char SendData[32] = "Data Buffer"; LPVOID ReplyBuffer = NULL; DWORD ReplySize = 0; // Validate the parameters if (argc != 2) { printf("usage: %s IP address\n", argv[0]); return 1; } ipaddr = inet_addr(argv[1]); if (ipaddr == INADDR_NONE) { printf("usage: %s IP address\n", argv[0]); return 1; } hIcmpFile = IcmpCreateFile(); if (hIcmpFile == INVALID_HANDLE_VALUE) { printf("\tUnable to open handle.\n"); printf("IcmpCreatefile returned error: %ld\n", GetLastError() ); return 1; } ReplySize = sizeof(ICMP_ECHO_REPLY) + sizeof(SendData); ReplyBuffer = (VOID*) malloc(ReplySize); if (ReplyBuffer == NULL) { printf("\tUnable to allocate memory\n"); return 1; } dwRetVal = IcmpSendEcho(hIcmpFile, ipaddr, SendData, sizeof(SendData), NULL, ReplyBuffer, ReplySize, -1); if (dwRetVal != 0) { PICMP_ECHO_REPLY pEchoReply = (PICMP_ECHO_REPLY)ReplyBuffer; struct in_addr ReplyAddr; ReplyAddr.S_un.S_addr = pEchoReply->Address; printf("\tSent icmp message to %s\n", argv[1]); if (dwRetVal > 1) { printf("\tReceived %ld icmp message responses\n", dwRetVal); printf("\tInformation from the first response:\n"); } else { printf("\tReceived %ld icmp message response\n", dwRetVal); printf("\tInformation from this response:\n"); } printf("\t Received from %s\n", inet_ntoa( ReplyAddr ) ); printf("\t Status = %ld\n", pEchoReply->Status); printf("\t Roundtrip time = %ld milliseconds\n", pEchoReply->RoundTripTime); } else { printf("\tCall to IcmpSendEcho failed.\n"); printf("\tIcmpSendEcho returned error: %ld\n", GetLastError() ); return 1; } return 0; }
// Ping test BOOL PingTest(LPCWSTR strIpAddr, ICMP_ECHO_REPLY& reply) { CString strIP = strIpAddr; LPWSTR addr = strIP.GetBuffer(strIP.GetLength()); CHAR cIPString[128] = {'\0',}; WideCharToMultiByte(CP_ACP, 0, addr, -1, cIPString, sizeof(cIPString), NULL, NULL); IPAddr ipaddr; WSADATA wsadata; HANDLE hIcmp; BOOL bResult = FALSE; if(strlen(cIPString)) { // start winsock, requesting min version of 1.01 WSAStartup(0x0101, &wsadata ); //******************************************************************* // Now we ping the IP address resolved above //******************************************************************* // convert the IP char string to a IPAddr representation ipaddr = inet_addr((const char*)cIPString); if(ipaddr == INADDR_NONE) { AfxMessageBox(TEXT("Invalid Host or IP Entered")); WriteFileLog(1, _T("[PING] Invalid Host or IP Entered\r\n") ); } else { INT iPacketSize = 0; // ping test을 위한 핸들 생성 hIcmp = IcmpCreateFile(); if(hIcmp == INVALID_HANDLE_VALUE) { AfxMessageBox(TEXT("Could not create ICMP handle")); WriteFileLog(1, _T("[PING] Could not create ICMP handle\r\n") ); } else { LPVOID lpData = NULL; LPVOID lpRevBuffer = NULL; // determine the size of the data packet to send iPacketSize = 32; // allocate memory for the ping function call return and packet size lpData = LocalAlloc(LPTR, iPacketSize); lpRevBuffer = LocalAlloc(LPTR, sizeof(ICMP_ECHO_REPLY) * iPacketSize); if(lpData && lpRevBuffer) { // send the ping if( NULL == IcmpSendEcho( hIcmp, ipaddr, lpData, iPacketSize, NULL, lpRevBuffer, (sizeof(ICMP_ECHO_REPLY) * iPacketSize), 1000)) { // ping test 실패 bResult = FALSE; WriteFileLog(1, _T("[PING] IcmpSendEcho Failed(%d)\r\n"), GetLastError() ); } else { // ping test 성공 //&reply = (ICMP_ECHO_REPLY*)lpRevBuffer; memcpy(&reply, lpRevBuffer, sizeof(ICMP_ECHO_REPLY)); bResult = TRUE; } } free(lpData); free(lpRevBuffer); IcmpCloseHandle(hIcmp); } } WSACleanup(); } else { WriteFileLog(1, _T("[PING] Invalid IP Address\r\n") ); } return bResult; }
// // Purpose: // Sends an ICMP echo request to the IP address specified // // Parameters: // IP address // // Return value: // True if the information received from the first response // BOOL WINAPI Ping(char *ip) { // Declare and initialize variables HANDLE hIcmpFile; unsigned long ipaddr = INADDR_NONE; DWORD dwRetVal = 0; char SendData[32] = "Data Buffer"; LPVOID ReplyBuffer = NULL; DWORD ReplySize = 0; ipaddr = inet_addr(ip); if (ipaddr == INADDR_NONE) { //printf("usage: IP address\n"); return FALSE; } hIcmpFile = IcmpCreateFile(); if (hIcmpFile == INVALID_HANDLE_VALUE) { //printf("\tUnable to open handle.\n"); //printf("IcmpCreatefile returned error: %ld\n", GetLastError()); return FALSE; } ReplySize = sizeof(ICMP_ECHO_REPLY) + sizeof(SendData); ReplyBuffer = (VOID*)malloc(ReplySize); if (ReplyBuffer == NULL) { //printf("\tUnable to allocate memory\n"); return FALSE; } dwRetVal = IcmpSendEcho(hIcmpFile, ipaddr, SendData, sizeof(SendData), NULL, ReplyBuffer, ReplySize, 1000); if (dwRetVal != 0) { //PICMP_ECHO_REPLY pEchoReply = (PICMP_ECHO_REPLY)ReplyBuffer; //struct in_addr ReplyAddr; //ReplyAddr.S_un.S_addr = pEchoReply->Address; //printf("\tSent icmp message to %s\n", ip); //if (dwRetVal > 1) //{ // printf("\tReceived %ld icmp message responses\n", dwRetVal); // printf("\tInformation from the first response:\n"); //} //else //{ // printf("\tReceived %ld icmp message response\n", dwRetVal); // printf("\tInformation from this response:\n"); //} //printf("\t Received from %s\n", inet_ntoa(ReplyAddr)); //printf("\t Status = %ld\n", pEchoReply->Status); //printf("\t Roundtrip time = %ld milliseconds\n", pEchoReply->RoundTripTime); } else { //printf("\tCall to IcmpSendEcho failed.\n"); //printf("\tIcmpSendEcho returned error: %ld\n", GetLastError()); return FALSE; } return TRUE; }