IP地址扫描C++实现
时间: 2024-01-10 15:19:42 浏览: 50
以下是使用C++实现IP地址扫描的示例代码:
```c++
#include <iostream>
#include <string>
#include <vector>
#include <thread>
#include <mutex>
#include <chrono>
#include <atomic>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;
mutex mtx;
atomic<int> cnt(0);
void scan_ip(const string& ip, int port) {
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("socket");
return;
}
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr(ip.c_str());
if (connect(sockfd, (struct sockaddr*)&addr, sizeof(addr)) == 0) {
mtx.lock();
cout << ip << ":" << port << " is open" << endl;
mtx.unlock();
}
close(sockfd);
cnt++;
}
void scan_ips(const string& prefix, int start, int end, int port) {
for (int i = start; i <= end; i++) {
string ip = prefix + to_string(i);
thread t(scan_ip, ip, port);
t.detach();
}
}
int main(int argc, char* argv[]) {
if (argc != 4) {
cout << "Usage: " << argv[0] << " <prefix> <start> <end>" << endl;
return 0;
}
string prefix = argv[1];
int start = atoi(argv[2]);
int end = atoi(argv[3]);
int port = 80;
auto start_time = chrono::steady_clock::now();
scan_ips(prefix, start, end, port);
while (cnt < (end - start + 1)) {
this_thread::sleep_for(chrono::milliseconds(100));
}
auto end_time = chrono::steady_clock::now();
auto elapsed_time = chrono::duration_cast<chrono::milliseconds>(end_time - start_time).count();
cout << "Scan completed in " << elapsed_time << "ms" << endl;
return 0;
}
```
该示例代码使用了C++的标准库和POSIX socket API,实现了一个简单的IP地址扫描器。用户可以通过命令行参数指定要扫描的IP地址范围和端口号,程序将会并发地扫描指定范围内的所有IP地址和指定端口,输出开放的端口号。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)