This is just a basic TCP Port scanner that returns a list of the ports and whether or not they are open. It should run on any *nix system. Due to adding the import "sys/types.h", it will also run on legacy BSD systems which don't include the needed definitions in "sys/socket.h". It takes the IP to be scanned as the only argument when run from the command line.
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
int main(int argc, const char * argv[])
{
int s, port;
struct hostent *hostaddr;
struct sockaddr_in servaddr;
servaddr.sin_family = AF_INET;
hostaddr = gethostbyname(argv[1]);
for (port=0; port<=65535; port++)
{
s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
servaddr.sin_port = htons(port);
if(connect(s, (struct sockaddr *) &servaddr, sizeof(servaddr)) == -1)
printf("Port %d is closed\n", port);
else
printf("Port %d is open\n",port);
close(s);
}
return 0;
}
I compiled it with gcc 4.2.1 and tested it on a mac.