• Post Reply Bookmark Topic Watch Topic
  • New Topic

InetAddress class

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the InetAddress class of java.net package there is a method
byte[] getAddress()
As this method returns a byte array it is not able to give correct IP addresses above the no. 127.
Is this an error in the api or am I not using it properly.. please see the code below for reference
import java.net.*;
class trial16{
public static void main(String arg[])throws UnknownHostException{
InetAddress i = InetAddress.getByName("www.postmark.net");
byte [] b = i.getAddress();
System.out.println(i.getHostAddress());
for (int j=0; j<b.length; j++){>
System.out.print(b[j]+".");
}
}
}
output of the program is
207.244.122.71
-49.-12.122.71.
 
Pawel Veselov
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Did you ever heard of sign bit ?
In Java there is no unsigned types, so you what you see is signed representation of eight-bit set bytes.
207 = 256 - 49
244 = 256 - 12
122 and 71 are less then 128, so they have eight bit unset.
That's the trick.

------------------
With best of best regards, Pawel S. Veselov ( aka Black Angel )
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry my question was miss leading. I know why it got printed as -49 etc. I want to ask, shouldnt the method be returning an array of shorts or ints instead of bytes, since with bytes the result would not be as expected.
 
Pawel Veselov
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think this will be a good idea. The range is 0-255, that is byte
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!