Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

Finding and Reporting Network Addresses

Problem

You want to look up a host’s address name or number, or get the address at the other end of a network connection.

Solution

Get an InetAddress object.

Discussion

The InetAddress object represents the Internet address of a given computer or host. There are no public constructors; you obtain an InetAddress by calling the static byName( ) method, passing in either a hostname like www.darwinsys.com or a network address as a string, like “1.23.45.67”. All the “lookup” methods in this class can throw the checked exception UnknownHostException, which must be caught or declared on the calling method’s header. None of these methods actually contacts the remote host, so they do not throw the other exceptions related to network connections.

The method getHostAddress( ) gives you the numeric IP address (as a string) corresponding to the InetAddress. The inverse is getHostName( ) , which reports the name of the InetAddress. This can be used to print the address of a host given its name, or vice versa:

// From InetAddrDemo.java 
String ipNumber = "123.45.67.89";
String hostName = "www.darwinsys.com"; 
System.out.println(hostName + "'s address is " + 
    InetAddress.byName(hostName).getHostAddress(  ));
 System.out.println(ipNumber + "'s name is " + 
    InetAddress.byName(ipNumber).getHostName(  ));

You can also get an InetAddress from a Socket by calling its getInetAddress( ) method. You can construct a Socket using an InetAddress instead of a hostname string. ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata