Course Content
Java RMI
Java Inner class
Java File class
Layout Managers
Java Programming Tutorial
About Lesson

Networking in Java

Java is a premier language for network programming. package encapsulate large number of classes and interface that provides an easy-to use means to access network resources. Here are some important classes and interfaces of package.

Java Networking Classes

CacheRequest CookieHandler
CookieManager Datagrampacket
Inet Address ServerSocket
Socket DatagramSocket
Proxy URL

Java Networking Interfaces

CookiePolicy CookieStore
FileNameMap SocketOption
InetAddress ServerSocket
SocketImplFactory ProtocolFamily


Inet Address encapsulates both numerical IP address and the domain name for that address. Inet address can handle both IPv4 and Ipv6 addresses. Inet Address class has no visible constructor. To create an inet Address object, you have to use Factory methods.

Three commonly used Inet Address factory methods are.

  1. static InetAddress getLocalHost() throws UnknownHostException
  2. static InetAddress getByName (String hostname) throws UnknownHostException
  3. static InetAddress[ ] getAllByName (String hostname) throws UnknownHostException

InetAddress subclasses

Example using InetAddress class

class Demo
  public static void main(String[] args) throws 
UnknownHostException { InetAddress address = InetAddress.getLocalHost(); System.out.println(address); address = InetAddress.getByName
(""); System.out.println(address); InetAddress sw[] = InetAddress.getAllByName
(""); for(int i=0; i< sw.length; i++) { System.out.println(sw[i]); } } }


Socket and ServerSocket Class

Socket is foundation of modern networking, a socket allows single computer to serve many different clients at once. Socket establishes connection through the use of port, which is a numbered socket on a particular machine. Socket communication takes place via a protocol. Socket provides communication mechanism between two computers using TCP. There are two kind of TCP sockets in Java. One is for server and other is for client.

  • ServerSocket is for servers.
  • Socket class is for client.

URL class

Java URL Class present in package, deals with URL (Uniform Resource Locator) which uniquely identify or locate resources on internet.


Important Methods of URL class

  • getProtocol() : Returns protocol of URL
  • getHost() : Returns hostname(domain name) of URL
  • getPort() : Returns port number of URL
  • getFile() : Returns filename of URL

Program using URL class

class Demo
  public static void main(String[] arg) throws 
MalformedURLException { URL hp = new URL("
); System.out.println(hp.getProtocol()); System.out.println(hp.getFile()); } }

http /index

error: Content is protected !!