|
The
java.net.InetAddress
class represents IP addresses.
It works with the host
name (String)
and IP address
(int)
of an Internet host.
InetAddress
has several useful methods for obtaining host names and IP addresses.
Here are some demos, some derived from those in
the book
Java Network Programming, by E. R.
Harold.
The first one shows how to get the IP address from the host name or, vice
versa, the host name from the IP address.
Note
that getByName(String
str)
returns the HostName/IP_Address
pair given
either the host name or the IP address:
|
oreilly.java

|
|
import java.net.*;
class oreilly
{
public
static void main (String args[]) {
InetAddress address=null;
System.out.println("From Domain name:");
try {
address = InetAddress.getByName("www.oreilly.com");
System.out.println(
" InetAddress for
www.oreilly.com = "+address);
}
catch (UnknownHostException e) {
System.out.println(" Could
not find www.oreilly.com");
System.exit(0);
}
String IPstr="host address string.";
System.out.println("From IP number:");
try {
IPstr = address.getHostAddress();
address = InetAddress.getByName(IPstr);
System.out.println(
" InetAddress
for "+IPstr+" = "+address);
}
catch (UnknownHostException e) {
System.out.println(" Could
not find "+IPstr);
}
}
}
|
Here
get the local host name and IP address:
|
myAddress.java
>
java myAddress
This computer's address = foo/130.237.217.62
|
|
import
java.net.*;
class
myAddress {
public static void main (String args[]) {
try {
InetAddress
address = InetAddress.getLocalHost();
System.out.println("This computer's
address = " +address);
} catch (UnknownHostException e) {
System.out.println(
"Could not find this
computer's address.");
}
}
}
|
This
applet presents the local host and IP address:
|
|
| mport
java.net.*;
public
class MyAddressApplet extends java.applet.Applet
{
String msg;
private InetAddress myAddress = null;
/*--------------------------------------------------------*/
public void init(){
try{
myAddress = InetAddress.getLocalHost();
msg = "Local
IP address = " + myAddress.toString();
} catch (UnknownHostException e){
System.out.println("Failed to getLocalHost");
msg
= "Local
IP address is unknown";
}
}
/*---------------------------------------------------------*/
public void paint (java.awt.Graphics
g){
g.drawString(Msg, 10, 15);
}
}
|
Finally,
this application returns the IP address if given a host name, or returns
the host name if given the IP address:
|
GetAddress.java

|
|
import java.net.*;
class GetAddress
{
public
static void main (String args[]) {
// Check on argument
if( args.length != 1){
System.out.println("Need IP or Host
name argument!");
System.exit(0);
}
try {
InetAddress
address = InetAddress.getByName(args[0]);
System.out.println("This computer's address = " + address);
}
catch (UnknownHostException e) {
System.out.println(
"Could not find this computer's
address.");
}
}
}
|
|