Hello,
Im trying to developing a simple portscan, but I m getting an error in the connect() function. connect() is returning -1 and I have no idea why and how to solve.
Error SS:
Before the connect() function, I have debugged and it is ok.
The code:
Code:
#include <stdlib.h> // atoi()
#include <stdio.h> // I/O
#include <winsock2.h> // winsock 2.0
#include <ws2tcpip.h>
#define INITIAL_PORT 1
#define FINAL_PORT 65535
int main(int argc, char* argv[])
{
int ports, // represents the analised port
initialPort, // initial port of scanning
finalPort, // final port of scanning
mySocket, // socket used for analysis of ports
returnConnect;
WSADATA wsaData;
struct sockaddr_in target;
struct hostent *host;
struct servent *service;
WSAStartup(MAKEWORD(2,2),&wsaData);
if(argc == 1)
{
printf("\n ********************************************************************\n");
printf(" ** ScanPort v1.0 (English Version) **\n");
printf(" ** Developed by Insurgente **\n");
printf(" ** USE <%s> <target> <initial-port> <final-port> **\n",argv[0]);
printf(" ********************************************************************\n");
return 0;
}
if(argc == 2)
{
initialPort = INITIAL_PORT;
finalPort = FINAL_PORT;
}
if(argc > 2)
{
initialPort = atoi(argv[2]);
finalPort = atoi(argv[3]);
}
printf("\n Scanning Ports from <%d> to <%d> in <%s>:\n",initialPort,finalPort,argv[1]);
for(ports = initialPort; ports < finalPort; ports++)
{
host = gethostbyname(argv[1]);
if (host == NULL)
{
printf("\nCant find Host\n");
return 1;
}
// Created to analyze the socket port
mySocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(mySocket < 0)
{
printf("\n\nError creating socket\n\n");
return 1;
}
target.sin_family = host->h_addrtype; // address type returned
target.sin_port = htons(ports); // receive the analysed port
target.sin_addr = *((struct in_addr*)host->h_addr); //inet_addr("l0.0.2.15");
memset(&target.sin_zero,0,sizeof(target.sin_zero));
returnConnect = connect(mySocket,(struct sockaddr*)&target,sizeof(target));
if(returnConnect == 0)
{
printf("\nIF CONNECT()\n");
service = getservbyport(htons(ports),"TCP");
printf("\nPort [%d] is open. Service: [%s]",ports,(service == NULL?"Unknown":service->s_name));
closesocket(mySocket);
}
else // if returnConnect == -1 then error
{
printf("\nELSE CONNECT()\n Error: %d,\n WSAGetLastError: %d",returnConnect,WSAGetLastError());
closesocket(mySocket); // if dont can to connect in port, closes the socket
}
}
}
If someone can help me, I thank.
Sorry for my bad english