Java Networking Basics
In this page:
What is an IP Address and URL?
The java.net package contains the core classes for network communication in Java. InetAddress represents IP addresses (both IPv4 and IPv6), and the URL class represents a Uniform Resource Locator, giving you a structured way to work with network addresses instead of manipulating raw strings.
Example: What is an IP Address and URL?
// Import java.net.InetAddress so it can be used by its short name
import java.net.InetAddress;
// Import java.net.URL so it can be used by its short name
import java.net.URL;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) throws Exception {
InetAddress address = InetAddress.getByName("127.0.0.1");
// Create a new URL object and store it in url
URL url = new URL("https://example.com/page");
// Print a line to the console
System.out.println(address.getHostAddress() + " " + url.getHost());
}
}
Login to try C/C++/Java/PHP code in the editor
Reading from a URL Connection
The URLConnection class lets you open a communication link to a URL and inspect metadata like headers before reading the body. You can pull the raw byte stream of a page using getInputStream(), which is the lower-level building block that higher-level HTTP clients are built on top of.
Example: Reading from a URL Connection
// Import java.net.URLConnection so it can be used by its short name
import java.net.URLConnection;
// Import java.io.* so it can be used by its short name
import java.io.*;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) throws Exception {
// Create a new File object and store it in file
File file = new File("page.txt");
// Try code that might throw an exception
try (PrintWriter out = new PrintWriter(file)) { out.print("sample content"); }
URLConnection conn = file.toURI().toURL().openConnection();
// Try code that might throw an exception
try (InputStream in = conn.getInputStream()) {
// Print a line to the console
System.out.println(new String(in.readAllBytes()));
}
file.delete();
}
}
Login to try C/C++/Java/PHP code in the editor
URI vs URL in Java 11+
A URI represents an abstract resource identifier (it doesn't have to be resolvable), while a URL is a specific, locatable resource. Since Java 11, the recommended pattern is to construct a URI first and only convert it to a URL with toURL() when you actually need to open a connection, since URI's constructor validates syntax more strictly and avoids some legacy URL pitfalls.
Example: URI vs URL in Java 11+
import java.net.URI;
import java.net.URL;
public class Main {
public static void main(String[] args) throws Exception {
URI uri = new URI("https://example.com/page"); // validated more strictly
URL url = uri.toURL(); // converted only when actually needed
System.out.println(uri + " -> " + url);
}
}
Login to try C/C++/Java/PHP code in the editor
Network Protocols Overview
Java abstracts most low-level protocol details away from application code: Sockets run over TCP for reliable, ordered delivery, and DatagramSockets run over UDP for lightweight, connectionless messaging. Knowing which protocol a given API sits on top of helps you reason about whether delivery is guaranteed and how much overhead to expect.
Example: Network Protocols Overview
import java.net.*;
public class Main {
public static void main(String[] args) throws Exception {
Socket tcpSocket = new Socket(); // TCP -- reliable, ordered
DatagramSocket udpSocket = new DatagramSocket(); // UDP -- lightweight, connectionless
System.out.println("TCP and UDP sockets created");
udpSocket.close();
}
}
Login to try C/C++/Java/PHP code in the editor
Hostname Resolution
You can resolve a domain name to its underlying IP address (or addresses, since a name can map to several) using the InetAddress class's getByName() and getAllByName() methods. This is the same DNS lookup step your browser performs before it can actually open a socket to a server.
Example: Hostname Resolution
import java.net.InetAddress;
public class Main {
public static void main(String[] args) throws Exception {
InetAddress address = InetAddress.getByName("localhost");
System.out.println(address.getHostAddress()); // same DNS-style lookup a browser performs
}
}
Login to try C/C++/Java/PHP code in the editor
- Using
new URL(...)in new code, which is deprecated since Java 20; useURI.create(...).toURL(). - Not handling
UnknownHostExceptionwhen resolving a hostname, which happens if the name does not exist or there is no network. - Opening a connection without setting connect and read timeouts, so the program can hang for a long time.
Chapter Quiz — Complete all 4 topics to unlock
0/4 topics done
Complete these topics first: