0% found this document useful (0 votes)
90 views26 pages

Chapter-4 Network Programming: Client-Server Architecture

The document discusses network programming in Java. It describes how sockets allow programs to communicate across a network using protocols like TCP and UDP. It explains the client-server model and key classes like ServerSocket and Socket that are used for network programming in Java.

Uploaded by

sample name
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
90 views26 pages

Chapter-4 Network Programming: Client-Server Architecture

The document discusses network programming in Java. It describes how sockets allow programs to communicate across a network using protocols like TCP and UDP. It explains the client-server model and key classes like ServerSocket and Socket that are used for network programming in Java.

Uploaded by

sample name
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Chapter-4

Network programming
1. What is Network?
2. Client-Server Architecture
 Server: - an application that runs on the host computer that provides a means of
connection and Useful information once a connection is established.
 Client: - application(s) running on different computer(s) that seek to establish a
connection and request computation/ information from the server.

3. What is a Socket?

The term network programming refers to writing programs that execute across multiple devices
(computers), in which the devices are all connected to each other using a network. Network
programming fall into two categories: - the sockets API and tools for working with Uniform
Resource Locators (URLs). 
A socket is a communication end point. Sockets are popularly used in client/server
computing. Socket is a door between application process and end-to-end-transport protocol. A
socket on one computer can “talk” to a socket on another computer via communication channel. 
Socket communication takes place via a protocol. Internet Protocol (IP) is a low-level routing
protocol that breaks data into small packets and sends them to an address across a network. Java
support two protocols:-
 Transmission Control Protocol (TCP) is a higher-level protocol that manages to robustly
string together these packets, sorting and retransmitting them as necessary to reliably
transmit data. TCP is used for reliable stream-based I/O across the network.
 User Datagram Protocol (UDP) can be used directly to support fast, connectionless,
unreliable transport of packets. UDP supports a simpler, point-to-point datagram-oriented
model.

4. Host, Port Number and Internet addresses


In client/server communication, each Host needs an IP address and a port number.
Host: - The IP address of the machine we want to talk to.
Port Number
 A number identifying a process on the host. Once a connection has been established,
a higher-level protocol ensues, which is dependent on which port you are using.
 This address is subdivided into 65,536 ports
 Many services run on well-known ports. For example:- TCP/IP reserves the lower 1,024
ports for specific protocols. Many of these will seem familiar to you if you have spent
any time surfing the Internet. Port number 21 is for FTP; 23 is for Telnet; 25 is for e-
mail; 43 is for whois; 80 is for HTTP; 119 is for netnews—and the list goes on. It
is up to each protocol to determine how a client should interact with the port.
Internet addresses
 Every host on the Internet is identified by a unique Address, four-byte Internet Protocol
(IP) address.
 This is written in dotted format like 199.1.32.90 where each byte is an unsigned integer
between 0 and 255.
Originally, all Internet addresses consisted of 32-bit values, organized as four 8-bit
values. This address type was specified by IPv4 (Internet Protocol, version 4). However, a new
addressing scheme, called IPv6 (Internet Protocol, version 6) has come into play. IPv6 uses a
128-bit value to represent an address, organized into eight 16-bit chunks.
Just as the numbers of an IP address describe a network hierarchy, the name of an
Internet address, called its domain name, describes a machine’s location in a name space.
For example, www.HerbSchildt.com is in the COM top-level domain (reserved for U.S.
Commercial sites); it is called HerbSchildt, and www identifies the server for web requests.
An Internet domain name is mapped to an IP address by the Domain Naming Service
(DNS). This enables users to work with domain names, but the Internet operates on IP
Addresses.
The Networking Classes and Interfaces

