473,748 Members | 2,658 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

Jan 31 '06 #1
65 21457
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;
}
*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.
Jan 31 '06 #2
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.
Jan 31 '06 #3


kyle.tk wrote On 01/31/06 15:27,:
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?


You could use sscanf(). Unfortunately, it's hard
to persuade sscanf() to reject things like "123.0.0.-1"
or " 127. 0. 0. 1".

Another possibility would be to use isdigit() to
check the first character of each field and then strtoul()
to convert it, then check that strtoul() stopped on a '.'
(or on a '\0' the final time). You might also check that
the stopping point wasn't too far from the start, so as
to reject "00000000000012 7.0.0.000000000 000000001".

--
Er*********@sun .com

Feb 1 '06 #4
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 ";
That \0 is not necessary.
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);
Well, let's work through this loop.
Start: i = 11, j = 10.
Iter 1: j => 9. ip[9] == '.' so i => 9.
Iter 2: j => 8. i => 8. tmp[8] = ip[8] = '1'.
Iter 3: j => 7. ip[7] == '.' so i => 6.
Iter 4: j => 6. i => 5. tmp[5] = ip[6] = '8'.
Iter 5: j => 5. i => 4. tmp[4] = ip[5] = '6'.
Iter 6: j => 4. i => 3. tmp[3] = ip[4] = '1'.
Iter 7: j => 3. ip[3] = '.', so i => 3.
Iter 8: j => 2. i => 2. tmp[2] = ip[2] = '2'.
Iter 9: j => 1. i => 1. tmp[1] = ip[1] = '9'.
Iter10: j => 0. i => 0. tmp[0] = ip[0] = '1'.
Iter11: j => -1. Undefined behaviour, reading ip[-1].
Maybe will try and write to tmp[-1].

So you end up with tmp = "1921680010 00" and maybe having
written a buffer overflow before the start of tmp.

Hopefully it's now clear that your loop structure is pretty
weak and error-prone. A much better approach here is
to read forwards through ip, computing as you go, you
don't need to create a new array.
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];


tmp[0] is '1'. '1' * 100 will probably give you a value of 4900.
You mean to write: (tmp[0] - '0') * 100 , etc.

Feb 1 '06 #5

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;
}
*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.


Alright, after looking at that post I came up with this. I didn't use
yours verbatim because I have not yet implemented the stroul function.

Heres what I have got now. Critique?

unsigned long iptol(const char *ip){
unsigned long value = 0; /* Total Value */
unsigned char ocet = 0; /* Ocet Value */
int i = strlen(ip) - 1; /* Index in ip */
int m = 1; /* Ocet multiplier */
int j;
for (j=0; j < 4; j++){
while ( ip[i] != '.' && ip[i] != '\0' ){
ocet += m * (ip[i] - 48);
m *= 10;
i--;
}
value += (ocet << (8 * j));
ocet = 0;
m = 1;
i--;
};
return value;
}
-kyle

Feb 1 '06 #6

"kyle.tk" <ky*****@gmail. com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
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?


Yes, this is an alternate method, using more string processing. It compiles
and works for DJGPP and OW1.3:
#include <stdio.h>
#include <string.h>

unsigned long iptoul(char *ip)
{
char i,*tmp;
unsigned long val=0, cvt;

tmp=strtok(ip," .");
for (i=0;i<4;i++)
{
sscanf(tmp,"%lu ",&cvt);
val<<=8;
val|=(unsigned char)cvt;
tmp=strtok(NULL ,".");
}
return(val);
}

int main(void)
{

char *ip="124.15.22. 102";

unsigned long ret;

printf("%s\n",i p);
ret=iptoul(ip);
printf("%08lx\n ",ret);
return(0);
}
Rod Pemberton
Feb 1 '06 #7
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;
}
I don't see any any conversion from character to digits (via a "- '0'"
kind of operation.) So I can't see how this is possibly supposed to
work. Furthermore, it is possible and legal to specify IP addresses
in which each portion might exceed 255, and therefore might have more
than 3 digits -- its supposed to just wrap around.
int main(void){
char *ip = "124.15.22.102" ;
iptol(ip);
}

Any suggestions? Maybe there is a better way to do this?


This is off the top of my head:

unsigned long iptol (const char *ip) {
unsigned long ipl, b;
int i, m;
for (b = ipl = 0ul, m=4, i = 0; ; i++) {
switch (ip[i]) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
b = b*10 + ip[i] - '0';
break;
default:
ipl = (ipl << 8ul) + b;
if ('.' != ip[i] || 0==(--m)) return ipl;
b = 0;
break;
}
}
}

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/

Feb 1 '06 #8
"kyle.tk" wrote:
.... snip ...
Alright, after looking at that post I came up with this. I didn't use
yours verbatim because I have not yet implemented the stroul function.


strtoul() is a standard function. You don't need to implement it.

--
"The power of the Executive to cast a man into prison without
formulating any charge known to the law, and particularly to
deny him the judgement of his peers, is in the highest degree
odious and is the foundation of all totalitarian government
whether Nazi or Communist." -- W. Churchill, Nov 21, 1943
Feb 1 '06 #9

CBFalconer wrote:

strtoul() is a standard function. You don't need to implement it.


I know it is a standard function in libc. The platform I am targeting
does not yet have a fully ported libc.

-kyle

Feb 1 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
5431
by: jagmeena | last post by:
Hello, I am sure this problem has been addressed before, however, I could'nt get a suitable solution to my problem. Hence I am posting here. Thanks a lot for all your help. The code I have is typedef struct Rec { unsigned char msg; unsigned long len;
7
2154
by: bryan | last post by:
I think I'm missing something fundamental here. I'm trying to set an unsigned long value via a u_long pointer, however it coredumps everytime I get to that instruction. Here is a sample program that demonstrates the issue: --- snip --- #include <unistd.h> int main() { char buf;
2
3121
by: Ryan Liu | last post by:
Hi, Can someone tell me how to calculate an IPaddress's long value? I have an application which lisiten on a port using UDP protocol. There could be multiple client sendind UDP data to it and I am only interested data from one client, I know that client's IP address in form of 127.0.0.1 etc. I think I need convert that IP into IPaddress then can compare with
1
2082
by: benfly08 | last post by:
Hi, guys. I have a Long value like 12345678, but i want to format it as 12,345,678 and then convert it into String. I can't find out the way to format a long value like that. Any Hints?
0
8995
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8832
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9381
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9332
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9254
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4608
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4879
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3316
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2791
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.