#include <stdio.h>
#include <string.h>
#include <iostream>
#include <winsock2.h>
using namespace std;
#pragma comment (lib, "ws2_32")
class CInitSock
{
public:
CInitSock(int version01 = 2, int version02 = 2)
{
WSADATA wsaData = {0};
WORD version = 0;
version = MAKEWORD(version01, version02);
if (WSAStartup(version, &wsaData) != 0)
{
cout << "Initlization failed....." << endl;
exit(0);
}
}
~CInitSock()
{
WSACleanup();
}
};
void ScanPort01(char* strIP);
void ScanPort02(char* strIP, char* strStartPort, char * strEndPort);
void Help(void);
int const MAX_LEN = 18;
CInitSock mysock;
int main(int argc, char* argv[])
{
if (argc != 2 && argc != 4)
{
Help();
return 0;
}
else if (argc == 2)
{
ScanPort01(argv[1]);
}
else if (argc == 4)
{
ScanPort02(argv[1], argv[2], argv[3]);
}
return 0;
}
void Help(void)
{
cout << "=================================================================" << endl;
cout << "/t This program need argv[n]" << endl;
cout << "/t Linke ScanPort IP" << endl;
cout << "/t ScanProt IP StartPort EndPort" << endl;
cout << "/t If you still have some problem." << endl;
cout << "/t Please send email to andylin02@126.com" << endl;
cout << "=================================================================" << endl;
cout << endl;
}
void ScanPort01(char* strIP)
{
int i = 0;
SOCKET sock = 0;
sockaddr_in sin = {0};
int nPort[MAX_LEN] = {21, 22, 23, 25, 53, 79, 80, 110, 111, 135, 139, 443, 554, 1433, 1521, 3306, 3389};
for (i = 0; i < MAX_LEN; i++)
{
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
{
cout << "create socket failed!" << endl;
exit(0);
}
sin.sin_family = AF_INET;
sin.sin_addr.S_un.S_addr = inet_addr(strIP);
sin.sin_port = htons(nPort[i]);
if (connect(sock, (sockaddr*)&sin, sizeof(sin)) != SOCKET_ERROR)
{
cout << nPort[i] << " /tport is open " << endl;
closesocket(sock);
}
else
{
cout << nPort[i] << " /tport is closed " << endl;
closesocket(sock);
}
}
}
void ScanPort02(char* strIP, char* strStartPort, char* strEndPort)
{
int i = 0;
SOCKET sock = 0;
sockaddr_in sin = {0};
int nStartPort = 0;
int nEndPort = 0;
nStartPort = atoi(strStartPort);
nEndPort = atoi(strEndPort);
//check for the net work
if ( (sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET )
{
cout << "create socket failed!" << endl;
exit(0);
}
closesocket(sock);
for (i = nStartPort; i < nEndPort; i++)
{
if ( (sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET )
{
cout << "create socket failed!" << endl;
exit(0);
}
sin.sin_family = AF_INET;
sin.sin_addr.S_un.S_addr = inet_addr(strIP);
sin.sin_port = htons(i);
if (connect(sock, (sockaddr*)&sin, sizeof(sin)) != SOCKET_ERROR)
{
cout << i << " /tport is open!" << endl;
closesocket(sock);
}
else
{
closesocket(sock);
}
}
}