Java provides a set of classes, defined in a package called java.net, to enable the rapid
development of network applications. Key classes, interfaces, and exceptions in java.net package
are:-
The Classes
 ContentHandler  DatagramPacket
 DatagramSocket  ContentHandlerFactory
 DatagramSocketImpl  FileNameMap
 HttpURLConnection  SocketImplFactory
 InetAddress  URLStreamHandlerFactory
 MulticastSocket Exceptions
 ServerSocket  BindException
 Socket  ConnectException
 SocketImpl  MalformedURLException
 URL  NoRouteToHostException
 URLConnection  ProtocolException
 URLEncoder  SocketException
 URLStreamHandler  UnknownHostException
The Interfaces  UnknownServiceException

InetAddress
The InetAddress class is used to encapsulate both the numerical IP address and the
domain name for that address. You interact with this class by using the name of an IP host,
which is more convenient and understandable than its IP address. The InetAddress class hides
the number inside. InetAddress can handle both IPv4 and IPv6 addresses.

Factory Methods

The InetAddress class has no visible constructors. To create an InetAddress object, you have to
use one of the available factory methods. Factory methods are merely a convention
whereby static methods in a class return an instance of that class. Three commonly used
InetAddress factory methods are shown here:-

 static InetAddress getLocalHost( ) throws UnknownHostException :- The


getLocalHost( ) method simply returns the InetAddress object that represents the local
host.
 static InetAddress getByName(String hostName) throws
UnknownHostException:- The getByName( ) method returns an InetAddress for a host
name passed to it.
 static InetAddress[ ] getAllByName(String hostName) throws
UnknownHostException:- The getAllByName( ) factory method returns an array of
InetAddresses that represent all of the addresses that a particular name resolves to.
N.B:- If these methods are unable to resolve the host name, they throw an
UnknownHostException.

Example:- // Demonstrate InetAddress.

import java.net.*;

class InetAddressTest

public static void main(String args[]) throws UnknownHostException {

InetAddress Address = InetAddress.getLocalHost();

System.out.println(Address);

Address = InetAddress.getByName("www.HerbSchildt.com");

System.out.println(Address);

InetAddress SW[] = InetAddress.getAllByName("www.nba.com");

for (int i=0; i<SW.length; i++)

System.out.println(SW[i]);

}}

Output

default/166.203.115.212

www.HerbSchildt.com/216.92.65.4

www.nba.com/216.66.31.161

www.nba.com/216.66.31.179

Example2:- Let's see a simple example of InetAddress class to get ip address of


www.javatpoint.com website.

import java.io.*;  
import java.net.*;  
public class InetDemo{  
public static void main(String[] args){  
try{  
InetAddress ip=InetAddress.getByName("www.javatpoint.com");  
  System.out.println("Host Name: "+ip.getHostName());  
System.out.println("IP Address: "+ip.getHostAddress());  
}
catch(Exception e){System.out.println(e);}  
}  }  

Output:

Host Name: www.javatpoint.com


IP Address: 206.51.231.148

5. TCP Sockets
TCP is a reliable point-to-point communication protocol that client-server applications on the
Internet use to communicate with each other. To communicate over TCP, a client program and a
server program establish a connection to one another. The client and server programs both bind a
socket to each end of the connection and communicate by reading and writing to those
sockets. There are some commonly used socket classes in the java.net packages.
Java uses Socket for clients and ServerSocket for servers in a connection-oriented
environment.
Server Sockets: - To create Server sockets java uses ServerSocket class. This class has the
following constructors:

public ServerSocket(int port) throws IOException

Attempts to create a server socket bound to the specified port. An exception


occurs if the port is already bound by another application.

public ServerSocket(int port, int backlog) throws IOException


Similar to the previous constructor, the backlog parameter specifies how many
incoming clients to store in a wait queue.

public ServerSocket(int port, int backlog, InetAddress address) throws


IOException
Similar to the previous constructor, the InetAddress parameter specifies the
local IP address to bind to. The InetAddress is used for servers that may have
multiple IP addresses, allowing the server to specify which of its IP addresses
to accept client requests on

public ServerSocket() throws IOException


