Java Networking

Last Updated : 17 Apr, 2026

Java Networking is the concept of connecting two or more computing devices to exchange data and resources. It allows Java applications to communicate over the internet or local networks.

  • All communications in Java networking happen at the application layer.
  • The java.net package provides APIs for protocols, sockets, IP addresses, and URLs.
  • Java was designed with networking in mind, making distributed computing simpler.
  • In Java, networking is supported through the java.net package, which provides classes and interfaces to handle low-level communication, socket programming, and access to network resources.

Common Network Protocols 

1. TCP (Transmission Control Protocol)

TCP is a connection-oriented protocol that ensures data is delivered accurately and in the correct order. It establishes a connection before communication and verifies successful data transfer.

  • Reliable and error-checked data transmission
  • Maintains data order using acknowledgements
  • Used for web applications, file transfer, and emails

2. UDP (User Datagram Protocol)

UDP is a connectionless protocol designed for fast data transmission without delivery guarantees. It sends data packets independently, making it suitable for real-time communication.

  • Faster but unreliable compared to TCP
  • No connection setup or acknowledgement
  • Used in streaming, gaming, and video conferencing

Refer to this article to know more about TCP and UDP - Differences between TCP and UDP.

Java Networking Terminology

  • IP Address: Logical address that identifies a device on a network (e.g., 192.168.0.1). Range: 0.0.0.0 – 255.255.255.255.
  • Port Number: Identifies applications uniquely on a device. Range: 0 – 65,535.
  • Protocol: Set of rules for communication (e.g., TCP, FTP, HTTP).
  • MAC Address: Unique identifier assigned to a network interface card, written in hexadecimal.
  • Socket: Endpoint for two-way communication between devices.
  • Connection-Oriented Protocol: Requires connection setup (e.g., TCP).
  • Connectionless Protocol: No prior connection setup, data sent directly (e.g., UDP).

Java Networking classes

The java.net package provides classes to handle networking operations in Java. Commonly used classes are:

  • CacheRequest: Used to store resources in ResponseCache. Provides an OutputStream to write resource data into cache.
  • CookieHandler: Provides a callback mechanism to manage HTTP cookies during client-server communication.
  • CookieManager: A concrete implementation of CookieHandler that manages cookies using CookieStore and CookiePolicy.
  • DatagramPacket: Represents a data packet used in UDP-based, connectionless communication.
  • InetAddress: Represents IP addresses and hostnames, supporting both IPv4 and IPv6.
  • ServerSocket: Implements the server side of a TCP connection and listens for client requests on a port.
  • Socket: Represents a client-side TCP connection used to send and receive data.
  • DatagramSocket: Used for sending and receiving UDP packets and supports broadcast communication.
  • Proxy: Represents proxy settings for a connection. Useful for network security and anonymity.
  • URL: Represents a Uniform Resource Locator pointing to a web resource such as a file or web page.
  • URLConnection: Represents a communication link between a Java application and a URL resource.
  • HttpURLConnection: A subclass of URLConnection that supports HTTP-specific operations like GET and POST.
  • URLEncoder / URLDecoder: Encode and decode strings to make them safe for transmission in URLs.
  • MulticastSocket: A specialized UDP socket used for group communication (multicasting).
  • Authenticator: Provides a mechanism to handle authentication when accessing protected network resources.

Java Networking Interfaces

Important interfaces from java.net:

  • CookiePolicy: Defines rules for accepting or rejecting HTTP cookies.
  • CookieStore: Stores and manages cookies used during HTTP communication.
  • FileNameMap: Maps file names or extensions to corresponding MIME types.
  • SocketOption: Used to configure socket behavior such as timeout and buffer size.
  • SocketImplFactory: Allows creation of custom socket implementation classes.
  • ProtocolFamily: Represents a family of communication protocols.

Socket Programming

Socket programming enables communication between client and server applications over TCP or UDP.

Steps for TCP Communication

  1. Server creates a ServerSocket and listens on a port.
  2. Client creates a Socket and requests a connection.
  3. Server accepts the connection and returns a Socket.
  4. Data is exchanged via I/O streams (InputStream, OutputStream).
  5. Connection is closed when communication ends.

Socket Class

