Ch 16.1 Networking Overview
Networking is the practice of connecting two or more computers or devices via cables or wireless communication to form a network capable of exchanging data. Using Java's java.net package, developers can build network applications without needing deep knowledge of low-level hardware networking.
1. IP Addresses
An IP address is a unique numerical identifier assigned to each device (host) on a network.
- IPv4: 4-byte address in dotted-decimal form (e.g.,
192.168.0.1) — currently being exhausted - IPv6: 16-byte next-generation address (e.g.,
2001:0db8:85a3::8a2e:0370:7334)
Java uses the InetAddress class to represent and resolve IP addresses.
import java.net.InetAddress;
import java.net.UnknownHostException;
public class InetAddressExample {
public static void main(String[] args) {
try {
// Resolve hostname to IP address
InetAddress ip = InetAddress.getByName("www.google.com");
System.out.println("Host name: " + ip.getHostName());
System.out.println("IP address: " + ip.getHostAddress());
// Get all IP addresses (load-balanced hosts may have multiple)
InetAddress[] allAddresses = InetAddress.getAllByName("www.example.com");
for (InetAddress addr : allAddresses) {
System.out.println("Address: " + addr.getHostAddress());
}
// Local machine's address
InetAddress localhost = InetAddress.getLocalHost();
System.out.println("Localhost: " + localhost.getHostAddress());
// Check if an address is reachable
boolean reachable = ip.isReachable(3000); // 3 second timeout
System.out.println("Reachable: " + reachable);
} catch (UnknownHostException e) {
System.err.println("Host not found: " + e.getMessage());
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
}
2. Port Numbers
If an IP address is a building's street address, a port is the door number within that building.
A single computer (one IP) can run multiple services simultaneously — a web server, a mail server, a database server. Port numbers (0–65535) identify which specific application should receive incoming data.
Well-Known Ports (0–1023)
Reserved by international standards for common system services. Avoid using these for personal applications; use ports 1024 and above instead (e.g., 8080).
| Port | Protocol | Service |
|---|---|---|
| 80 | HTTP | Web (unencrypted) |
| 443 | HTTPS | Web (encrypted) |
| 21 | FTP | File transfer |
| 22 | SSH | Secure shell / remote access |
| 25 | SMTP | Email sending |
| 3306 | MySQL | MySQL database |
| 5432 | PostgreSQL | PostgreSQL database |
3. TCP vs UDP
Network communication protocols differ in reliability and speed.
| Feature | TCP | UDP |
|---|---|---|
| Connection | Connection-oriented (3-way handshake) | Connectionless |
| Reliability | Guaranteed delivery and ordering | No guarantee |
| Speed | Slower (acknowledgment overhead) | Faster |
| Use cases | Web, file transfer, email | Video streaming, online games, DNS |
| Java classes | ServerSocket, Socket | DatagramSocket, DatagramPacket |
// TCP: establish connection first, then communicate reliably
// Client initiates:
Socket socket = new Socket("192.168.1.1", 8080);
// Server waits:
ServerSocket server = new ServerSocket(8080);
Socket client = server.accept();
// UDP: fire and forget (no connection)
DatagramSocket ds = new DatagramSocket();
byte[] data = "Hello".getBytes();
DatagramPacket packet = new DatagramPacket(data, data.length,
InetAddress.getByName("192.168.1.1"), 8080);
ds.send(packet); // send without waiting for acknowledgment
4. The Client-Server Model
Most network applications follow the client-server model:
- Server: Listens on a fixed port, waits for incoming connections
- Client: Knows the server's address and port, initiates the connection
Client Server
| |
|-- connect(IP:PORT) ---------->|
|<-- accept() returns Socket ---|
| |
|-- send request -------------->|
|<-- receive response ----------|
| |
|-- close() ------------------->|
5. java.net Core Classes
| Class | Package | Purpose |
|---|---|---|
InetAddress | java.net | Represents an IP address |
URL | java.net | Represents a URL (web address) |
URLConnection | java.net | HTTP connection (legacy) |
HttpURLConnection | java.net | HTTP GET/POST requests |
HttpClient | java.net.http | Modern HTTP client (Java 11+) |
ServerSocket | java.net | TCP server socket |
Socket | java.net | TCP client/communication socket |
DatagramSocket | java.net | UDP socket |
DatagramPacket | java.net | UDP data packet |
MulticastSocket | java.net | UDP multicast |
6. Network I/O is Stream-Based
Network communication in Java uses the same I/O streams you learned in Chapter 15. A Socket object provides InputStream and OutputStream — you read and write data through them exactly as you would with a file.
import java.net.*;
import java.io.*;
public class SocketStreamDemo {
public static void main(String[] args) throws IOException {
try (Socket socket = new Socket("echo.example.com", 7)) { // echo service
// Get the socket's I/O streams
InputStream rawIn = socket.getInputStream();
OutputStream rawOut = socket.getOutputStream();
// Wrap them for convenient text communication
BufferedReader in = new BufferedReader(new InputStreamReader(rawIn));
PrintWriter out = new PrintWriter(rawOut, true); // autoFlush
// Send a message
out.println("Hello, server!");
// Receive the echo
String response = in.readLine();
System.out.println("Server replied: " + response);
}
}
}
7. Practical Example: Simple Network Information Tool
import java.net.*;
import java.util.*;
public class NetworkInfo {
public static void main(String[] args) throws Exception {
System.out.println("=== Network Information ===");
// Local hostname and IP
InetAddress local = InetAddress.getLocalHost();
System.out.println("Hostname: " + local.getHostName());
System.out.println("Local IP: " + local.getHostAddress());
System.out.println("Loopback: " + InetAddress.getByName("localhost").getHostAddress());
// Enumerate all network interfaces
System.out.println("\n=== Network Interfaces ===");
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface ni = interfaces.nextElement();
if (!ni.isUp() || ni.isLoopback()) continue;
System.out.println("Interface: " + ni.getDisplayName());
Enumeration<InetAddress> addrs = ni.getInetAddresses();
while (addrs.hasMoreElements()) {
InetAddress addr = addrs.nextElement();
System.out.println(" Address: " + addr.getHostAddress()
+ (addr instanceof Inet4Address ? " (IPv4)" : " (IPv6)"));
}
}
// Resolve common hostnames
System.out.println("\n=== DNS Lookup ===");
String[] hosts = {"www.google.com", "www.github.com"};
for (String host : hosts) {
try {
InetAddress addr = InetAddress.getByName(host);
System.out.printf("%-20s -> %s%n", host, addr.getHostAddress());
} catch (UnknownHostException e) {
System.out.printf("%-20s -> FAILED (no network?)%n", host);
}
}
}
}
Pro tip: When building production network applications:
- Always set socket timeouts (
socket.setSoTimeout(ms)) to prevent hanging indefinitely - Handle
SocketTimeoutException,ConnectException, andSocketExceptionexplicitly - Use
try-with-resourcesfor allSocketandServerSocketobjects - For high-concurrency servers, consider Java NIO's non-blocking channels (
java.nio.channels) or a framework like Netty - For HTTP communication, prefer Java 11+'s
HttpClientoverHttpURLConnection