#include <string.h>
#include <winsock.h>
#include <windows.h>
#include <iostream.h>
#pragma comment(lib,"ws2_32.lib")
int main(int argc, char *argv[])
{
cout<<"**************************************************"<<endl
<<"单线程端口扫描器"<<endl<<endl
<<"作者:东方"<<endl
<<"**************************************************"<<endl;
int portStart=1,portEnd=65535;
int mysocket;
int portCount = 0;
struct sockaddr_in my_addr;
WSADATA wsaData;
WORD wVersionRequested=MAKEWORD(1,1);//设置最低版本号
if(argc < 2)
{
cout<<"usage:"<<argv[0]<<" host portstart portend\n"<<endl;
exit(1);
}
if (portStart>portEnd)
cout<<"错误!开始端口号必须小于结束端口号"<<endl;
else
{
if (WSAStartup(wVersionRequested , &wsaData))
{
cout<<"连接socket库失败,请检查版本号是否为1.1\n"<<endl;
exit(1);
}
portStart=atoi(argv[2]);
portEnd=atoi(argv[3]);
lable: for(int i=portStart; i < portEnd; i++)
{ //atoi()将字符串转换为数字
cout<<"正在建立socket........................."<<endl;
if((mysocket = socket(AF_INET, SOCK_STREAM,0)) == INVALID_SOCKET)
{
cout<<"Socket建立失败"<<endl;
goto lable;
}
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(i); //将端口转化
my_addr.sin_addr.s_addr = inet_addr(argv[1]); //htonl(INADDR_ANY)将本机所有IP付给
cout<<"正在扫描端口:"<<i<<endl;
if(connect(mysocket, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == SOCKET_ERROR)
{
cout<<"端口"<<i<<"关闭!"<<endl;
closesocket(mysocket);
}
else
{
portCount++;
cout<<"端口"<<i<<"开放\n"<<endl;
}
}
cout<<"目标主机"<<argv[1]<<"从"<<portStart<<"--"<<portEnd<<"共有"<<portCount<<"个端口开放"<<endl;
closesocket(mysocket);
WSACleanup(); //in order to allow the WS2_32.DLL to free any resources for the application
}
return 0;
}