Check if a String is a Valid IPv4 Address in C

To check if a string is a valid IPv4 address in C, you can either use built-in functions like inet_pton from <arpa/inet.h> or implement your own validation logic using string manipulation functions such as strtok and atoi. Both approaches ensure that the given string conforms to the IPv4 format: four numerical segments separated by dots, with each segment between 0 and 255.


Example 1: Using inet_pton Function

This example demonstrates how to check if a string is a valid IPv4 address using the inet_pton function. We pass the IP string to inet_pton, which converts the address from text to binary form. If the conversion is successful, the address is valid.

main.c

</>
Copy
#include <stdio.h>
#include <arpa/inet.h>

int main() {
    const char *ip = "192.168.1.1";
    struct in_addr addr;
    int result = inet_pton(AF_INET, ip, &addr);

    if(result == 1)
        printf("Valid IPv4 address\n");
    else
        printf("Invalid IPv4 address\n");

    return 0;
}

Explanation:

  1. The variable ip holds the string we want to validate.
  2. The inet_pton function is called with parameters: AF_INET (address family), the IP string, and a pointer to addr where the binary representation will be stored.
  3. If inet_pton returns 1, the IP address is valid; otherwise, it is invalid.
  4. The printf function outputs the result accordingly.

Output:

Valid IPv4 address

Example 2: Manual Validation Using strtok and atoi

This example demonstrates how to manually validate an IPv4 address by parsing the string using strtok and converting each segment to an integer using atoi. We check that each segment is a number between 0 and 255 and that the address contains exactly three dots.

main.c

</>
Copy
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int is_valid_ip(const char *ip) {
    if(ip == NULL)
        return 0;

    int num, dots = 0;
    char *ip_copy = strdup(ip);  // Duplicate the input string
    if(ip_copy == NULL)
        return 0;
    
    char *token = strtok(ip_copy, ".");
    if(token == NULL) {
        free(ip_copy);
        return 0;
    }
    
    while(token) {
        // Check if token is a number
        for (int i = 0; token[i] != '\0'; i++) {
            if(!isdigit(token[i])) {
                free(ip_copy);
                return 0;
            }
        }
        
        num = atoi(token);
        if(num < 0 || num > 255) {
            free(ip_copy);
            return 0;
        }
        
        token = strtok(NULL, ".");
        if(token != NULL)
            dots++;
    }
    
    free(ip_copy);
    // Valid IP should contain exactly 3 dots
    return (dots == 3);
}

int main() {
    const char *ip = "256.100.50.0";

    if(is_valid_ip(ip))
        printf("Valid IPv4 address\n");
    else
        printf("Invalid IPv4 address\n");

    return 0;
}

Explanation:

  1. The function is_valid_ip takes a string ip as input and returns 1 if valid, otherwise 0.
  2. strdup creates a duplicate of the input string for safe tokenization.
  3. strtok is used to split the string by the dot character (.), obtaining each segment of the IP address.
  4. For each token, we verify that every character is a digit using isdigit and then convert the token to an integer with atoi.
  5. We check that the integer value is between 0 and 255.
  6. The variable dots counts the number of dot separators; a valid IPv4 address must have exactly three dots.
  7. The main function tests the validation function with an example IP address and prints the result using printf.

Output:

Invalid IPv4 address

Conclusion

In this tutorial, we learned two different approaches to check if a string is a valid IPv4 address in C:

  1. Using inet_pton: This approach leverages a standard library function to convert the IP address from text to binary format, ensuring its validity.
  2. Manual Validation: This method uses string tokenization and conversion functions to verify each segment of the IP address manually.