Creates an unbound server socket. When using this constructor, use the bind()
method when you are ready to bind the server socket

Methods Description

public int getLocalPort()

Returns the port that the server socket is listening on. This method is useful if
you passed in 0 as the port number in a constructor and let the server find a
port for you.

public Socket accept() throws IOException


Waits for an incoming client. This method blocks until either a client connects
to the server on the specified port or the socket times out, assuming that the
time-out value has been set using the setSoTimeout() method. Otherwise, this
method blocks indefinitely

public void setSoTimeout(int timeout)


Sets the time-out value for how long the server socket waits for a client during
the accept().

public void bind(SocketAddress host, int backlog)


Binds the socket to the specified server and port in the SocketAddress object.
Use this method if you instantiated the ServerSocket using the no-argument
constructor.

Client Sockets: -To create client sockets java uses Socket class. This class has following two
constructors:

public Socket(String host, int port) throws UnknownHostException,


IOException.
This method attempts to connect to the specified server at the specified port. If
this constructor does not throw an exception, the connection is successful and
the client is connected to the server.

public Socket(InetAddress host, int port) throws IOException


This method is identical to the previous constructor, except that the host is
denoted by an InetAddress object.

public Socket(String host, int port, InetAddress localAddress, int


localPort) throws IOException.
Connects to the specified host and port, creating a socket on the local host at
the specified address and port.

public Socket(InetAddress host, int port, InetAddress localAddress, int


localPort) throws IOException.
This method is identical to the previous constructor, except that the host is
denoted by an InetAddress object instead of a String

public Socket()
Creates an unconnected socket. Use the connect() method to connect this
socket to a server.

Methods Description

public void connect(SocketAddress host, int timeout) throws


IOException

This method connects the socket to the specified host. This method is needed
only when you instantiated the Socket using the no-argument constructor.

public InetAddress getInetAddress()


This method returns the address of the other computer that this socket is
connected to.

public int getPort()


Returns the port the socket is bound to on the remote machine.

public int getLocalPort()


Returns the port the socket is bound to on the local machine.

public SocketAddress getRemoteSocketAddress()


Returns the address of the remote socket.

public InputStream getInputStream() throws IOException


Returns the input stream of the socket. The input stream is connected to the
output stream of the remote socket.

public OutputStream getOutputStream() throws IOException


Returns the output stream of the socket. The output stream is connected to the
input stream of the remote socket

public void close() throws IOException


Closes the socket, which makes this Socket object no longer capable of
connecting again to any server

Life cycles of the client/server model

Life cycle of a client:

1. A client socket is created using Socket()


2. The socket connects to a remote host
3. Data exchange between local and remote hosts.
o an input stream to read data
o an output stream to send data to server.
4. Connection terminates after transmission of data is complete.

Life cycle of a server:

1. A server socket is created on a particular port using ServerSocket().


2. The socket listens for an incoming connection request from a client on the port using
accept().
3. Data exchange after connection is made.
o The server and client interact according to an agreed upon protocol.
4. Either or both of getInputStream() and getOutputStream(), depending on the type of
server, is called to exchange data with the client.
5. The server, the client, or both closes the connection upon completion of data exchange.
6. The server returns to step 2 and waits for the next connection request.

Example: Java client (TCP)

importjava.io.*;
importjava.net.*;
classTCPClient {
    publicstaticvoidmain(String argv[]) throwsException
    {
        String sentence;
        String modifiedSentence;
        BufferedReaderinFromUser =
          newBufferedReader(newInputStreamReader(System.in));
        Socket clientSocket = newSocket("hostname", 6789);
        DataOutputStreamoutToServer =
          newDataOutputStream(clientSocket.getOutputStream());
 
        BufferedReaderinFromServer =
          newBufferedReader(new
          InputStreamReader(clientSocket.getInputStream()));
        sentence = inFromUser.readLine();
        outToServer.writeBytes(sentence + '\n');
        modifiedSentence = inFromServer.readLine();
        System.out.println("FROM SERVER: "+ modifiedSentence);
        clientSocket.close();
     }}

