IP: long-> InetAddress

V

vertigo

Hello
i have received ip address in long and i want to convert it
to InetAddress. For example, i have:
167772939 and i want to receive InetAddress which point's to 10.0.3.11.

How can i do it ?

Thanx
Michal
 
M

Marco Schmidt

vertigo:
i have received ip address in long and i want to convert it
to InetAddress. For example, i have:
167772939 and i want to receive InetAddress which point's to 10.0.3.11.

The operations shift right (>>) and bitwise and (&) can be used to
accomplish just that. Alternatively, division (/) and modulus (%).

I have recently written such a method:

public static String fromNumerical(long address)
{
StringBuffer sb = new StringBuffer();
for (int i = 0, shift = 24; i < 4; i++, shift -= 8)
{
long value = (address >> shift) & 0xff;
sb.append(value);
if (i != 3)
{
sb.append('.');
}
}
return sb.toString();
}

If there is something like that in the runtime library, I don't know
it.

Regards,
Marco
 
R

Roedy Green

i have received ip address in long and i want to convert it
to InetAddress. For example, i have:
167772939 and i want to receive InetAddress which point's to 10.0.3.11.

How can i do it ?

see http://mindprod.com/jgloss/ip.html


public class DottedQuad
{
/**
* display an IP as a dotted quad xxx.xxx.xxx.xxx
*/
public static String dottedQuad ( int ip )
{
StringBuffer sb = new StringBuffer( 15 );
for ( int shift=24; shift >0; shift-=8 )
{
// process 3 bytes, from high order byte down.
sb.append( Integer.toString( (ip >>> shift) & 0xff ));
sb.append('.');
}
sb.append(Integer.toString( ip & 0xff ));
return sb.toString();
}

/**
* test harness
*
* @param args not used
*/
public static void main ( String[] args )
{
System.out.println( dottedQuad( 0x01ff0010 ) );
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top