Skip to content

Commit

Permalink
use elegant check for valid ip addresses (#372)
Browse files Browse the repository at this point in the history
Also works for IPv6 addresses
  • Loading branch information
mwarning committed Jun 19, 2019
1 parent 444707c commit 1777849
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 25 deletions.
26 changes: 1 addition & 25 deletions src/conf.c
Original file line number Diff line number Diff line change
Expand Up @@ -45,30 +45,6 @@
#include "auth.h"
#include "util.h"

int validateIP4Dotted(const char *ip4addr)
{
if (strlen(ip4addr) < 7 || strlen(ip4addr) > 15) {
return 0;
}

char tail[16];
tail[0] = 0;
int i = 0;
unsigned int d[4];
int c = sscanf(ip4addr, "%3u.%3u.%3u.%3u%s", &d[0], &d[1], &d[2], &d[3], tail);

if (c != 4 || tail[0]) {
return 0;
}

for (i = 0; i < 4; i++) {
if (d[i] > 255) {
return 0;
}
}
return 1;
}


/** @internal
* Holds the current configuration of the gateway */
Expand Down Expand Up @@ -989,7 +965,7 @@ config_read(const char *filename)
fclose(fd);

if (config.fas_remoteip) {
if (validateIP4Dotted(config.fas_remoteip) == 1) {
if (is_addr(config.fas_remoteip) == 1) {
debug(LOG_INFO, "fasremoteip - %s - is a valid IPv4 address...", config.fas_remoteip);
} else {
debug(LOG_ERR, "fasremoteip - %s - is NOT a valid IPv4 address format...", config.fas_remoteip);
Expand Down
8 changes: 8 additions & 0 deletions src/util.c
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,14 @@ get_uptime_string(char buf[64])
return format_duration(started_time, time(NULL), buf);
}

int is_addr(const char* addr) {
struct sockaddr_in sa;
struct sockaddr_in6 sa6;

return (inet_pton(AF_INET, addr, &sa.sin_addr) == 1) ||
(inet_pton(AF_INET6, addr, &sa6.sin6_addr) == 1);
}

void
ndsctl_status(FILE *fp)
{
Expand Down
3 changes: 3 additions & 0 deletions src/util.h
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ int is_auth_online();
/* @brief Format a time_t value to 'Fri Jul 27 18:52:22 2018' */
char *format_time(time_t time, char buf[64]);

/* @brief Check if the address is a valid IPv4 or IPv6 address */
int is_addr(const char* addr);

/*
* @brief Mallocs and returns nodogsplash uptime string
*/
Expand Down

0 comments on commit 1777849

Please sign in to comment.