Example: - Java server (TCP)

importjava.io.*;
importjava.net.*;
classTCPServer {
  publicstaticvoidmain(String argv[]) throwsException
    {
      String clientSentence;
      String capitalizedSentence;
      ServerSocketwelcomeSocket = newServerSocket(6789);
       while(true) {
             Socket connectionSocket = welcomeSocket.accept();
           BufferedReaderinFromClient =
              newBufferedReader(new
              InputStreamReader(connectionSocket.getInputStream()));
           DataOutputStream  outToClient =
             newDataOutputStream(connectionSocket.getOutputStream());
           clientSentence = inFromClient.readLine();
           capitalizedSentence = clientSentence.toUpperCase() + '\n';
           outToClient.writeBytes(capitalizedSentence);
        }}}
Example of Java Socket Programming (Read-Write both side)

In this example, client will write first to the server then server will receive and print the
text. Then server will write to the client and client will receive and print the text. The step
goes on.

File: MyServer.java

import java.net.*;  
import java.io.*;  
class MyServer{  
public static void main(String args[])throws Exception{  
ServerSocket ss=new ServerSocket(3333);  
Socket s=ss.accept();  
DataInputStream din=new DataInputStream(s.getInputStream());  
DataOutputStream dout=new DataOutputStream(s.getOutputStream());  
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));  
  
String str="",str2="";  
while(!str.equals("stop")){  
str=din.readUTF();  
System.out.println("client says: "+str);  
str2=br.readLine();  
dout.writeUTF(str2);  
dout.flush();  
}  
din.close();  
s.close();  
ss.close();  
}}  

File: MyClient.java

import java.net.*;  
import java.io.*;  
class MyClient{  
public static void main(String args[])throws Exception{  
Socket s=new Socket("localhost",3333);  
DataInputStream din=new DataInputStream(s.getInputStream());  
DataOutputStream dout=new DataOutputStream(s.getOutputStream());  
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));  
  
String str="",str2="";  
while(!str.equals("stop")){  
str=br.readLine();  
dout.writeUTF(str);  
dout.flush();  
str2=din.readUTF();  
System.out.println("Server says: "+str2);  
}  
  
dout.close();  
s.close();  
}}

6. UDP Socket
Some applications that you write to communicate over the network will not require the reliable,
point-to-point channel provided by TCP. Rather, your applications might benefit from a mode of
communication that delivers independent packages of information.
The DatagramPacket and DatagramSocket classes in thejava.net package implement system-
independent datagram communication using UDP.
UDP is contained in two classes:-
 java.net.DatagramSocket
 java.net.DatagramPacket

6.1. DatagramSocket class


The DatagramSocket class represents a connection-less socket for sending and receiving
datagram packets. A datagram is information but there is no guarantee of its content, arrival or
arrival time.
Constructors of DatagramSocket class
 DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it
with the available Port Number on the localhost machine.
 DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and
binds it with the given Port Number.
 DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a
datagram socket and binds it with the specified port number and host address.
The class DatagramSocket supports various methods that can be used for transmitting or
receiving data a datagram over the network. The two key methods are:
 void send(DatagramPacket p):- Sends a datagram packet from this socket.
 void receive(DatagramPacket p):- Receives a datagram packet from this socket.

6.2. Datagram packet: - A datagram is an independent, self-contained message sent over the
network whose arrival, arrival time, and content are not guaranteed.

Datagram packets are used to implement a connectionless packet delivery service supported by
the UDP protocol. Each message is transferred from source machine to destination based on
information contained within that packet. That means, each packet needs to have destination
address and each packet might be routed differently, and might arrive in any order. Packet
delivery is not guaranteed.
The format of datagram packet is:

Constructors of DatagramPacket class


 DatagramPacket(byte[] barr, int length): it creates a datagram packet. This constructor
