I'm writing a port scanner with the intent to loop through an entire subnet to see if port 445 is open on any of the hosts as a way to learn C programming. The way that this program is currently setup, one needs to manually enter in a single IP address, and the scanner fires off. It is working perfectly (finally).
The current issue I'm facing: I'm not sure how to approach making this program scan an entire subnet, rather than just a single host. After researching this question, I believe the best route to pursue would be stripping off the last octet of the IP address, and having it loop from 1-254. However, I'm not entirely sure how to begin approaching this issue. This is my current code (heavily commented for clarification):
...
void portScan() {
struct hostent *host;
int err, i , sock ,start , end;
char hostname[100];
struct sockaddr_in sa;
//Get the hostname to scan
printf("Enter hostname or IP to scan: ");
gets(hostname);
//Get start port number
start = 445;
//Get end port number
end = 445;
//Initialise the sockaddr_in structure
strncpy((char*)&sa , "" , sizeof sa);
sa.sin_family = AF_INET;
//direct ip address, use it
if(isdigit(hostname[0])) {
sa.sin_addr.s_addr = inet_addr(hostname);
}
//Start the port scan loop
printf("Starting the portscan loop : \n");
for( i = start ; i <= end ; i++) {
//Fill in the port number
sa.sin_port = htons(i);
//Create a socket of type internet
sock = socket(AF_INET , SOCK_STREAM , 0);
//Check whether socket was created or not
if(sock < 0) {
perror("\nSocket");
exit(1);
}
//Connect using that socket and sockaddr structure
err = connect(sock , (struct sockaddr*)&sa , sizeof sa);
//not connected
if(err < 0) {
//printf("%s %-5d %s\r" , hostname , i, strerror(errno));
fflush(stdout);
}
//connected
else {
printf("%-5d open\n", i);
}
close(sock);
}
printf("\r");
fflush(stdout);
}
TL;DR: I'm not sure how to approach modifying this code to strip the last octet of the IP address, and loop through the subnet by replacing the last octet with a 1 - 254. Any feedback, ideas or help is highly appreciated! Still highly junior in the C world.