Reputation: 333
I want to search an IP address up to the "/" and take everything before the "/" so I can convert it from a char to an int. Then take that int and convert it to binary. How would I read everything before the "/", store it in a variable, and then continue to convert it to binary. I'm aware of strlen
but don't think that will work with my situation? The length up to "/" is not constant.
My code:
int main(int argc, char** argv)
{
char *s;
char buf[] = "10.29.246.49/32";
s = strchr(buf, '/');
if (s != NULL)
printf("found '/' at %s\n", s);
return 0;
}
Upvotes: 0
Views: 68
Reputation: 3045
You can use strtok
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv)
{
char *s;
char buf[] = "10.29.246.49/32";
s = strtok(buf, "/");
if (s)
printf("%s\n", s);
return 0;
}
This program yields
10.29.246.49
The character '/'
is replaced with '\0'
. Now you can use strlen
on the string.
Upvotes: 2