• Post Reply Bookmark Topic Watch Topic
  • New Topic

byte[] for IP address storage????

 
Bob Ruth
Ranch Hand
Posts: 320
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the InetAddress class there are several methods that retrieve IP addresses. The address is stored in a byte array, 4 bytes for a IP4 address.

How does that work?

I tried using getByAddress() where you pass both the string and the byte array. Problem is, a byte is a signed value so any attempt to stick a value > 127 in an address bytes draws a compiler error .... loss of precision. When I call getByName() on a known address string, the address that comes back in the byte array WILL print values over 127. Like.....241 shows up as 241.

Why would they have ever used a byte array to hold an 8 bit unsigned value? How is it that the API calls can store numbers > 127 into the byte array but I can't?

I have GOT to be missing something here.... I just don't know what it is.....

Help???
 
Joe Ess
Bartender
Posts: 9362
11
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Bob Ruth:
The address is stored in a byte array, 4 bytes for a IP4 address.


I'm looking at the source for InetAddress in JDK 1.6.0_05 and the internal storage is an int:

There are getters and setters for 4-byte arrays.

Problem is, a byte is a signed value so any attempt to stick a value > 127 in an address bytes draws a compiler error .... loss of precision.


This is called a "narrowing conversion". You have to reassure the compiler that you know what you are doing and the data will fit in a byte with a cast:
 
Bob Ruth
Ranch Hand
Posts: 320
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, sir! I knew that I had to be missing something elementary and I just didn't think of that in the light of a conversion. Thanks!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!