C端口扫描


#include <stdio.h> 
#include <winsock.h> 
#define NETWORK_ERROR -1 
#define NETWORK_OK 0 
#define PORT_MIN 1 
#define PORT_MAX 65535 

HANDLE hThread;
DWORD hID;

char hostname[30];

int starting_port = 0;
int ending_port = 0;
int nopen = 0;

DWORD portscan();

int main()
{
    int ret;

    WSADATA dat;
    DWORD version;

    version = MAKEWORD(2, 2);

    ret = WSAStartup(version, &dat);

    if (ret != 0)
    {
        printf("Error initializing Winsock.\n");
        WSACleanup();
        return NETWORK_ERROR;
    }
    if (ret == 0)
    {

        printf("Enter hostname:");
        scanf("%s", hostname);

        printf("Enter starting port:");
        scanf("%d", &starting_port);

        if (starting_port < PORT_MIN)
        {
            printf("Invalid port number.\n");
            WSACleanup();
            return NETWORK_ERROR;
        }

        printf("Enter ending port:");
        scanf("%d", &ending_port);

        if (ending_port > PORT_MAX)
        {
            printf("Invalid port number.\n");
            WSACleanup();
            return NETWORK_ERROR;
        }

        printf("\nScanning [%s]...\n", hostname);

        hThread = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)portscan, 0, 0,
            &hID);

        if (hThread == 0)
        {
            printf("Failed to create thread.\n");
            WSACleanup();
            return NETWORK_ERROR;
        }
        Sleep( - 1);
    }
    WSACleanup();
    return NETWORK_OK;
}

DWORD portscan()
{
    int i, nret;

    SOCKET thesocket;
    LPHOSTENT hostent;

    thesocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    hostent = gethostbyname((hostname));

    for (i = starting_port; i < ending_port + 1; ++i)
    {

        SOCKADDR_IN hostinfo;

        hostinfo.sin_family = AF_INET;
        hostinfo.sin_addr = *((LPIN_ADDR) *hostent->h_addr_list);
        hostinfo.sin_port = htons(i);

        nret = connect(thesocket, (LPSOCKADDR) &hostinfo, sizeof(hostinfo));

        if (nret == 0)
        {
            printf("\n\t%d\n", i);
            ++nopen;
        }
    }

    printf("\nScan complete.\n\n");
    printf("Number of ports opened = %d\n", nopen);

    closesocket(thesocket);
    return 0;
}








你可能感兴趣的:(端口)