forked from abhn/tcp-port-scanner-c
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscanner.c
93 lines (74 loc) · 1.93 KB
/
scanner.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
87
88
89
90
91
92
93
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
void scanner(int port, char host[]);
int main(int argc, char **argv) {
char host[100];
char *p;
int ports[10];
int i = 0;
int var;
char tok[] = " ,";
if (argc < 2) {
fprintf(stderr,"[+]usage: %s <hostname> <port,port,port...>\n", argv[0]);
exit(0);
}
p = strtok(argv[2], tok);
strcpy(host, argv[1]);
while(p != NULL) {
sscanf(p, "%d", &var);
ports[i++] = var;
p = strtok(NULL, tok);
}
for(i=0; i<(sizeof(ports)/sizeof(ports[0]); i++) {
fprintf(stdout, "\n[+]Testing port: %d\n", ports[i]);
scanner(ports[i], host);
}
return 0;
}
void scanner(int port, char host[]) {
int sock, n;
struct hostent *server;
struct sockaddr_in serv_addr;
char buffer[4096];
server = gethostbyname(host);
sock = socket(AF_INET, SOCK_STREAM, 0);
/* Edit the params of socket to scan UDP ports,
* should be pretty straight forward I suppose.
*/
if(sock < 0) {
fprintf(stderr, "[-]Error creating socket");
return;
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
// AF_UNIX for Unix style socket
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(port);
n = connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
sleep(2);
if(n < 0) {
fprintf(stderr, "[-]Error Connecting to port\n");
return;
}
memset(buffer, 0, sizeof(buffer));
strcpy(buffer, "garbage\r\n");
n = write(sock, buffer, strlen(buffer));
if(n < 0) {
fprintf(stderr, "[-]Error writing (Port closed maybe?!)\n");
return;
}
bzero(buffer, 4096);
n = read(sock, buffer, 4096);
if(n < 0) {
fprintf(stderr, "[-]Error reading (Port closed maybe?!)\n");
return;
}
fprintf(stdout,"[*]%s\n", buffer);
close(sock);
}