473,772 Members | 3,672 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
65 21478

"Joe Wright" wrote:
RSoIsCaIrLiIoA 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.

I hate to be late. Assuming this was ever a valid question, how about
this? Is there a better way?


there sure is a shorter way... It is up to you to figure out the converse
function of iptol yourself (aka ltoip)... try using the % operator and
shifting... ;-)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
<SNIP>

Too many #includes... tend to bloat the code ...

Here is my working example (OW1.4 but I don't find any implementation
defined stuff in it so it _is_ portable, AFAICS) which doesn't even need
_any_ lib-function for the logic, it is pure C too...:

//just for printf in main() and nothing else...
#include <stdio.h>

unsigned long iptol(char* IP) {
char* runner=IP;
unsigned int factor=1;
unsigned long temp=0;
unsigned int reset=0;

while(*runner) runner++;

while((IP - runner--)) {
if(*runner=='.' ) {
factor <<= 8;
reset^=reset;
runner--;
}
temp += factor * (*runner - '0') * (reset==1?10:(r eset==2?100:1)) ;
reset++;
}
return temp;
}

int main(int argc, char **argv)
{
if(argc<=1){
printf("Example : %s 10.2.3.123\n", argv[0]);
return -1;
}

printf("%x:%ld" ,iptol(argv[1]),iptol(argv[1]));
return 0;
}

The theory is that really well written stuff doesn't need comments. :-)


could be true :-) but I tend to say real beauty needs no decoration...

regards
John
Feb 3 '06 #31

"John F" wrote:
Here is my working example (OW1.4 but I don't find any implementation
defined stuff in it so it _is_ portable, AFAICS) which doesn't even need
_any_ lib-function for the logic, it is pure C too...:
the portability stuff was meant to exclude the argv[0] ... sorry...
if(argc<=1){
printf("Example : %s 10.2.3.123\n", argv[0]);
return -1;
}


this is of course _not_ portable... I simply read over it... sorry.

regards
John
Feb 3 '06 #32
Mark McIntyre wrote:
RSoIsCaIrLiIoA <zz@zz.z> wrote:
"kyle.tk" <ky*****@gmail. com> 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.


do you like my last try?


I don't like any of your tries - you're posting what looks like some
form of assembler to comp.lang.c. Stop that please.


