Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <winsock2.h>
- #include <iphlpapi.h>
- #include <icmpapi.h>
- #include <stdio.h>
- #include <locale.h>
- #pragma comment(lib, "iphlpapi.lib")
- #pragma comment(lib, "ws2_32.lib")
- #pragma warning(disable : 4996)
- using namespace std;
- const int N = 512;
- const size_t timeout = 1000;
- int MinMaxMed(int* arr, int size, int flag)
- {
- if (flag == 1)
- {
- int min = timeout;
- for (int i = 0; i < size; i++)
- if (arr[i] < min)
- min = arr[i];
- return min;
- }
- else if (flag == 2)
- {
- int max = 0;
- for (int i = 0; i < size; i++)
- if (arr[i] > max)
- max = arr[i];
- return max;
- }
- else
- {
- int med = 0;
- for (int i = 0; i < size; i++)
- med += arr[i];
- med /= size;
- return med;
- }
- }
- int main()
- {
- setlocale (LC_ALL, "Russian")
- WORD ver = MAKEWORD(2, 2);
- WSADATA wsaData;
- int err = 0;
- if (err = WSAStartup(ver, &wsaData))
- cout << "Error while WSAStartup";
- HANDLE IcmpHandle;
- char ReqData[N];
- LPVOID ReplyBuffer;
- WORD ReplySize;
- char HostName[N];
- unsigned long HostAddr;
- DWORD dwRetVal;
- int TrCount = 0;
- int* RecTimeArr;
- cout << "Введите адрес:\n";
- cin >> HostName;
- cout << "Введите количество попыток:\n";
- cin >> TrCount;
- cout << "Введите сообщение:\n";
- cin >> ReqData;
- RecTimeArr = new int[TrCount] {};
- ReplySize = sizeof(ICMP_ECHO_REPLY) + sizeof(ReqData) + 8;
- ReplyBuffer = (VOID*)malloc(ReplySize);
- if (ReplyBuffer == NULL)
- {
- cout << "Невозможно выделить память\n";
- return 1;
- }
- IcmpHandle = IcmpCreateFile();
- if (IcmpHandle == INVALID_HANDLE_VALUE)
- {
- cout << "Ошибка при открытии \n";
- return 1;
- }
- struct hostent* host = gethostbyname(HostName);
- if (host == NULL)
- {
- cout << "Can't get host by name\n";
- return 1;
- }
- HostAddr = inet_addr(inet_ntoa(*((in_addr*)host->h_addr_list[0])));
- for (int i = TrCount; i > 0; i--)
- {
- dwRetVal = IcmpSendEcho(IcmpHandle, HostAddr, ReqData, sizeof(ReqData), NULL, ReplyBuffer, ReplySize, 1000);
- if (dwRetVal)
- {
- PICMP_ECHO_REPLY pEchoReply = (PICMP_ECHO_REPLY)ReplyBuffer;
- struct in_addr ReplyAddr;
- ReplyAddr.S_un.S_addr = pEchoReply->Address;
- if (i == 1)
- cout << "Received " << dwRetVal << " icmp message from " << inet_ntoa(ReplyAddr) << " time: " << pEchoReply->RoundTripTime << " ms\n";
- else
- cout << "Received " << dwRetVal << " icmp messages from " << inet_ntoa(ReplyAddr) << " time: " << pEchoReply->RoundTripTime << " ms\n";
- RecTimeArr[TrCount - i] = pEchoReply->RoundTripTime;
- }
- else
- {
- cout << "Call to IcmpSendEcho failed.\n";
- }
- }
- if (RecTimeArr[0] != 0)
- cout << "min - " << MinMaxMed(RecTimeArr, TrCount, 1) << " ms, max - " << MinMaxMed(RecTimeArr, TrCount, 2) << " ms, med - " << MinMaxMed(RecTimeArr, TrCount, 3) << " ms\n";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement