Java Networking

Last Updated : 6 Oct, 2026

Java Networking enables two or more computing devices to communicate and exchange data over a network. Java provides networking APIs mainly through the java.net package for building network-based applications.

  • Supports network communication using protocols such as TCP and UDP.
  • Provides APIs for working with sockets, IP addresses, URLs, and other 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

  • Server creates a ServerSocket and listens on a port.
  • Client creates a Socket and requests a connection.
  • Server accepts the connection and returns a Socket.
  • Data is exchanged via I/O streams (InputStream, OutputStream).
  • 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

  • Run ServerSide. It waits for a client.
  • Run ClientSide. It connects to the server.
  • 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

Modern HTTP Client API

Java provides the java.net.http package for modern HTTP communication. Introduced in Java 11 as a standard API, it provides a cleaner approach for sending HTTP requests and receiving responses than the older HttpURLConnection API.

The main components are:

ComponentDescription
HttpClientSends HTTP requests and manages communication with HTTP servers.
HttpRequestRepresents an HTTP request, including the URI, headers, and request method.
HttpResponse<T>Represents the response received from an HTTP server.
Java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class HttpClientExample {
    public static void main(String[] args) throws Exception
    {

        HttpClient client = HttpClient.newHttpClient();

        HttpRequest request
            = HttpRequest.newBuilder()
                  .uri(URI.create(
                      "https://www.geeksforgeeks.org/"))
                  .GET()
                  .build();

        HttpResponse<String> response = client.send(
            request, HttpResponse.BodyHandlers.ofString());

        System.out.println("Status Code: "
                           + response.statusCode());
    }
}

Output:

Status Code: 200

Note: The actual status code depends on the server response and network availability.

Comment