is used to receive the packets.
 DatagramPacket(byte[] barr, int length, InetAddress address, int port): it creates a
datagram packet. This constructor is used to send the packets.
The key methods of DatagramPacket class are:
 byte[] getData():-Returns the data buffer.
 intgetLength():- Returns the length of the data to be sent or the length of the data
received.
 voidsetData(byte[] buf):- Sets the data buffer for this packet.
 voidsetLength(int length):-Sets the length for this packet.
Example of Sending DatagramPacket by DatagramSocket
//DSender.java  
import java.net.*;  
public class DSender{  
  public static void main(String[] args) throws Exception {  
    DatagramSocket ds = new DatagramSocket();  
    String str = "Welcome java";  
    InetAddress ip = InetAddress.getByName("127.0.0.1");       
  DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);  
    ds.send(dp);  
    ds.close();  
  }  }  
Example of Receiving DatagramPacket by DatagramSocket
//DReceiver.java  
import java.net.*;  
public class DReceiver{  
  public static void main(String[] args) throws Exception {  
    DatagramSocket ds = new DatagramSocket(3000);  
    byte[] buf = new byte[1024];  
    DatagramPacket dp = new DatagramPacket(buf, 1024);  
    ds.receive(dp);  
    String str = new String(dp.getData(), 0, dp.getLength());  
    System.out.println(str);  
    ds.close();  
  }  }  

Example:- This is a sample java program using sockets to establish UDP connection.


Udp Server.java
import java.io.*; import java.net.*;
class UdpServer {
public static void main(String arg[]) {
String str;
Try {
BufferedReader Br = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket Sock = new DatagramSocket(1000);
DatagramPacket Dp;
System.out.println("Enter the data..... Enter 'exit' to stop");
while(true) {
str = Br.readLine();
Dp = new DatagramPacket(str.getBytes(), str.length(),
InetAddress.getByName("localhost"),2000);
Sock.send(Dp);
if(str.equals("exit")) break;
}
Sock.close();
}
catch(Exception e) { }
}}

UdpClient.java
import java.net.*;
class UdpClient {
public static void main(String arg[]) {
String str;
DatagramSocket Sock;
DatagramPacket Dp;
Try {
Sock = new DatagramSocket(2000);
byte Buff[] = new byte[1024];
System.out.println("Client ready...");
while(true) {
Dp = new DatagramPacket(Buff,1024);
Sock.receive(Dp);
str = new String(Dp.getData(),0,Dp.getLength());
System.out.println(str);
if(str.equals("exit")) break;
}
Sock.close();
}
catch(Exception e) {
System.out.println("Connection failure..."); }
Finally {
System.out.println("Server Disconnected...");
}}}
 
OUTPUT:
Udp Server :
E:\>java UdpServer
Enter the data..... Enter 'exit' to stop
hello
exit
Udp Client:
E:\ >java UdpClient
Client ready...
hello
exit
Server Disconnected...

Stream Socket vs. Datagram Socket

Stream socket
• A dedicated point‐to‐point channel between a clientand server.
• Use TCP (Transmission Control Protocol) for datatransmission.
• Lossless and reliable.
• Sent and received in the same order.

Datagram socket
 No dedicated point‐to‐point channel between a client and server.
• Use UDP (User Datagram Protocol) for datatransmission.
• May lose data and not 100% reliable.
• Data may not received in the same order as sent.
7. What is URL?
URL is an acronym for Uniform Resource Locator. It points to a resource on the World Wide
Web.
For example:- http://www.javatpoint.com/java-tutorial  
A URL contains many information:
 Protocol: In this case, http is the protocol.
 Server name or IP Address: In this case, www.javatpoint.com is the server name.
 Port Number: It is an optional attribute. If we write
http//ww.javatpoint.com:80/sonoojaiswal/ , 80 is the port number. If port number is not
mentioned in the URL, it returns -1.
 File Name or directory name: In this case, index.jsp is the file name.

