Java Reference
In-Depth Information
Here's the result:
%
java ReverseTest
oreilly.com
The
getHostAddress()
method returns a string containing the dotted quad format of
the IP address.
Example 4-4
uses this method to print the IP address of the local machine
in the customary format.
Example 4-4. Find the IP address of the local machine
import
java.net.*
;
public
class
MyAddress
{
public
static
void
main
(
String
[]
args
)
{
try
{
InetAddress
me
=
InetAddress
.
getLocalHost
();
String
dottedQuad
=
me
.
getHostAddress
();
System
.
out
.
println
(
"My address is "
+
dottedQuad
);
}
catch
(
UnknownHostException
ex
)
{
System
.
out
.
println
(
"I'm sorry. I don't know my own address."
);
}
}
}
Here's the result:
%
java MyAddress
My address is 152.2.22.14.
Of course, the exact output depends on where the program is run.
If you want to know the IP address of a machine (and you rarely do), then use the
getAddress()
method, which returns an IP address as an array of bytes in network byte
order. The most significant byte (i.e., the first byte in the address's dotted quad form) is
the first byte in the array, or element zero. To be ready for IPv6 addresses, try not to
assume anything about the length of this array. If you need to know the length of the
array, use the array's
length
field:
InetAddress
me
=
InetAddress
.
getLocalHost
();
byte
[]
address
=
me
.
getAddress
();
The bytes returned are unsigned, which poses a problem. Unlike C, Java doesn't have
an unsigned byte primitive data type. Bytes with values higher than 127 are treated as
negative numbers. Therefore, if you want to do anything with the bytes returned by
getAddress()
, you need to promote the bytes to
int
s and make appropriate adjust‐
ments. Here's one way to do it:
int
unsignedByte
=
signedByte
<
0
?
signedByte
+
256
:
signedByte
;