Click to See Complete Forum and Search --> : Constructing an InetAddress from a byte[]
Dillinger4
Jun 14th, 2005, 10:20 PM
After reading a question on this topic over at jguru i tried to figure out how an InetAddress object could be constructed using an ip address in the form of a byte[].
Figuring the ip address is most likely a String(say if a host is resolved to an IpAddress) i tried to construct a byte array to make another InetAddress object but the code simply fails because the byte array is too long.
InetAddress inet = InetAddress.getByName("www.sun.com");
String ip = inet.getHostAddress();
System.out.println(ip);
InetAddress inet2 = InetAddress.getByAddress(ip.getBytes());
System.out.println(inet2.getHostAddress());
Even hardcoding the values of the ip address into a byte[] wouldn't work since java dosen't have unsigned primative types. :sick:
System_Error
Jun 15th, 2005, 08:58 AM
use getAddress to get the bytes:
import java.net.*;
class Testing
{
public static void main(String[] args) throws Exception
{
InetAddress inet = InetAddress.getByName("www.sun.com");
byte[] ip = inet.getAddress();
InetAddress inet2 = InetAddress.getByAddress(ip);
System.out.println(inet2.getHostAddress());
}
}
Dillinger4
Jun 15th, 2005, 06:25 PM
Works. Now getAddress() returns a byte[] but that's only from a InetAddress object that has been created already. So what would we do without it?
InetAddress inet = InetAddress.getByName("www.sun.com");
System.out.println(inet.getHostName());
System.out.println(inet.getHostAddress());
InetAddress inet2 = InetAddress.getByAddress(inet.getAddress());
System.out.println(inet2.getHostName());
System.out.println(inet2.getHostAddress());
System_Error
Jun 15th, 2005, 09:20 PM
So your wanting to get the IP Address without an InetAddress object to read the bytes from? If so, I don't think it's possible. I've looked into the URL class, but it doesn't have anything, even though it does support the ipaddress as an argument. The only other way I can think of is getting some external process:
Process p = Runtime.Runtime().exec("ipconfig");
Maybe somehow you could get it using net commands.
Dillinger4
Jun 15th, 2005, 10:41 PM
Posted by System_Error
Maybe somehow you could get it using net commands.
Perhaps. Ill have to look into it. Thanks for the help. :thumb:
CornedBee
Jun 17th, 2005, 11:44 AM
What exactly is wrong with using an InetAddress?
Dillinger4
Jun 17th, 2005, 01:26 PM
hugh? :ehh:
CornedBee
Jun 17th, 2005, 02:04 PM
Why do you need to construct an InetAddress from a byte[] that comes from who-knows-where?
Dillinger4
Jun 17th, 2005, 06:02 PM
It was a question that was asked by someone. Why they would want to i have no idea. :lol:
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.