7.1.URL class: - The java.net.URL class provides many methods. The important
methods of URL class are:-

Method Description
public String getProtocol() it returns the protocol of the URL.
public String getHost() it returns the host name of the URL.
public String getPort() it returns the Port Number of the URL.
public String getFile() it returns the file name of the URL.
public URLConnection openConnection() it returns the instance of URLConnection
i.e. associated with this URL.
Example:-
//URLDemo.java  
import java.io.*;  
import java.net.*;  
public class URLDemo{  
public static void main(String[] args){  
try{  
URL url=new URL("http://www.javatpoint.com/java-tutorial");    
System.out.println("Protocol: "+url.getProtocol());  
System.out.println("Host Name: "+url.getHost());  
System.out.println("Port Number: "+url.getPort());  
System.out.println("File Name: "+url.getFile());    
}catch(Exception e){System.out.println(e);}  
}}  
Test it Now
Output:
Protocol: http
Host Name: www.javatpoint.com
Port Number: -1
File Name: /java-tutorial

7.2.URLConnection class
The Java URLConnection class represents a communication link between the URL and the
application. This class can be used to read and write data to the specified resource referred by the
URL.
The openConnection() method of URL class returns the object of URLConnection class.
Syntax: public URLConnection openConnection()throws IOException{}  
The URLConnection class provides many methods, we can display all the data of a webpage
by using the getInputStream() method. The getInputStream() method returns all the data of the
specified URL in the stream that can be read and displayed.
Example:-
import java.io.*;  
import java.net.*;  
public class URLConnectionExample {  
public static void main(String[] args){  
try{  
URL url=new URL("http://www.javatpoint.com/java-tutorial");  
URLConnection urlcon=url.openConnection();  
InputStream stream=urlcon.getInputStream();  
int i;  
while((i=stream.read())!=-1){  
System.out.print((char)i);  
}}
catch(Exception e){System.out.println(e);}  
}  }  

7.3. HttpURLConnection class


The Java HttpURLConnection class is http specific URLConnection. It works for HTTP
protocol only. By the help of HttpURLConnection class, you can get information of any HTTP
URL such as header information, status code, response code etc. The
java.net.HttpURLConnection is subclass of URLConnection class.
The openConnection() method of URL class returns the object of URLConnection class.
Syntax: public URLConnection openConnection()throws IOException{}  
You can typecast it to HttpURLConnection type as given below.
URL url=new URL("http://www.javatpoint.com/java-tutorial");    
HttpURLConnection huc=(HttpURLConnection)url.openConnection();  

Example:-
import java.io.*;    
import java.net.*;    
public class HttpURLConnectionDemo{    
public static void main(String[] args){    
try{    
URL url=new URL("http://www.javatpoint.com/java-tutorial");    
HttpURLConnection huc=(HttpURLConnection)url.openConnection();  
for(int i=1;i<=8;i++){  
System.out.println(huc.getHeaderFieldKey(i)+" = "+huc.getHeaderField(i));  
}  
huc.disconnect();   
}
catch(Exception e){System.out.println(e);}    
}  }    
Output:
Date = Wed, 10 Dec 2014 19:31:14 GMT
Set-Cookie = JSESSIONID=D70B87DBB832820CACA5998C90939D48; Path=/
Content-Type = text/html
Cache-Control = max-age=2592000
Expires = Fri, 09 Jan 2015 19:31:14 GMT
Vary = Accept-Encoding,User-Agent
Connection = close
Transfer-Encoding = chunked
8. What Is a Network Interface?

A network interface is the point of interconnection between a computer and a private or public
network. A network interface is generally a network interface card (NIC), but does not have to
have a physical form. Instead, the network interface can be implemented in software. For
example, the loopback interface (127.0.0.1 for IPv4 and ::1 for IPv6) is not a physical device
but a piece of software simulating a network interface. The loopback interface is commonly used
in test environments.

