17. February 2012 08:00
A short example to show how to check and ip address is actually an ip address in C. I have seen a number of time that people provide solution using reg'ex and various other methods to attempt to do this. However there is a standard function that will test for you.
The function is called inet_pton will be able to tell you if a string is acutally an ip address or not. Typically the function also has another use which is to convert an ip address into its network byte ordered integer format.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
int main(int argc, char **argv) {
unsigned long ip = 0;
if (argc < 2) {
printf("Usage: %s <ipv4>\n", argv[0]);
exit(EXIT_FAILURE);
}
if (0 == inet_pton(AF_INET, argv[1], &ip)) {
printf("Failed\n");
exit(EXIT_FAILURE);
}
printf("IP: %ld\n", ip);
return 0;
}
adfe5d34-722d-48ca-b770-c99771d850c1|0|.0