Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/articles/c-tutorials/)
-   -   Port scanner in C (http://www.go4expert.com/articles/port-scanner-c-t11233/)

shukad33 9Jun2008 16:37

Port scanner in C
 
Port scanner in C
Code: C

#include<stdio.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<stdlib.h>
#include<netdb.h>
int main(int argc,char **argv)
{
    int i,err,net;
    struct hostent *host;
    struct sockaddr_in sa;
    if(argc!=2)
    {
        printf("Error...Usage :%s ip-address",argv[0]);
        exit(0);
    }
    for(i=1;i<20000;i++)
    {
        sa.sin_family=AF_INET;
        sa.sin_port=htons(i);
        sa.sin_addr.s_addr=inet_addr(argv[1]);
        net=socket(AF_INET,SOCK_STREAM,0);
        err=connect(net,(struct sockaddr_in *)&sa,sizeof(sa));
        if(err>=0)
        {
            printf("\n%d is open",i);
        }
    }
    printf("\n");
 }


shabbir 9Jun2008 17:10

Re: Port scanner in C
 
Can you explain how do I get the following header files. sys/socket.h

madlex 9Jun2008 18:48

Re: Port scanner in C
 
You are opening 20000 connections and you are closing none of them.
You should close connections in your for.

Code:

if(err>=0)
        {
            printf("\n%d is open",i);
        }

This is wrong. Values over zero may express an error, not a succesful connection.
You should really interpret this values and the print a correct output.
(hint: will return 0 on success).

You didn't specify the platform. For windows platform is necesary to call WSAStartup, to initialize the winsock library, otherwise you will receive errors from each call made to winsock's API.

shukad33 10Jun2008 19:05

Re: Port scanner in C
 
Quote:

Originally Posted by shabbir
Can you explain how do I get the following header files. sys/socket.h

Its a unix platform supported program. Hence it is assumed to be available in UNIX...


All times are GMT +5.5. The time now is 03:43.