The java.net.NetworkInterface class represents both types of interfaces.

NetworkInterface is useful for a multi-homed system, which is a system with multiple NICs.
Using NetworkInterface, you can specify which NIC to use for a particular network activity.

For example, assume you have a machine with two configured NICs, and you want to send data
to a server. You create a socket like this:

Socket soc = new java.net.Socket();


soc.connect(new InetSocketAddress(address, port));

To send the data, the system determines which interface is used. However, if you have a
preference or otherwise need to specify which NIC to use, you can query the system for the
appropriate interfaces and find an address on the interface you want to use. When you create the
socket and bind it to that address, the system uses the associated interface. For example:

NetworkInterfacenif = NetworkInterface.getByName("bge0");
Enumeration<InetAddress>nifAddresses = nif.getInetAddresses();

Socket soc = new java.net.Socket();


soc.bind(new InetSocketAddress(nifAddresses.nextElement(), 0));
soc.connect(new InetSocketAddress(address, port));

You can also use NetworkInterface to identify the local interface on which a multicast group is
to be joined. For example:

NetworkInterfacenif = NetworkInterface.getByName("bge0");
MulticastSocketms = new MulticastSocket();
ms.joinGroup(new InetSocketAddress(hostname, port), nif);

NetworkInterface can be used with Java APIs in many other ways beyond the two uses described
here.
Retrieving Network Interfaces

The NetworkInterface class has no public constructor. Therefore, you cannot just create a new
instance of this class with the new operator. Instead, the following static methods are available so
that you can retrieve the interface details from the system: getByInetAddress(), getByName(),
and getNetworkInterfaces(). The first two methods are used when you already know the IP
address or the name of the particular interface. The third method, getNetworkInterfaces()
returns the complete list of interfaces on the machine.

Network interfaces can be hierarchically organized. The NetworkInterface class includes two
methods, getParent() and getSubInterfaces(), that are pertinent to a network interface
hierarchy. The getParent() method returns the parent NetworkInterface of an interface. If a
network interface is a subinterface, getParent() returns a non-null value. The
getSubInterfaces() method returns all the subinterfaces of a network interface.

The following example program lists the name of all the network interfaces and subinterfaces (if
any exist) on a machine.

import java.io.*;
import java.net.*;
importjava.util.*;
import static java.lang.System.out;

public class ListNIFs


{
public static void main(String args[]) throws SocketException {
Enumeration<NetworkInterface> nets =
NetworkInterface.getNetworkInterfaces();

for (NetworkInterfacenetIf : Collections.list(nets)) {


out.printf("Display name: %s\n", netIf.getDisplayName());
out.printf("Name: %s\n", netIf.getName());
displaySubInterfaces(netIf);
out.printf("\n");
}
}

static void displaySubInterfaces(NetworkInterfacenetIf) throws SocketException


{
Enumeration<NetworkInterface>subIfs = netIf.getSubInterfaces();

for (NetworkInterfacesubIf : Collections.list(subIfs)) {


out.printf("\tSub Interface Display name: %s\n", subIf.getDisplayName());
out.printf("\tSub Interface Name: %s\n", subIf.getName());
}
}
}

The following is sample output from the example program:


Display name: bge0
Name: bge0
Sub Interface Display name: bge0:3
Sub Interface Name: bge0:3
Sub Interface Display name: bge0:2
Sub Interface Name: bge0:2
Sub Interface Display name: bge0:1
Sub Interface Name: bge0:1

Display name: lo0


Name: lo0

Listing Network Interface Addresses

One of the most useful pieces of information you can get from a network interface is the list of
IP addresses that are assigned to it. You can obtain this information from a NetworkInterface
instance by using one of two methods. The first method, getInetAddresses(), returns an
Enumeration of InetAddress. The other method, getInterfaceAddresses(), returns a list of
java.net.InterfaceAddress instances. This method is used when you need more information
about an interface address beyond its IP address. For example, you might need additional
information about the subnet mask and broadcast address when the address is an IPv4 address,
and a network prefix length in the case of an IPv6 address.

