Constructing an InetAddress from a byte[]
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.
Code:
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:
Re: Constructing an InetAddress from a byte[]
use getAddress to get the bytes:
Code:
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());
}
}
Re: Constructing an InetAddress from a byte[]
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?
Code:
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());
Re: Constructing an InetAddress from a byte[]
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:
Code:
Process p = Runtime.Runtime().exec("ipconfig");
Maybe somehow you could get it using net commands.
Re: Constructing an InetAddress from a byte[]
Quote:
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:
Re: Constructing an InetAddress from a byte[]
What exactly is wrong with using an InetAddress?
Re: Constructing an InetAddress from a byte[]
Re: Constructing an InetAddress from a byte[]
Why do you need to construct an InetAddress from a byte[] that comes from who-knows-where?
Re: Constructing an InetAddress from a byte[]
It was a question that was asked by someone. Why they would want to i have no idea. :lol: