Java Reference
In-Depth Information
This version does no real error reporting, but a version called ConnectFriendly does; we'll
see this version in Handling Network Errors .
See Also
Java supports other ways of using network applications. You can also open a URL and read
from it (see URI, URL, or URN? ). You can write code so that it will run from a URL, when
opened in a web browser, or from an application.
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. It has
no public constructors; you obtain an InetAddress by calling the static getByName() meth-
od, 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
UnknownHostException (a subclass of java.io.IOException ), which must be caught or
declared on the calling method's header. None of these methods actually contact 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) correspond-
ing 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:
public
public class
class InetAddrDemo
InetAddrDemo {
public
public static
static void
void main ( String [] args ) throws
throws IOException {
Search WWH ::




Custom Search