-
Notifications
You must be signed in to change notification settings - Fork 0
/
scan.c
86 lines (76 loc) · 2 KB
/
scan.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include<stdio.h>
#include<sys/socket.h>
#include<errno.h>
#include<netdb.h>
#include<string.h>
#include<stdlib.h>
int main(int argc , char **argv)
{
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 : ");
gets(hostname);
//Get start port number
printf("\nEnter start port number : ");
scanf("%d" , &start);
//Get end port number
printf("Enter end port number : ");
scanf("%d" , &end);
//Initialise the sockaddr_in structure
strncpy((char*)&sa , "" , sizeof sa);
sa.sin_family = AF_INET;
//direct ip address, use it
if(isdigit(hostname[0]))
{
printf("Doing inet_addr...");
sa.sin_addr.s_addr = inet_addr(hostname);
printf("Done\n");
}
//Resolve hostname to ip address
else if( (host = gethostbyname(hostname)) != 0)
{
printf("Doing gethostbyname...");
strncpy((char*)&sa.sin_addr , (char*)host->h_addr , sizeof sa.sin_addr);
printf("Done\n");
}
else
{
herror(hostname);
exit(2);
}
//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 created fine 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);
return(0);
}