Date: 2015feb6
Update: 2026oct3
Language: C/C++
Q. C/C++: Simple code to validate an internet host name / IP-address
A. Here is a simple function for that.
Its not perfect but its very fast (not internet access) and
catches must user mistakes.
// Helper
inline bool isValidHostChar(const char c) {
return isalnum(c) || c == '.' || c == '-' || c == '_';
}
// Not perfect but catches most user mistakes
bool isValidHost(const char *host) {
if (host == NULL) return false;
if (strlen(host) < 3) return false;
for (const char *p = host; *p; p++) {
if (!isValidHostChar(*p)) return false;
}
return true;
}
Full Example Use:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
// (Place the functions from above here)
int main() {
{
const char *str = "example.com";
printf("is '%s' valid=%s\n", str, isValidHost(str) ? "true" : "false");
}
{
const char *str = "example";
printf("is '%s' valid=%s\n", str, isValidHost(str) ? "true" : "false");
}
{
const char *str = "127.0.0.1";
printf("is '%s' valid=%s\n", str, isValidHost(str) ? "true" : "false");
}
{
const char *str = "John Doe";
printf("is '%s' valid=%s\n", str, isValidHost(str) ? "true" : "false");
}
}
Output:
is 'example.com' valid=true // Correct
is 'example' valid=true // Wrong
is '127.0.0.1' valid=true // Correct
is 'John Doe' valid=false // Correct