c++实现多线程ping代码
时间: 2023-07-29 14:06:33 浏览: 213
以下是用C++实现多线程Ping的示例代码:
```cpp
#include <iostream>
#include <thread>
#include <vector>
#include <chrono>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <string>
#ifdef _WIN32
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#else
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#endif
std::mutex mtx;
std::condition_variable cv;
std::atomic<int> activeThreads(0);
void pingHost(const std::string& ip) {
// 创建套接字
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
std::lock_guard<std::mutex> lock(mtx);
std::cout << "Failed to create socket for " << ip << std::endl;
return;
}
// 设置超时时间为1秒
struct timeval timeout;
timeout.tv_sec = 1;
timeout.tv_usec = 0;
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout));
// 设置服务器地址和端口
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(80);
if (inet_pton(AF_INET, ip.c_str(), &(server.sin_addr)) <= 0) {
std::lock_guard<std::mutex> lock(mtx);
std::cout << "Invalid address: " << ip << std::endl;
return;
}
// 连接到服务器
if (connect(sock, (struct sockaddr*)&server, sizeof(server)) < 0) {
std::lock_guard<std::mutex> lock(mtx);
std::cout << "Failed to connect to " << ip << std::endl;
return;
}
std::lock_guard<std::mutex> lock(mtx);
std::cout << "Ping successful to " << ip << std::endl;
#ifdef _WIN32
closesocket(sock);
#else
close(sock);
#endif
}
int main() {
#ifdef _WIN32
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cerr << "Failed to initialize Winsock" << std::endl;
return 1;
}
#endif
std::vector<std::string> hosts = { "127.0.0.1", "192.168.0.1", "8.8.8.8" };
std::vector<std::thread> threads;
for (const auto& host : hosts) {
threads.emplace_back([&]() {
pingHost(host);
activeThreads--;
cv.notify_one();
});
activeThreads++;
}
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [&]() { return activeThreads == 0; });
#ifdef _WIN32
WSACleanup();
#endif
return 0;
}
```
上述代码使用了C++的线程库std::thread来创建多个线程,每个线程执行pingHost函数来执行Ping操作。通过互斥锁std::mutex和条件变量std::condition_variable来实现线程同步和等待所有线程完成的功能。
注意:上述代码在Windows平台下使用了Winsock库进行套接字操作,而在其他平台下使用了标准的POSIX套接字操作。请根据实际平台进行适配或修改。
阅读全文