Compare commits

..

No commits in common. "1662776d6b3aba14fde091ec30f1ab53768d67ba" and "7fa3b4366b3ee958520f4e67ae9ba0dae2a8887b" have entirely different histories.

View file

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