diff options
author | Lennart Poettering <lennart@poettering.net> | 2016-11-18 16:55:01 +0100 |
---|---|---|
committer | Lennart Poettering <lennart@poettering.net> | 2016-11-21 22:58:26 +0100 |
commit | 08a4849ec94fd06c3284994b91835b31a3a2f3aa (patch) | |
tree | 103141ee3a0db934d44bdf1e964ec682060fe658 | |
parent | fd18634de4d84eba2422908948c27ec6c5bf4cf5 (diff) |
shared: add new API to validate a string as hostname or IP address
-rw-r--r-- | src/shared/dns-domain.c | 12 | ||||
-rw-r--r-- | src/shared/dns-domain.h | 2 | ||||
-rw-r--r-- | src/test/test-dns-domain.c | 13 |
3 files changed, 27 insertions, 0 deletions
diff --git a/src/shared/dns-domain.c b/src/shared/dns-domain.c index f9a6fd5f03..33debadb15 100644 --- a/src/shared/dns-domain.c +++ b/src/shared/dns-domain.c @@ -1324,3 +1324,15 @@ int dns_name_apply_idna(const char *name, char **ret) { return (int) n; } + +int dns_name_is_valid_or_address(const char *name) { + /* Returns > 0 if the specified name is either a valid IP address formatted as string or a valid DNS name */ + + if (isempty(name)) + return 0; + + if (in_addr_from_string_auto(name, NULL, NULL) >= 0) + return 1; + + return dns_name_is_valid(name); +} diff --git a/src/shared/dns-domain.h b/src/shared/dns-domain.h index af780f0b8b..03f160369c 100644 --- a/src/shared/dns-domain.h +++ b/src/shared/dns-domain.h @@ -107,3 +107,5 @@ int dns_name_equal_skip(const char *a, unsigned n_labels, const char *b); int dns_name_common_suffix(const char *a, const char *b, const char **ret); int dns_name_apply_idna(const char *name, char **ret); + +int dns_name_is_valid_or_address(const char *name); diff --git a/src/test/test-dns-domain.c b/src/test/test-dns-domain.c index e2f097c95e..b4db4a6702 100644 --- a/src/test/test-dns-domain.c +++ b/src/test/test-dns-domain.c @@ -627,6 +627,18 @@ static void test_dns_name_apply_idna(void) { test_dns_name_apply_idna_one("föö.bär.", "xn--f-1gaa.xn--br-via"); } +static void test_dns_name_is_valid_or_address(void) { + assert_se(dns_name_is_valid_or_address(NULL) == 0); + assert_se(dns_name_is_valid_or_address("") == 0); + assert_se(dns_name_is_valid_or_address("foobar") > 0); + assert_se(dns_name_is_valid_or_address("foobar.com") > 0); + assert_se(dns_name_is_valid_or_address("foobar..com") == 0); + assert_se(dns_name_is_valid_or_address("foobar.com.") > 0); + assert_se(dns_name_is_valid_or_address("127.0.0.1") > 0); + assert_se(dns_name_is_valid_or_address("::") > 0); + assert_se(dns_name_is_valid_or_address("::1") > 0); +} + int main(int argc, char *argv[]) { test_dns_label_unescape(); @@ -654,6 +666,7 @@ int main(int argc, char *argv[]) { test_dns_name_compare_func(); test_dns_name_common_suffix(); test_dns_name_apply_idna(); + test_dns_name_is_valid_or_address(); return 0; } |