Re: Convert an ip address to long value
- From: Michael Mair <Michael.Mair@xxxxxxxxxxxxxxx>
- Date: Tue, 31 Jan 2006 21:56:42 +0100
Michael Mair wrote:
kyle.tk wrote:
I am trying to write a function to convert an ipv4 address that is held in the string char *ip to its long value equivalent. Here is what I have right now, but I can't seem to get it to work.
#include <string.h> #include <stdio.h>
/* Convert an ipv4 address to long integer */ /* "192.168.1.1" --> 3232235777 */ unsigned long iptol(char *ip){ unsigned char o1,o2,o3,o4; /* The 4 ocets */ char tmp[13] = "000000000000\0"; short i = 11; /* Current Index in tmp */ short j = (strlen(ip) - 1); do { if ((ip[--j] == '.')){ i -= (i % 3); } else { tmp[--i] = ip[j]; } } while (i > -1); o1 = (tmp[0] * 100) + (tmp[1] * 10) + tmp[2]; o2 = (tmp[3] * 100) + (tmp[4] * 10) + tmp[5]; o3 = (tmp[6] * 100) + (tmp[7] * 10) + tmp[8]; o4 = (tmp[9] * 100) + (tmp[10] * 10) + tmp[11]; return (o1 * 16777216) + (o2 * 65536) + (o3 * 256) + o4; }
int main(void){ char *ip = "124.15.22.102"; iptol(ip); }
Any suggestions? Maybe there is a better way to do this?
Too lazy to look right now; consider
#include <string.h> #include <stdlib.h> #include <stdio.h>
#define NUM_OCTETTS 4
int iptoul (const char *ip, unsigned long *plong) { char *next = NULL; const char *curr = ip; unsigned long tmp; int i, err = 0;
*plong = 0; for (i = 0; i < NUM_OCTETTS; i++) { tmp = strtoul(curr, &next, 10); if (tmp >= 256 || (tmp == 0 && next == curr)) { err++; break; }
Forgot the obvious one:
if (*next != '.' && i != (NUM_OCTETTS-1)) {
err++;
break;
}
*plong = (*plong << 8) + tmp; curr = next + 1; }
if (err) { return 1; } else { return 0; } }
int main (void) { const char *ip = "124.15.22.102"; unsigned long ret;
if (0 == iptoul(ip, &ret)) printf("%s -> %lu\n", ip, ret);
return 0; }
Cheers Michael
-- E-Mail: Mine is an /at/ gmx /dot/ de address. .
- References:
- Convert an ip address to long value
- From: kyle.tk
- Re: Convert an ip address to long value
- From: Michael Mair
- Convert an ip address to long value
- Prev by Date: Re: Convert an ip address to long value
- Next by Date: Re: Question about the clc string lib
- Previous by thread: Re: Convert an ip address to long value
- Next by thread: Is C portable from PC to UNIX
- Index(es):
Relevant Pages
|