Here is a program that takes an IP address in the form of an input string, and converts it to a long
value. The filter_ip()
function is used to first remove all non-numeric characters from the string. Then strtol()
is used to convert the string to a long
value.
It is better to use strtol()
than atol()
because strtol()
detects integer overflows. errno
is declared in the error.h
header file, and strtol()
sets the value of errno
if there is an overflow. strtol()
converts as many characters as it can, starting from the beginning of the string, and sets tailptr
to point the the remaining characters. If no conversion can be performed, tailptr
will point to the beginning of the string.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
void filter_ip(char *str);
int main(void)
{
char ip_addr[] = "127.0.0.1";
long res;
char *tailptr;
printf("IP Address: %s\n", ip_addr);
filter_ip(ip_addr);
errno = 0;
res = strtol(ip_addr, &tailptr, 10);
if (errno) {
perror("Unable to convert IP address");
} else if (tailptr == ip_addr) {
fprintf(stderr, "No conversion performed\n");
} else {
printf("%ld\n", res);
}
return 0;
}
void filter_ip(char *str)
{
size_t i, j;
for (i = 0, j = 0; str[i] != '\0'; i++) {
if (isdigit(str[i])) {
str[j++] = str[i];
}
}
str[j] = '\0';
}
Program output:
IP Address: 127.0.0.1
127001