EDIT: Sorry that the code isn't indented or anything, it was when I posted it. I tried the "Attach Code" button but it gave me an error every time I tried to attach code.
Code:
tags didn't work either. Is there something I should be using?
Ok, so my first post somehow didn't post. This is the short version. I have to write a port scanner for class. Very basic. I am a Java programmer but this has to be in C++ and I am new to socket programming to forgive me if the answer is simple. After reading Beej's Guide I came up with this:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <arpa/inet.h>
int status;
int i;
int s;
int c;
int j;
struct sockaddr_in ip4addr;
char Str[16];
int main(int argc, char *argv[])
{
for(i = 1; i<=65535; i++)
{
ip4addr.sin_family = AF_INET;
ip4addr.sin_port = htons(i);
inet_pton(AF_INET, "131.204.36.98", &ip4addr.sin_addr);
if ((s = socket(PF_INET, SOCK_STREAM, 0)) == -1)
{
//printf("Error creating socket");
}
else
{
//Set Non-blocking
int opts;
opts = fcntl(s, F_GETFL);
if (1==1) opts = (opts | O_NONBLOCK);
else opts = (opts & ~O_NONBLOCK);
fcntl(s, F_SETFL, opts);
for(j = 0; j<1000; j++)
{
if ((c = connect(s, (struct sockaddr*)&ip4addr, sizeof ip4addr)) == -1)
{
//if(j==9999){printf("closed: %d\n", i);}
}
else
{
printf("open: %d\n", i);
break;
}
}
}
}
}
The non-blocking section was causing it not to catch open ports hence the loop. This scanner runs fast but is only roughly 97% accurate (sometimes it misses ports). So I did some more reading and looking and came up with this:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <arpa/inet.h>
#include <unistd.h>
int status;
int i;
int s;
int c;
int j;
struct sockaddr_in ip4addr;
struct hostent *hostaddr;
int main(int argc, char *argv[])
{
for(i = 1; i<=65535; i++)
{
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
memset( &ip4addr, 0, sizeof(ip4addr));
ip4addr.sin_family = AF_INET;
ip4addr.sin_port = htons(i);
inet_pton(AF_INET, "131.204.2.251", &ip4addr.sin_addr);
if ((c = connect(s, (struct sockaddr*)&ip4addr, sizeof ip4addr)) != -1)
{
printf("open: %d\n", i);
}
close(s);
}
}
This one is 100% solid, but oh my GOSH is it slow. What the heck do I need to do to speed up the second version? Any help is greatly appreciated. Thank you all in advance.