C + + scan specified host open port, OS provides a connect () system call, used to establish a connection with a remote host port, if the port is in the frame listening state of the remote host, connect () connection is successful; otherwise, the port is closed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
// ScanPorts.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include<iostream> Using namespace std; #include<WinSock2.h> #pragma comment (lib,"ws2_32.lib") #define STATUS_FALIED 0xFFFF Unsigned long serverIP; Long MaxThread = 200; Long ThreadCount = 0; Long *aa = &ThreadCount; // Scan port threads DWORD WINAPI ScanPort(LPVOID lpParam){ Short Port = *(short*)lpParam; InterlockedIncrement(aa); // Create streaming socket SOCKET sock = socket(AF_INET, SOCK_STREAM,0); If (sock == INVALID_SOCKET){ Cout << "Failed to create a socket!" << endl; Return 0; } Else{ // Fill in the server address Sockaddr_in severAddr; severAddr.sin_family = AF_INET; severAddr.sin_port = htons(Port); severAddr.sin_addr.S_un.S_addr = serverIP; // Determine if this machine is turned on Connect(sock, (sockaddr*)&severAddr, sizeof(severAddr)); Struct fd_set write; FD_ZERO(&write); FD_SET(sock, &write); // initialization timeout Struct timeval timeout; Timeout.tv_sec = 100 / 1000; Timeout.tv_usec = 0; If (select(0,NULL,&write,NULL,&timeout)>0) { Cout << Port <<","; }; Closesocket(sock); } InterlockedDecrement(aa); Return 0; } Void main(int argc, char *argv[]) { If (argc != 2){ Cout << "Please enter the destination host IP address" << endl; } // Establish binding with socket library WSADATA WSAData; If (WSAStartup(MAKEWORD(2, 2), &WSAData) != 0) { Cout << "WSAStartup falied!" << GetLastError() << endl; ExitProcess(STATUS_FALIED); } serverIP = inet_addr(argv[1]); Cout << "The following ports are open:" << endl; For (int i = 1; i < 1024; i++){ // exceed the maximum allowable number of threads waiting While (ThreadCount >= MaxThread) Sleep(10); //Create thread, scan port DWORD ThreadID; CreateThread(NULL, 0, ScanPort, (LPVOID)new short(i), 0, &ThreadID); } //There are still threads that are not finished waiting While (ThreadCount>0) Sleep(50); WSACleanup(); } |
This article has been printed on copyright and is protected by copyright laws. It must not be reproduced without permission.If you need to reprint, please contact the author or visit the copyright to obtain the authorization. If you feel that this article is useful to you, you can click the "Sponsoring Author" below to call the author!
Reprinted Note Source: Baiyuan's Blog>>https://wangbaiyuan.cn/en/c-scan-specified-host-open-port-2.html
No Comment