The Socket class represents a TCP client-side connection. It allows sending, receiving data, and closing connections. Each socket is associated with one remote host, for another host a new socket must be created.

Common Methods:

  • connect(SocketAddress host, int timeout): Connects the socket to a given host.
  • getPort(): Returns the remote port of the connection.
  • getInetAddress(): Returns the remote IP address.
  • getLocalPort(): Returns the local port of the socket.
  • getRemoteSocketAddress(): Returns the remote socket address.
  • getInputStream(): Returns input stream of the socket.
  • getOutputStream(): Returns output stream of the socket.
  • close(): Closes the socket connection.

ServerSocket Class

The ServerSocket class implements the server side of a TCP connection. It listens for client requests on a given port. If the port is unavailable, the constructor throws an exception.

Common Methods:

  • getLocalPort(): Returns the port the server is listening on.
  • setSoTimeout(int timeout): Sets timeout while waiting for a client.
  • accept(): Waits and accepts a client connection.
  • bind(SocketAddress host, int backlog): Binds server to a specific address and port.

Example: Basic Client-Server Communication

Client Side

Java
import java.io.*;
import java.net.*;

public class ClientSide {
    public static void main(String[] args) {
        try (Socket socket = new Socket("127.0.0.1", 5000);
             DataOutputStream out = new DataOutputStream(socket.getOutputStream());
             BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
            
            System.out.println("Connected to Server");
            String line;
            while (!(line = br.readLine()).equals("End")) {
                out.writeUTF(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Server Side

Java
import java.io.*;
import java.net.*;

public class ServerSide {
    public static void main(String[] args) {
        try (ServerSocket server = new ServerSocket(5000);
             Socket socket = server.accept();
             DataInputStream in = new DataInputStream(socket.getInputStream())) {
            
            System.out.println("Server started. Waiting for client...");
            String line;
            while (!(line = in.readUTF()).equals("End")) {
                System.out.println("Client: " + line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Execution Steps

  1. Run ServerSide. It waits for a client.
  2. Run ClientSide. It connects to the server.
  3. Type messages in the client window, server displays them.

InetAddress Class

The InetAddress class represents IP addresses and hostnames. It supports both IPv4 and IPv6.

Types of Addresses

  • Unicast: Identifies a single interface.
  • Multicast: Identifies a group of interfaces.

Common Methods:

  • getByAddress(byte[] addr): Returns an InetAddress from raw IP.
  • getByName(String host): Returns IP of a given hostname.
  • getLocalHost(): Returns local host IP.
  • getHostName(): Returns hostname.
  • getHostAddress(): Returns IP address as string.

Example:

Java
import java.net.*;

public class InetAddressExample {
    public static void main(String[] args) throws Exception {
        InetAddress local = InetAddress.getLocalHost();
        System.out.println("Local Host: " + local);
        System.out.println("Host Name: " + local.getHostName());

        InetAddress gfg = InetAddress.getByName("www.geeksforgeeks.org");
        System.out.println("GeeksforGeeks IP: " + gfg);
    }
}

URL Class

The URL class represents a Uniform Resource Locator that points to a resource on the web.

Components of a URL

  • Protocol: How communication happens (http, https, ftp).
  • Hostname: The server where the resource exists.
  • File/Path: The location of the resource.
  • Port (optional): Communication port number.

Common Methods:

  • getProtocol(): Returns protocol of URL.
  • getHost(): Returns hostname.
  • getPort(): Returns port of the URL.
  • getFile(): Returns filename.
  • getPath(): Returns path of the URL.
  • toString(): Returns URL as a string.
  • getDefaultPort(): Returns default port of the protocol.

Example:

Java
import java.net.*;

public class URLExample {
    public static void main(String[] args) throws Exception {
        URL url = new URL("https://write.geeksforgeeks.org/post/3038131");

        System.out.println("Protocol : " + url.getProtocol());
        System.out.println("Host : " + url.getHost());
        System.out.println("File : " + url.getFile());
        System.out.println("Path : " + url.getPath());
        System.out.println("Default Port : " + url.getDefaultPort());
    }
}

Output:

Protocol : https
Host : write.geeksforgeeks.org
File : /post/3038131
Path : /post/3038131
Default Port : 443

Comment