c++多线程Ping代码
时间: 2023-11-20 16:40:52 浏览: 139
多线程ping
4星 · 用户满意度95%
当然!以下是一个使用C++多线程编写的简单Ping代码示例:
```cpp
#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
#else
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#endif
std::atomic<bool> running(true);
void ping(const std::string& ip, int timeout) {
while (running) {
#ifdef _WIN32
SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == INVALID_SOCKET) {
std::cerr << "Failed to create socket" << std::endl;
return;
}
sockaddr_in serverAddr{};
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(80);
inet_pton(AF_INET, ip.c_str(), &(serverAddr.sin_addr));
if (connect(sock, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) != 0) {
std::cout << ip << " is down" << std::endl;
} else {
std::cout << ip << " is up" << std::endl;
}
closesocket(sock);
#else
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
std::cerr << "Failed to create socket" << std::endl;
return;
}
sockaddr_in serverAddr{};
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(80);
inet_pton(AF_INET, ip.c_str(), &(serverAddr.sin_addr));
if (connect(sock, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) != 0) {
std::cout << ip << " is down" << std::endl;
} else {
std::cout << ip << " is up" << std::endl;
}
close(sock);
#endif
std::this_thread::sleep_for(std::chrono::milliseconds(timeout));
}
}
int main() {
std::string ip;
int timeout;
std::cout << "Enter IP address to ping: ";
std::cin >> ip;
std::cout << "Enter timeout (in milliseconds): ";
std::cin >> timeout;
std::thread pingThread(ping, ip, timeout);
// Wait for user input to stop the ping thread
std::cin.ignore();
running = false;
pingThread.join();
return 0;
}
```
这段代码使用了sockets来实现Ping功能。它创建一个线程来定期尝试连接到指定的IP地址,并根据连接结果输出相应的信息。
请注意,此代码在Windows和Linux上都可以编译运行。在Windows上,它使用了Winsock库;在Linux上,它使用了socket库。因此,根据不同的操作系统,你可能需要进行一些调整和适配。
希望这个示例对你有所帮助!如果你有任何疑问,请随时提问。
阅读全文