扫描给定范围端口是否开放


#include 
#include 
#include 
#include 
#pragma comment(lib,"ws2_32.lib")
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
   int m,n;
    //初始化Windows Sockets 动态库
    WSADATA wsaData;
    if(WSAStartup(MAKEWORD(2,2),&wsaData)!=0)
    {
        cout<<"找不到可使用的WinSock dll!"<return 1;
    }
    SOCKET sClient = NULL;
    SOCKADDR_IN addrServ;
    addrServ.sin_family=AF_INET;
    addrServ.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
    printf("请输入要扫描的端口范围(例如1-1024):");
    scanf("%d-%d",&m,&n);
    if(m > n)
        printf("输入错误请重新输入!");
    for (int _port = m;_port<=n;_port++){
        if (sClient == NULL)
        {
            //创建套接字
            sClient=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
            if(sClient==INVALID_SOCKET)
            {
                cout<<"创建客户端socket失败!"<return 1;
            }
        }
    addrServ.sin_port=htons(_port);
    //连接服务器
    if(connect(sClient,(sockaddr *)&addrServ,sizeof(sockaddr))==SOCKET_ERROR)
    {
        cout<<"port "<<_port<<" is not open!"<//closesocket(sClient);
        //return 1;
    }
    else{
        cout<<"port "<<_port<<" open on host!!!!!!!!!!!!"<//关闭套接字,释放资源
    getchar();
    WSACleanup();
    return 0;
}

你可能感兴趣的:(扫描给定范围端口是否开放)