Port scanner in C

shukad33's Avatar author of Port scanner in C
This is an article on Port scanner in C 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's Avatar, Join Date: Jul 2004
Go4Expert Founder
Can you explain how do I get the following header files. sys/socket.h
madlex's Avatar, Join Date: Jun 2008
Go4Expert Member
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's Avatar, Join Date: Jun 2008
Newbie Member
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...