+-------------------+ .:\:\:/:/:.
| PLEASE DO NOT F :.:\:\:/:/:.:
| FEED THE TROLLS | :=.' - - '.=:
| | '=(\ 9 9 /)='
| Thank you, | ( (_) )
| Management | /`-vvv-'\
+-------------------+ / \
| | @@@ / /|,,,,,|\ \
| | @@@ /_// /^\ \\_\
@x@@x@ | | |/ WW( ( ) )WW
\||||/ | | \| __\,,\ /,,/__
\||/ | | | jgs (______Y______)
/\/\/\/\/\/\/\/\//\/\\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
=============== =============== =============== =============== ==

--
"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 3 '06 #33
"John F" <sp**@127.0.0.1 > writes:
reset^=reset;


Are you hoping that your compiler will turn that into
xor eax,eax
and thus be faster than
mov eax, 0
?

Or do you just think that more is more?

Phil
--
What is it: is man only a blunder of God, or God only a blunder of man?
-- Friedrich Nietzsche (1844-1900), The Twilight of the Gods
Feb 3 '06 #34

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.

[snip]

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

-kyle


This example is probably a little silly, but it has the advantage of
not relying on the standard library (other than printf()). It will
handle octets in different formats (e.g., 0.255.0377.0xff ) and it will
accept leading and trailing whitespace in each octet (e.g., "127. 0
..0. 1"). Whitespace embedded within the octet token ("1 27.0.0.1")
will cause the function to return 0.

Error handling is non-existent; it will not detect overflow in any of
the octets (e.g. 256.397.400.999 ), nor will it handle missing octets
(255.255.0). That should be relatively straightforward to fix, though.

#include <stdio.h>

typedef enum {start, lead, dec, oct, hex, tail, err} state_t;
typedef enum {shft, eval, none} action_t;

static state_t stateTable[7][20] = {
{lead, dec, dec, dec, dec, dec, dec, dec, dec, dec, err, err, err,
err, err, err, err, err, start, err},
{oct, oct, oct, oct, oct, oct, oct, oct, err, err, err, err, err,
err, err, err, hex, start, tail, err},
{dec, dec, dec, dec, dec, dec, dec, dec, dec, dec, err, err, err,
err, err, err, err, start, tail, err},
{oct, oct, oct, oct, oct, oct, oct, oct, err, err, err, err, err,
err, err, err, err, start, tail, err},
{hex, hex, hex, hex, hex, hex, hex, hex, hex, hex, hex, hex, hex,
hex, hex, hex, err, start, tail, err},
{err, err, err, err, err, err, err, err, err, err, err, err, err,
err, err, err, err, start, tail, err},
{err, err, err, err, err, err, err, err, err, err, err, err, err,
err, err, err, err, err, err, err}
};

static action_t actionTable[7][20] = {
{none, shft, shft, shft, shft, shft, shft, shft, shft, shft, none,
none, none, none, none, none, none, eval, none, none},
{shft, shft, shft, shft, shft, shft, shft, shft, none, none, none,
none, none, none, none, none, none, eval, none, none},
{shft, shft, shft, shft, shft, shft, shft, shft, shft, shft, none,
none, none, none, none, none, none, eval, none, none},
{shft, shft, shft, shft, shft, shft, shft, shft, none, none, none,
none, none, none, none, none, none, eval, none, none},
{shft, shft, shft, shft, shft, shft, shft, shft, shft, shft, shft,
shft, shft, shft, shft, shft, none, eval, none, none},
{none, none, none, none, none, none, none, none, none, none, none,
none, none, none, none, none, none, eval, none, none},
{none, none, none, none, none, none, none, none, none, none, none,
none, none, none, none, none, none, none, none, none}
};
static int mapchar(int c)
{
switch(c)
{
case '0': return 0; break;
case '1': return 1; break;
case '2': return 2; break;
case '3': return 3; break;
case '4': return 4; break;
case '5': return 5; break;
case '6': return 6; break;
case '7': return 7; break;
case '8': return 8; break;
case '9': return 9; break;
case 'a': case 'A': return 10; break;
case 'b': case 'B': return 11; break;
case 'c': case 'C': return 12; break;
case 'd': case 'D': return 13; break;
case 'e': case 'E': return 14; break;
case 'f': case 'F': return 15; break;
case 'x': case 'X': return 16; break;
case '.': case 0: return 17; break;
case ' ': case '\t': case '\n': return 18; break;
default: return 19;
}
}

unsigned long iptolong(const char *ip)
{
unsigned long ipval=0;
unsigned long octet=0;
int base=10;

state_t state = start;
do
{
action_t action = actionTable[state][mapchar(*ip)];
switch(action)
{
case shft:
octet = octet * base + mapchar(*ip);
break;

case eval:
ipval <<= 8;
ipval += octet;
octet = 0;
break;

default:
break;
}

state = stateTable[state][mapchar(*ip)];
switch(state)
{
case dec: base = 10; break;
case oct: base = 8; break;
case hex: base = 16; break;
}
} while(*ip++);

return ipval;

}

int main(int argc, char **argv)
{
unsigned long ipval;
ipval = iptolong(argv[1]);
printf("long value of \"%s\" is %lu (%x)\n", argv[1], ipval,
ipval);

return 0;
}

Feb 3 '06 #35

"Phil Carmody" wrote:
"John F" writes:
reset^=reset;
Are you hoping that your compiler will turn that into
xor eax,eax
and thus be faster than
mov eax, 0


maybe... depends on the optimizer... That way I encourage the optimizer into

mine does generate two 3 byte instructions...
mov eax, dword ptr -0x4[ebp]
xor dword ptr -0x4[ebp],eax

versus one seven byte instruction...
mov dword ptr -0x4[ebp],0x00000000
Or do you just think that more is more?


not always :-) depends on the object...

regards
John F(dot)
Feb 3 '06 #36
On 2006-02-03, John F <sp**@127.0.0.1 > wrote:

"Phil Carmody" wrote:
"John F" writes:
reset^=reset;


Are you hoping that your compiler will turn that into
xor eax,eax
and thus be faster than
mov eax, 0


maybe... depends on the optimizer... That way I encourage the optimizer into

mine does generate two 3 byte instructions...
mov eax, dword ptr -0x4[ebp]
xor dword ptr -0x4[ebp],eax

versus one seven byte instruction...
mov dword ptr -0x4[ebp],0x00000000


How about just passing -Os [or whatever "optimize for size" option] to
the compiler and letting it make that decision? Your "two 3 byte
instructions" also waste a register, and probably take twice as long to
execute, if not longer
Feb 3 '06 #37

"Jordan Abel" wrote:
On 2006-02-03, John F <sp**@127.0.0.1 > wrote:

"Phil Carmody" wrote:
"John F" writes:
reset^=reset;

Are you hoping that your compiler will turn that into
xor eax,eax
and thus be faster than
mov eax, 0
maybe... depends on the optimizer... That way I encourage the optimizer
into

mine does generate two 3 byte instructions...
mov eax, dword ptr -0x4[ebp]
xor dword ptr -0x4[ebp],eax

versus one seven byte instruction...
mov dword ptr -0x4[ebp],0x00000000


How about just passing -Os [or whatever "optimize for size" option] to
the compiler and letting it make that decision?


-Os is OW ... it doesn't make the decision to translate =0 with x^x ...
There seems to be slight a difference in the semantics tree ... dunno. Have
to dig into that :-) quite interesting why ... or rather why not.
Your "two 3 byte
instructions" also waste a register, and probably take twice as long to
execute, if not longer


BC3.1 does generate xor cx,cx ... that's simple and fast... it will depent
largely on the instruction set that is used.
I'll ask an OW expert how to get the compiler to use ecx ... since it gets
push/pop-ed ... weird stuff.

regards
John
Feb 3 '06 #38

John Bode wrote:
[snip]
Whitespace embedded within the octet token ("1 27.0.0.1")
will cause the function to return 0.


=sigh=

Actually, that's not true. I was thinking of a slightly different
version of this code that I was working on before settling on this
solution. What you should get back in this case is the value of
whatever octets have been processed up to this point.

Again, no error handling in this version.

Feb 3 '06 #39
On 2006-02-03, John F <sp**@127.0.0.1 > wrote:

"Jordan Abel" wrote:
On 2006-02-03, John F <sp**@127.0.0.1 > wrote:

"Phil Carmody" wrote:
"John F" writes:
> reset^=reset;

Are you hoping that your compiler will turn that into
xor eax,eax
and thus be faster than
mov eax, 0

maybe... depends on the optimizer... That way I encourage the optimizer
into

mine does generate two 3 byte instructions...
mov eax, dword ptr -0x4[ebp]
xor dword ptr -0x4[ebp],eax

versus one seven byte instruction...
mov dword ptr -0x4[ebp],0x00000000
How about just passing -Os [or whatever "optimize for size" option] to
the compiler and letting it make that decision?


-Os is OW ... it doesn't make the decision to translate =0 with x^x ...
There seems to be slight a difference in the semantics tree ... dunno. Have
to dig into that :-) quite interesting why ... or rather why not.
Your "two 3 byte
instructions" also waste a register, and probably take twice as long to
execute, if not longer


BC3.1 does generate xor cx,cx ... that's simple and fast... it will depent
largely on the instruction set that is used.


The problem is that your variable is in memory, so storing an 0 literal
to it is faster than the "xor trick"
I'll ask an OW expert how to get the compiler to use ecx ... since it gets
push/pop-ed ... weird stuff.


It sounds like you don't really understand asm
Feb 3 '06 #40

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

Similar topics

4
5433
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
2155
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
3123
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
2083
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?
1
10038
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
8934
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7460
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6715
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5354
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
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
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
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2850
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.