C++端口扫描程序
C++ Port Scanner
我正在尝试用c ++进行端口扫描,以便我可以从网络中打开了某个端口的某些设备获取IP地址。我实现了超时,因为当我测试网络中的每个 IP 地址时,如果我没有得到响应,它会自动关闭连接。
如果我把这个超时放在大约 30 u秒,它只会检测到所有关闭的设备,如果我放一个更大的值,它会挂起并且永远不会完成。
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <string>
using namespace std;
static bool port_is_open(string ip, int port){
struct sockaddr_in address; /* the libc network address data structure */
short int sock = -1; /* file descriptor for the network socket */
fd_set fdset;
struct timeval tv;
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(ip.c_str()); /* assign the address */
address.sin_port = htons(port);
/* translate int2port num */
sock = socket(AF_INET, SOCK_STREAM, 0);
fcntl(sock, F_SETFL, O_NONBLOCK);
connect(sock, (struct sockaddr *)&address, sizeof(address));
FD_ZERO(&fdset);
FD_SET(sock, &fdset);
tv.tv_sec = 0; /* timeout */
tv.tv_usec = 50;
if (select(sock + 1, NULL, &fdset, NULL, &tv) == 1)
{
int so_error;
socklen_t len = sizeof so_error;
getsockopt(sock, SOL_SOCKET, SO_ERROR, &so_error, &len);
if (so_error == 0){
close(sock);
return true;
}else{
close(sock);
return false;
}
}
return false;
}
int main(int argc, char **argv){
int i=1;
int port = 22;
while (i<255) {
string ip = "10.0.60.";
std::string host = std::to_string(i);
ip.append(host);
if (port_is_open(ip, port)){
printf("%s:%d is openn", ip.c_str(), port);
}
i++;
}
return 0;
}
您可以将逻辑包装成异步调用,并以合理的超时并行启动(例如 10 秒,因为 30us 在标准条件下毫无意义)。线程将使程序加速大约 255 倍,在最坏的情况下,在此超时发生后,它将完成:
...
#include <iostream>
#include <thread>
#include <vector>
#include <sstream>
...
void task(std::string ip, int port){
if (port_is_open(ip, port))
cout << ip << ":" << port << " is openn";
}
int main(int argc, char **argv){
const std::string ip_prefix = "10.0.60.";
const int port = 22;
std::vector<std::thread *> tasks;
for (int i=0; i<255; i++){
std::ostringstream ip;
ip << ip_prefix << i;
tasks.push_back(new std::thread(task, ip.str(), port));
}
for (int i=0; i<255; i++){
tasks[i]->join();
delete tasks[i];
}
return 0;
}
您可能希望像这样编译它:g++ -std=c++11
或g++ -std=c++0x -pthread
(对于较旧的 GCC)。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- C++,系统无法执行指定的程序
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 重载操作程序时出错>>用于类中的字符串 memebr
- C++客户端/服务器聊天应用程序 - 从 Ubuntu 命令窗口扫描输入
- 我可以在我的 cmake 代码中手动使用 CMake 的 cpp 文件依赖项扫描程序吗?
- C++ 签名扫描程序输出错误
- 扫描头文件并报告可用代码的程序
- 控制台中的C++签名扫描程序
- C++端口扫描程序
- 强制无线网卡只扫描一个通道(以程序方式)
- 使用哪个库来创建简单的端口扫描程序
- 如何加快我的内存扫描程序
- 调试断言失败文件、令牌扫描程序和文本文件
- 扫描程序等待另一个类似的程序
- 发送扫描码到我的应用程序
- 扫描参数并用c++程序确定它们是什么
- 启动多个程序扫描计算机以查找恶意软件