C IP Address Validation
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 actually 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;
}
Did You find this page useful?
Yes
No
Last Modified: 08 March 2017
Releated Posts
2017-04-25 - Linux Programming - Signals the easy way
2017-03-01 - Shooting yourself in the head with threads
2013-02-16 - C - Some simple examples of using strcat
2012-11-03 - C - How to override malloc / free
2012-08-09 - C++ - Check an IP Address is in a IP Mask
2012-04-05 - Using gdb to debug a core file
2012-03-15 - C - Is the stdin a tty
2012-03-13 - C - Converting from char / string to int using atoi
2012-03-08 - C - UDP Socket example
2012-02-20 - C - Get home dir location in linux
2012-02-17 - C - IP address validation
2012-02-15 - C - Get current ip address of an interface
2012-02-10 - Using asprintf instead of sprintf or snprintf
2012-01-31 - C - Example of how to overwrite argv
2012-01-30 - C - The string reverse
2012-01-27 - C - Palindrome
2012-01-26 - C - Example of using popen
2011-12-28 - C - gethostbyname example
2011-12-11 - C - Linux get mac address from interface
2011-02-10 - CSharp - Wake on Lan (WOL) Packet