Java Networking
Networking is the practice of connecting computing devices to share information and resources.
Java networking allows programs to communicate over a network, with all communication managed at the application layer.
The java.net
package is the foundation for this, providing classes and interfaces that handle low-level communication details, letting developers focus on their application's logic.
Network Classes in Java
Java provides a rich set of classes for networking under the java.net
package.
URL
: It's a high-level class used to parse a URL string and open a connection to the resource it points to, making it easy to fetch web content. This class represents a Uniform Resource Locator.URLConnection :
URL
class represents an address, theURLConnection
class opens the actual communication link to the resource. It allows a program to connect to a server, read metadata (like content type and length), and send or receive data.InetAddress
: This class represents an IP (Internet Protocol) address. It's used to get the IP address of a host by its name (DNS lookup) or vice versa. It has subclasses for both IPv4 and IPv6 addresses.Socket
: This class is a fundamental building block for client-side TCP (Transmission Control Protocol) networking. ASocket
represents one end of a two-way communication link between two programs on the network. It is used to connect to a server, send data, and receive data.Socket socket = new Socket("localhost", 8080);
ServerSocket
: This class is the server-side counterpart toSocket
. AServerSocket
waits for requests to come in over the network from clients. When it receives a connection request, it creates aSocket
object to handle the communication with that specific client.ServerSocket server = new ServerSocket(8080);
DatagramSocket: Used for connectionless UDP communication. It sends and receives datagram packets.
DatagramSocket socket = new DatagramSocket();
DatagramPacket: Represents the data packet sent or received via a
DatagramSocket
in UDP communication.DatagramPacket packet = new DatagramPacket(buf, buf.length)
High-Level Networking
URL (Uniform Resource Locator)
A URL (Uniform Resource Locator) is a reference or an address of a resource on the internet. It's the text that is typed into a browser to visit a website, but it can also point to other resources like files or APIs. It tells a web client both how to get a resource and where to find it.
A URL is made up of several components: Protocol://hostname:port/path
https://example.com:9090/path/file?query=123#fragment
Protocol (or Scheme): This tells the browser which protocol to use to access the resource.
http
(Hypertext Transfer Protocol),https
(secure HTTP), andftp
(File Transfer Protocol). It's always followed by://
.Host (or Domain Name): Unique name or IP address of the server where the resource is located, like
www.google.com
oren.wikipedia.org
.Port: Optional number that specifies the "doorway" on the server to connect to. If it's omitted, a default port is used (
80
forhttp
and443
forhttps
).http://example.com:8080
.Path: Specifies the exact location of the resource on the server, similar to a file path on computer.
www.example.com/products/laptops.html
Query String (or Parameters): This optional part, which starts with a
?
, contains key-value pairs used to send data to the server. For example, ingoogle.com/search?q=java
,q=java
is the query string.Fragment (or Anchor): This optional part, which starts with a
#
, is a bookmark to a specific part of the resource on the page. For example,page.html#section2
would jump the browser to the element with the IDsection2
.
In Java, the URL
class is used to represent and parse these addresses.
Purpose of URL
and InetAddress
Classes
URL
Class
The purpose of the java.net.URL
class is to provide a simple, high-level abstraction for working with web resources. Instead of dealing with low-level sockets, URL
class is used to:
Parse URL strings into their components (protocol, host, port, etc.).
Open a connection to the resource using
openConnection()
.Easily retrieve the content of a resource using its
openStream()
method, which returns anInputStream
to read the data.
It's the go-to class when goal is simply to download content from a web address without managing the underlying connection details.
import java.net.URL;
import java.net.MalformedURLException;
class URLDemo {
public static void main(String[] args) throws MalformedURLException {
URL url = new URL("https://example.com:9090/path/");
System.out.println("URL is: " + url.toString());
System.out.println("Protocol: " + url.getProtocol());
System.out.println("Host: " + url.getHost());
System.out.println("Port: " + url.getPort());
System.out.println("Path: " + url.getPath());
}
}
Simple URL Program
import java.net.*;
import java.io.*;
import java.util.Date;
class URLDemo {
public static void main(String[] args) throws Exception {
URL url = new URL("https://www.google.com/");
// --- 1. Demonstrate URL Parsing Methods ---
System.out.println("--- URL Component Details ---");
System.out.println("Protocol: " + url.getProtocol());
System.out.println("Host: " + url.getHost());
// getPort() returns -1 if the port is not explicit in the URL
System.out.println("Port: " + url.getPort());
System.out.println("Default Port: " + url.getDefaultPort());
// --- 2. Get Header Information using URLConnection ---
URLConnection connection = url.openConnection();
System.out.println("\n--- Header Information ---");
System.out.println("Content-Type: " + connection.getContentType());
System.out.println("Content-Length: " + connection.getContentLengthLong());
System.out.println("Server Date: " + new Date(connection.getDate()));
}
}
--- URL Component Details ---
Protocol: https
Host: www.google.com
Port: -1
Default Port: 443
--- Header Information ---
Content-Type: text/html; charset=ISO-8859-1
Content-Length: -1
Server Date: Tue Aug 19 22:17:23 IST 2025
InetAddress
Class
The purpose of the java.net.InetAddress
class is to encapsulate an IP address and handle the interaction between hostnames and IP addresses.
The InetAddress
class represents an IP address and its corresponding domain name. It is primarily used to perform DNS lookups to convert a hostname into an IP address.
Its main uses are:
DNS Resolution: To find the IP address associated with a given hostname (e.g., converting
www.google.com
to an IP like142.250.195.36
). This is done using static methods likegetByName()
orgetAllByName()
.Reverse Lookup: To find the hostname associated with a given IP address.
Local Host Information: To get the IP address and name of the local machine.
It's a crucial utility for any network application that needs to know where to send data on the internet.
It has no public constructors, so static factory methods have to be used to create instances:
getByName(String host)
: Returns the IP address for a given hostname.getAllByName(String host)
: Returns all IP addresses for a hostname, as a single name can map to multiple IPs.getLocalHost()
: Returns the IP address of the local machine.getByAddress(byte[] addr)
: Creates anInetAddress
from a raw IP address in a byte array.
These methods throw an UnknownHostException
if the host cannot be found or if there is a network or DNS issue.
// Example: Converting a hostname to an IP address
import java.net.*;
public class HostToIP {
public static void main(String[] args) throws Exception {
InetAddress address = InetAddress.getByName("www.example.com");
System.out.println("IP Address: "
+ address.getHostAddress());
}
}