foreach-ui logo
codeLanguages
account_treeDSA

Quick Actions

quizlock Random Quiz
trending_uplock Progress
  • 1
  • 2
  • 3
  • 4
  • 5
  • quiz
Java
  • Understand fundamental networking concepts
  • Work with InetAddress for IP addresses
  • Know the difference between TCP and UDP
  • Handle common networking exceptions

Introduction to Java Networking

Your app needs to fetch data from an API, send emails, chat with other computers. That's networking. Java has built-in support—java.net and java.io packages give you everything you need.

What is Networking?

Networking enables communication between computers. At its core, it involves:

  • IP Addresses: Unique identifiers for devices on a network
  • Ports: Logical endpoints for different services (0-65535)
  • Protocols: Rules for communication (TCP, UDP, HTTP, etc.)
  • Sockets: Endpoints for bidirectional communication

The java.net Package

Java's networking API is contained in java.net:

import java.net.*;

// Key classes you'll use:
// InetAddress - represents an IP address
// URL - represents a Uniform Resource Locator
// URLConnection - for connecting to URLs
// Socket - TCP client socket
// ServerSocket - TCP server socket
// DatagramSocket - UDP socket
// DatagramPacket - UDP packet

IP Addresses and InetAddress

InetAddress represents an IP address (IPv4 or IPv6):

// Get address by hostname
InetAddress google = InetAddress.getByName("www.google.com");
System.out.println(google.getHostAddress());  // 142.250.x.x

// Get local host
InetAddress localhost = InetAddress.getLocalHost();
System.out.println(localhost.getHostName());     // your-computer-name
System.out.println(localhost.getHostAddress());  // 192.168.x.x

// Get loopback address
InetAddress loopback = InetAddress.getLoopbackAddress();
System.out.println(loopback);  // 127.0.0.1

// Get all addresses for a host (for load-balanced sites)
InetAddress[] addresses = InetAddress.getAllByName("www.google.com");
for (InetAddress addr : addresses) {
    System.out.println(addr.getHostAddress());
}

IPv4 vs IPv6

// IPv4: 192.168.1.1 (4 bytes)
Inet4Address ipv4 = (Inet4Address) InetAddress.getByName("192.168.1.1");

// IPv6: 2001:0db8:85a3:0000:0000:8a2e:0370:7334 (16 bytes)
Inet6Address ipv6 = (Inet6Address) InetAddress.getByName("::1");

// Check type
if (address instanceof Inet4Address) {
    System.out.println("IPv4 address");
} else if (address instanceof Inet6Address) {
    System.out.println("IPv6 address");
}

Checking Network Reachability

InetAddress address = InetAddress.getByName("www.google.com");

// Check if host is reachable (ping-like)
boolean reachable = address.isReachable(5000);  // timeout in ms
System.out.println("Reachable: " + reachable);

// With network interface
NetworkInterface netIf = NetworkInterface.getByName("eth0");
boolean reachable2 = address.isReachable(netIf, 64, 5000);

Network Interfaces

List available network interfaces:

import java.net.NetworkInterface;
import java.util.Enumeration;

Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
    NetworkInterface netIf = interfaces.nextElement();
    System.out.println("Name: " + netIf.getName());
    System.out.println("Display Name: " + netIf.getDisplayName());
    System.out.println("Is Up: " + netIf.isUp());
    System.out.println("Is Loopback: " + netIf.isLoopback());
    
    // Get IP addresses for this interface
    Enumeration<InetAddress> addresses = netIf.getInetAddresses();
    while (addresses.hasMoreElements()) {
        InetAddress addr = addresses.nextElement();
        System.out.println("  Address: " + addr.getHostAddress());
    }
    System.out.println();
}

TCP vs UDP

Java supports both transport protocols:

Feature TCP UDP
Connection Connection-oriented Connectionless
Reliability Guaranteed delivery No guarantee
Order Ordered delivery No ordering
Speed Slower (overhead) Faster
Use Cases HTTP, FTP, Email Streaming, DNS, Gaming
Java Classes Socket, ServerSocket DatagramSocket, DatagramPacket

TCP Overview

// TCP Client (simplified)
Socket socket = new Socket("localhost", 8080);
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
// ... communicate ...
socket.close();

// TCP Server (simplified)
ServerSocket server = new ServerSocket(8080);
Socket client = server.accept();  // Waits for connection
// ... communicate with client ...

UDP Overview

// UDP (simplified)
DatagramSocket socket = new DatagramSocket(9999);

// Send
byte[] data = "Hello".getBytes();
DatagramPacket packet = new DatagramPacket(data, data.length, 
    InetAddress.getByName("localhost"), 9999);
socket.send(packet);

// Receive
byte[] buffer = new byte[1024];
DatagramPacket received = new DatagramPacket(buffer, buffer.length);
socket.receive(received);

Ports and Well-Known Services

// Common port numbers:
// 20, 21 - FTP
// 22 - SSH
// 23 - Telnet
// 25 - SMTP
// 53 - DNS
// 80 - HTTP
// 443 - HTTPS
// 3306 - MySQL
// 5432 - PostgreSQL

// Check if a port is available
public static boolean isPortAvailable(int port) {
    try (ServerSocket socket = new ServerSocket(port)) {
        return true;
    } catch (IOException e) {
        return false;
    }
}

Exception Handling in Networking

Networking operations can fail in many ways:

try {
    InetAddress address = InetAddress.getByName("invalid.host.example");
} catch (UnknownHostException e) {
    System.err.println("Host not found: " + e.getMessage());
}

try {
    Socket socket = new Socket("localhost", 8080);
    socket.setSoTimeout(5000);  // Read timeout
    // ... operations ...
} catch (ConnectException e) {
    System.err.println("Connection refused");
} catch (SocketTimeoutException e) {
    System.err.println("Connection or read timed out");
} catch (IOException e) {
    System.err.println("I/O error: " + e.getMessage());
}

Common Networking Exceptions

Exception Cause
UnknownHostException DNS lookup failed
ConnectException Connection refused
SocketTimeoutException Operation timed out
BindException Port already in use
NoRouteToHostException Network unreachable
SocketException General socket error

System Properties for Networking

// Proxy settings
System.setProperty("http.proxyHost", "proxy.example.com");
System.setProperty("http.proxyPort", "8080");
System.setProperty("https.proxyHost", "proxy.example.com");
System.setProperty("https.proxyPort", "8080");

// Prefer IPv4
System.setProperty("java.net.preferIPv4Stack", "true");

// DNS cache TTL (seconds)
java.security.Security.setProperty("networkaddress.cache.ttl", "60");

Best Practices

  1. Always close resources: Use try-with-resources
  2. Set timeouts: Prevent indefinite waiting
  3. Handle exceptions gracefully: Network is unreliable
  4. Use appropriate buffer sizes: Balance memory and performance
  5. Consider threading: Don't block the main thread
// Good: try-with-resources and timeout
try (Socket socket = new Socket()) {
    socket.connect(new InetSocketAddress("localhost", 8080), 5000);
    socket.setSoTimeout(10000);
    // ... operations ...
} catch (IOException e) {
    // Handle gracefully
}

Java networking: InetAddress represents hosts, Socket connects to TCP servers, ServerSocket accepts connections, DatagramSocket handles UDP, URL and URLConnection access web resources. TCP is reliable but slower, UDP is fast but unreliable. Always handle exceptions and set timeouts. Close resources with try-with-resources. Common ports: 80 (HTTP), 443 (HTTPS), 22 (SSH).

© 2026 forEach. All rights reserved.

Privacy Policy•Terms of Service