Skip to content

Instantly share code, notes, and snippets.

@waffle2k
Created June 11, 2014 19:26
Show Gist options
  • Save waffle2k/31a592c2c908a76f21fd to your computer and use it in GitHub Desktop.
Save waffle2k/31a592c2c908a76f21fd to your computer and use it in GitHub Desktop.
Extract an IP address from a string.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// http://stackoverflow.com/a/792645
static
int isValidIp4 (char *str) {
int segs = 0; /* Segment count. */
int chcnt = 0; /* Character count within segment. */
int accum = 0; /* Accumulator for segment. */
/* Catch NULL pointer. */
if (str == NULL)
return 0;
/* Process every character in string. */
while (*str != '\0') {
/* Segment changeover. */
if (*str == '.') {
/* Must have some digits in segment. */
if (chcnt == 0)
return 0;
/* Limit number of segments. */
if (++segs == 4)
return 0;
/* Reset segment values and restart loop. */
chcnt = accum = 0;
str++;
continue;
}
/* Check numeric. */
if ((*str < '0') || (*str > '9'))
break;
/* Accumulate and check segment. */
if ((accum = accum * 10 + *str - '0') > 255)
return 0;
/* Advance other segment specific stuff and continue loop. */
chcnt++;
str++;
}
/* Check enough segments and enough characters in last segment. */
if (segs != 3)
return 0;
if (chcnt == 0)
return 0;
/* Address okay. */
return 1;
}
static
char * find_end_of_ip(char *ip){
char *p = ip;
while (*p != '\0') {
//printf("p[%c]\n",*p);
if (isdigit(*p)){
p++;
}
else if (*p == '.'){
p++;
}
else
return p;
}
return p;
}
static
char * extract_ip(char *ip){
char *d = strdup(ip);
////printf("dup[%s]\n", d);
char *end = find_end_of_ip(d);
*end = '\0';
return d;
}
int main(){
char *lines[] = {
"this has the address 1.2.3.4 in it",
"I connected from 22.44.55.66 today",
"test 1.2.3.4",
"1.2.3.4",
0
};
char **line = lines;
char *p;
while( *line ){
printf("Testing [%s]\n", *line );
p = *line;
while( *p ){
//printf("input [%s]\n", p );
if (isValidIp4( p )){
printf("VALID!!\n");
char *ipaddress = extract_ip(p);
printf("%s\n", ipaddress);
free(ipaddress);
break;
}
p++;
}
line++;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment