E
Eric Lilja
Hello, I have IPv4-numbers in the following format:
"\\x0A\\x11\\x8C\\x01"
Now I need each byte as an int. I wrote the following test program:
#include <stdio.h>
#include <stdlib.h>
static void to_ip(const char *, int *);
static void extract_substring(const char *, u_short, u_short, char *);
int
main(void)
{
const char *ip_as_string="\\x0A\\x11\\x8C\\x01";
int ip[4];
to_ip(ip_as_string, ip);
printf("IP is %i.%i.%i.%i\n", ip[0], ip[1], ip[2], ip[3]);
return 0;
}
static void
extract_substring(const char *s, u_short start, u_short end, char *out)
{
u_short out_index = 0;
for(; start <= end; ++start)
out[out_index++] = s[start];
out[++start] = '\0';
}
static void
to_ip(const char *ip_as_string, int *ip)
{
char sub[5] = "0";
char *ptr = sub;
u_short start_index = 1;
u_short end_index = 3;
u_short i = 0;
for(; i < 4; ++i)
{
extract_substring(ip_as_string, start_index, end_index, ptr + 1);
start_index += 4;
end_index += 4;
ip = strtol(sub, NULL, 16);
}
}
It compiles cleanly and produces the following output:
$ ./convert_to_ip.exe
IP is 10.17.140.1
But since I am very poor on string manipulations in C, I'm guessing
there are alot cleaner ways to do this. Please help me improve the
code. It's a homework problem, but as you can see I attempted to solve
it myself first.
/ E
"\\x0A\\x11\\x8C\\x01"
Now I need each byte as an int. I wrote the following test program:
#include <stdio.h>
#include <stdlib.h>
static void to_ip(const char *, int *);
static void extract_substring(const char *, u_short, u_short, char *);
int
main(void)
{
const char *ip_as_string="\\x0A\\x11\\x8C\\x01";
int ip[4];
to_ip(ip_as_string, ip);
printf("IP is %i.%i.%i.%i\n", ip[0], ip[1], ip[2], ip[3]);
return 0;
}
static void
extract_substring(const char *s, u_short start, u_short end, char *out)
{
u_short out_index = 0;
for(; start <= end; ++start)
out[out_index++] = s[start];
out[++start] = '\0';
}
static void
to_ip(const char *ip_as_string, int *ip)
{
char sub[5] = "0";
char *ptr = sub;
u_short start_index = 1;
u_short end_index = 3;
u_short i = 0;
for(; i < 4; ++i)
{
extract_substring(ip_as_string, start_index, end_index, ptr + 1);
start_index += 4;
end_index += 4;
ip = strtol(sub, NULL, 16);
}
}
It compiles cleanly and produces the following output:
$ ./convert_to_ip.exe
IP is 10.17.140.1
But since I am very poor on string manipulations in C, I'm guessing
there are alot cleaner ways to do this. Please help me improve the
code. It's a homework problem, but as you can see I attempted to solve
it myself first.
/ E