Convert an ip address to long value



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?

-kyle

.



Relevant Pages

  • Re: Convert an ip address to long value
    ... > 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. ... I don't see any any conversion from character to digits (via a "- '0'" ... > int main{ ...
    (comp.lang.c)
  • Re: Convert an ip address to long value
    ... > 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. ... > int main{ ...
    (comp.lang.c)
  • Re: Namenauflösung DNS
    ... Nein, ganz normal 'alt' IPv4. ... Robert ... Prev by Date: ...
    (microsoft.public.de.german.windowsxp.networking)
  • #define Question
    ... The following code is from Exercise 9.3 from 'A book on C' ... int main ... the Question is what single character do i need to add to make it works with ...
    (comp.lang.c)