Compare commits

...

2 commits

View file

@ -6,12 +6,12 @@
#include <errno.h>
#define MIN_TCP_PORT 1
#define TCP_TABLE "/proc/net/tcp"
#define TCP_TABLE_PATH "/proc/net/tcp"
#define TCP_TABLE_LINE_LENGTH 151
#define LOCALHOST_HEX "0100007F"
#define WILDCARD_HEX "00000000"
#define LOCALHOSTIP_HEX "0100007F"
#define WILDCARDIP_HEX "00000000"
#define LISTENING_HEX "0A"
#define PORTS_BLOCKS_TO_ALLOW 4
#define BLOCKS_TO_ALLOC 4
/**
* Print a nice error message
@ -23,14 +23,15 @@ static void print_error(char *name, const char *message) {
/**
* Get all the listening TCP ports
*/
static unsigned short *get_listening_ports(unsigned short *listening_ports, FILE *tcp_table_fptr) {
static unsigned short *get_listening_ports(FILE *tcp_table_fptr) {
unsigned short *listening_ports = malloc(BLOCKS_TO_ALLOC * sizeof(short));
char line[TCP_TABLE_LINE_LENGTH];
char delimiter[] = " ";
unsigned short len = 0;
char *address;
char *state;
char *field;
size_t allowed_for_ports = PORTS_BLOCKS_TO_ALLOW;
size_t blocks_allocated = BLOCKS_TO_ALLOC;
// Skip first line (header)
fgets(line, sizeof(line), tcp_table_fptr);
@ -48,19 +49,18 @@ static unsigned short *get_listening_ports(unsigned short *listening_ports, FILE
field = strtok(NULL, delimiter);
}
if ((!strncmp(address, LOCALHOST_HEX, 8) || !strncmp(address, WILDCARD_HEX, 8)) && !strncmp(state, LISTENING_HEX, 2)) {
if (len == allowed_for_ports) {
allowed_for_ports = allowed_for_ports + PORTS_BLOCKS_TO_ALLOW;
listening_ports = realloc(listening_ports, allowed_for_ports * sizeof(unsigned short));
if ((!strncmp(address, LOCALHOSTIP_HEX, 8) || !strncmp(address, WILDCARDIP_HEX, 8)) && !strncmp(state, LISTENING_HEX, 2)) {
if (len == blocks_allocated) {
blocks_allocated = blocks_allocated + BLOCKS_TO_ALLOC;
listening_ports = realloc(listening_ports, blocks_allocated * sizeof(short));
}
listening_ports[len] = strtol(address + strlen(address) - 4, NULL, 16);
len++;
}
}
if (len == allowed_for_ports) {
allowed_for_ports = allowed_for_ports + PORTS_BLOCKS_TO_ALLOW;
listening_ports = realloc(listening_ports, allowed_for_ports * sizeof(unsigned short));
if (len == blocks_allocated) {
listening_ports = realloc(listening_ports, blocks_allocated + 1);
}
listening_ports[len] = 0;
@ -94,14 +94,13 @@ int main(int argc, char *argv[]) {
}
// Open TCP table
FILE *tcp_table_fptr = fopen(TCP_TABLE, "r");
FILE *tcp_table_fptr = fopen(TCP_TABLE_PATH, "r");
if (tcp_table_fptr == NULL) {
print_error(argv[0], "error opening the TCP table.");
return errno;
}
unsigned short *listening_ports = malloc(PORTS_BLOCKS_TO_ALLOW * sizeof(unsigned short));
listening_ports = get_listening_ports(listening_ports, tcp_table_fptr);
unsigned short *listening_ports = get_listening_ports(tcp_table_fptr);
if (fclose(tcp_table_fptr) != 0) {
print_error(argv[0], "can't close the TCP table.");