The following example program lists all the network interfaces and their addresses on a machine:

import java.io.*;
import java.net.*;
importjava.util.*;
import static java.lang.System.out;

public class ListNets {

public static void main(String args[]) throws SocketException {


Enumeration<NetworkInterface> nets =
NetworkInterface.getNetworkInterfaces();
for (NetworkInterfacenetint : Collections.list(nets))
displayInterfaceInformation(netint);
}

static void displayInterfaceInformation(NetworkInterfacenetint) throws


SocketException {
out.printf("Display name: %s\n", netint.getDisplayName());
out.printf("Name: %s\n", netint.getName());
Enumeration<InetAddress>inetAddresses = netint.getInetAddresses();
for (InetAddressinetAddress : Collections.list(inetAddresses)) {
out.printf("InetAddress: %s\n", inetAddress);
}
out.printf("\n");
}
}

The following is sample output from the example program:

Display name: TCP Loopback interface


Name: lo
InetAddress: /127.0.0.1

Display name: Wireless Network Connection


Name: eth0
InetAddress: /192.0.2.0

Network Interface Parameters


You can access network parameters about a network interface beyond the name and IP addresses
assigned to it

You can discover if a network interface is “up” (that is, running) with the isUP() method. The
following methods indicate the network interface type:

 isLoopback() indicates if the network interface is a loopback interface.


 isPointToPoint() indicates if the interface is a point-to-point interface.
 isVirtual() indicates if the interface is a virtual interface.

The supportsMulticast() method indicates whether the network interface supports


multicasting. The getHardwareAddress() method returns the network interface's physical
hardware address, usually called MAC address, when it is available. The getMTU() method
returns the Maximum Transmission Unit (MTU), which is the largest packet size.

The following example expands on the example in Listing Network Interface Addresses by
adding the additional network parameters described on this page:

import java.io.*;
import java.net.*;
importjava.util.*;
import static java.lang.System.out;

public class ListNetsEx {

public static void main(String args[]) throws SocketException {


Enumeration<NetworkInterface> nets =
NetworkInterface.getNetworkInterfaces();
for (NetworkInterfacenetint : Collections.list(nets))
displayInterfaceInformation(netint);
}
static void displayInterfaceInformation(NetworkInterfacenetint) throws
SocketException {
out.printf("Display name: %s\n", netint.getDisplayName());
out.printf("Name: %s\n", netint.getName());
Enumeration<InetAddress>inetAddresses = netint.getInetAddresses();

for (InetAddressinetAddress : Collections.list(inetAddresses)) {


out.printf("InetAddress: %s\n", inetAddress);
}

out.printf("Up? %s\n", netint.isUp());


out.printf("Loopback? %s\n", netint.isLoopback());
out.printf("PointToPoint? %s\n", netint.isPointToPoint());
out.printf("Supports multicast? %s\n", netint.supportsMulticast());
out.printf("Virtual? %s\n", netint.isVirtual());
out.printf("Hardware address: %s\n",
Arrays.toString(netint.getHardwareAddress()));
out.printf("MTU: %s\n", netint.getMTU());
out.printf("\n");
}
}

The following is sample output from the example program:

Display name: bge0


Name: bge0
InetAddress: /fe80:0:0:0:203:baff:fef2:e99d%2
InetAddress: /129.156.225.59
Up? true
Loopback?false
PointToPoint?false
Supports multicast? false
Virtual?false
Hardware address: [0, 3, 4, 5, 6, 7]
MTU: 1500

Display name: lo0


Name: lo0
InetAddress: /0:0:0:0:0:0:0:1%1
InetAddress: /127.0.0.1
Up? true
Loopback?true
PointToPoint?false
Supports multicast? false
Virtual?false
Hardware address: null
MTU: 8232

You might also like