Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

convert ip address

Status
Not open for further replies.

patlv23

Programmer
May 23, 2002
31
0
0
PH
is there a way to convert ip address returned by gethostbyname (hex?) to dot notation (12.12.12.12) and vice versa? i'm using unix c. thanks in advance
 
Hi,
the value is a longword ( you can print it in Hex,Dec,Bin).

When you see 192.168.10.1, printed in Hex comes:

C0.a8.0a.01

If you don't writes dots comes C0a80a01: if you translate
it by a desktop calculator comes 3232238081 in dec.

Well, this does not answer to your programming question,
but it is useful to understand what you managing.

In programs you can use many ways to obtain results:

1) look on your platform and maby you find a routine.
2) use a struct/union
3) write iterative code

The struct you can use is:

#define u_char unsigned char
#define u_short unsigned short
#define u_long unsigned long

struct in_addr
{
union
{
struct { u_char s_b1,s_b2,s_b3,s_b4; } S_un_b;
struct { u_short s_w1,s_w2; } S_un_w;
u_long S_addr;
} ;
} S_un;


S_un.S_addr = gethostbyname( "fred" ) ;
printf( "%d.%d.%d.%d\n",
S_un.S_un_b.s_b4,
S_un.S_un_b.s_b3,
S_un.S_un_b.s_b2,
S_un.S_un_b.s_b1 ) ;

Be careful: in some platform b1..b4 may be changed.


Another approach is to shift bytes to go in both directs.


unsigned char ipc[4]={192,168,10,1};
unsigned long ipl=0, mask;
int i,j;

for( i=0 ; i<4 ; i++ )
{
printf( &quot;%d%c&quot;, ipc, i==3 ? '\n' : '.' ) ;
}

for( i=0 ; i<4 ; i++ )
{
j=3-i;
ipl+= ipc << (8*j) ;
}
printf( &quot;ipl=%u\n&quot;, ipl ) ;

THE reverse..

unsigned long x,y;

for( i=0 ; i<4 ; i++ )
{
j=3-i;
mask= 0xFF << (8*j) ;
y= ipl & mask ;
x = y >> 8*j ;
ipc= x ;
printf( &quot;%08x %08x %08x %3d\n&quot;, mask, y,x, ipc) ;
}

x and y vars are used to understand better the mechanism.


BYE
 
You should be able to use the inet_ntoa function. It returns the IP dot-formatted. See man inet_ntoa for more info. //Daniel
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top