The java.net package lets Java programs work with hosts, URLs and sockets: InetAddress for names and IP addresses, URL/URLConnection/HttpURLConnection for web resources, Socket/ServerSocket for TCP, DatagramSocket/DatagramPacket/MulticastSocket for UDP, and URLEncoder/URLDecoder for form encoding.
Medium 50 minSyllabus: “Internet classes”
Mark as
The idea in one minute
Networking is like the postal and phone system. InetAddress is the directory that turns a name into a street address (an IP). A URL is a full postal address with a department and a room (protocol, host, port, path). TCP sockets are a phone call: you dial (connect), the other side picks up (accept), and you talk in order until someone hangs up. UDP datagrams are postcards: each is addressed separately, cheap and fast, but some may arrive late, out of order or not at all.
Key points — the night-before list
Package java.net. Key checked exceptions: UnknownHostException (name cannot be resolved) and MalformedURLException (bad URL) — both subclasses of IOException.
InetAddress has no public constructor: use getByName(host), getAllByName(host), getLocalHost(), getByAddress(bytes); then getHostName(), getHostAddress().
url.openConnection() → URLConnection (getContentType, getContentLength …); cast to HttpURLConnection for setRequestMethod(), getResponseCode() (200, 404), disconnect().
TCP: new ServerSocket(port) + accept() (blocks, returns a Socket) on the server; new Socket(host, port) on the client; data flows through getInputStream() / getOutputStream().
UDP: a DatagramSocket sends and receives DatagramPackets (byte[] + length, plus address and port to send); connectionless and unreliable. MulticastSocket joins 224.0.0.0–239.255.255.255 groups.
URLEncoder.encode(s, "UTF-8") makes text form-safe: space → +, other unsafe characters → %XY; URLDecoder.decode reverses it.
Ports run 0–65535; well-known 0–1023 (HTTP 80, HTTPS 443, FTP 21, SMTP 25, DNS 53). A socket endpoint = IP address + port.
01Networking basics for Java programmers
Every machine on a network has an IP address — 32 bits for IPv4, written as four dotted numbers such as 192.168.1.10, or 128 bits for IPv6. People prefer host names (www.example.com), which the Domain Name System (DNS) translates into IP addresses. A machine runs many network programs at once, so each is identified by a 16-bit port number (0–65535); ports 0–1023 are the well-known ports of standard services. The pair IP address + port is a socket endpoint.
TCP — Socket, ServerSocket
Connection-oriented: connect before talking
Reliable: lost data is retransmitted
Delivers an ordered byte stream
Flow and congestion control; more overhead
Web, e-mail, file transfer, chat
UDP — DatagramSocket, DatagramPacket
Connectionless: every packet is addressed separately
No delivery guarantee
Packets may arrive out of order or duplicated
Small header, low latency
DNS queries, live media, games, multicast
Class
Purpose
InetAddress (Inet4Address, Inet6Address)
An IP address, with host-name lookup
URL
A uniform resource locator: parse its parts, open a stream to it
URI
A generic identifier: strict parsing, never touches the network
URLConnection, HttpURLConnection
A live connection to a URL: headers, request method, response code
Socket
The client side (and each server-side end) of a TCP connection
ServerSocket
Listens on a port and accepts incoming TCP connections
DatagramSocket, DatagramPacket
Send and receive UDP packets
MulticastSocket
A UDP socket that can join multicast groups
URLEncoder, URLDecoder
Convert text to and from the application/x-www-form-urlencoded format
InetSocketAddress
An IP address and port bundled together
The main java.net classes
02InetAddress: names and IP addresses
InetAddress represents an IP address (its subclasses Inet4Address and Inet6Address cover both versions). It has no public constructor; objects come from static factory methods, which perform a DNS lookup when given a name and throw UnknownHostException when the name cannot be resolved.
Method
What it does
static getByName(String host)
One address for a name or a literal IP string
static getAllByName(String host)
Every address of a host (big sites have several) as an array
static getLocalHost()
The address of the machine the program runs on
static getByAddress(byte[] addr)
Wrap raw bytes (4 for IPv4) without any lookup
static getLoopbackAddress()
127.0.0.1 or ::1 (Java 7)
getHostName() / getHostAddress()
The name, and the address as text such as "93.184.215.14"
getAddress()
The raw address bytes
isReachable(timeoutMs)
Tries to contact the host (an echo request)
isLoopbackAddress() / isMulticastAddress()
Classify the address
JavaLooking up addresses (output depends on your network; the last call throws UnknownHostException)
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Lookup {
public static void main(String[] args) {
try {
InetAddress local = InetAddress.getLocalHost();
System.out.println("This machine: " + local); // prints name/address
InetAddress site = InetAddress.getByName("www.oracle.com");
System.out.println(site.getHostName() + " -> " + site.getHostAddress());
for (InetAddress a : InetAddress.getAllByName("www.google.com"))
System.out.println(" " + a.getHostAddress()); // a host may have many IPs
InetAddress lo = InetAddress.getByName("127.0.0.1"); // a literal needs no DNS
System.out.println(lo.isLoopbackAddress()); // true
InetAddress.getByName("no-such-host.invalid"); // cannot be resolved
} catch (UnknownHostException e) {
System.out.println("Unknown host: " + e.getMessage());
}
}
}
toString() prints hostname/literal-address, for example mypc/192.168.1.5. Lookups are cached by the JVM, and the reserved .invalid domain is guaranteed never to resolve, which makes it handy for demonstrating the exception.
03URL: anatomy, parsing and reading
https://example.com:8080/docs/index.html?lang=en#intro
└─┬─┘ └────┬────┘ └┬─┘└──────┬───────┘ └──┬──┘ └─┬─┘
protocol host port path query fragment (ref)
The parts of a URL
Method
Returns
getProtocol()
"https"
getHost()
"example.com"
getPort()
8080 — and −1 when the URL contains no explicit port
getDefaultPort()
443, the protocol's default (80 for http, 21 for ftp)
getPath()
"/docs/index.html"
getQuery()
"lang=en" (null if there is none)
getFile()
"/docs/index.html?lang=en" — path plus query
getRef()
"intro" — the fragment after #
getAuthority()
"example.com:8080"
Getters for new URL("https://example.com:8080/docs/index.html?lang=en#intro")
JavaParsing a URL and reading the first lines of the page
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class ReadPage {
public static void main(String[] args) {
try {
URL url = new URL("https://example.com/"); // textbook form (deprecated in Java 20)// modern form: URL url = java.net.URI.create("https://example.com/").toURL();
System.out.println(url.getProtocol() + " " + url.getHost() + " " + url.getPort());
try (BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()))) {
String line;
int n = 0;
while ((line = in.readLine()) != null && n++ < 5)
System.out.println(line); // the first lines of the HTML
}
} catch (MalformedURLException e) { // a subclass of IOException: first
System.out.println("Bad URL: " + e.getMessage());
} catch (IOException e) {
System.out.println("Network error: " + e.getMessage());
}
}
}
// First line printed: https example.com -1 (no explicit port in the URL)
openStream() is shorthand for openConnection().getInputStream(). The constructor throws the checked MalformedURLException when the string has no protocol ("www.x.com") or an unknown one ("htp://x"). Since Java 20 the URL constructors are deprecated in favour of URI.create(s).toURL(), because URI parses more strictly; exams still use new URL(…).
04URLConnection and HttpURLConnection
Using a URLConnection
Create
URLConnection c = url.openConnection(); — this creates the object but sends nothing yet.
Configure
setRequestProperty("Accept", "text/html"), setConnectTimeout(ms), setReadTimeout(ms), setDoOutput(true) if you will send a body.
Connect
connect() — or implicitly, the first call to getInputStream() or getResponseCode().
Read the headers
getContentType(), getContentLength() (−1 when unknown), getDate(), getLastModified(), getHeaderField(name).
Exchange the body
getInputStream() to read the response; getOutputStream() to write a request body.
Finish
Close the streams; for HTTP, disconnect() releases the connection.
JavaAn HTTP GET with status and headers (typical output: 200 OK / Type: text/html; charset=UTF-8 / Length: …)
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class Status {
public static void main(String[] args) throws IOException {
URL url = new URL("https://example.com/");
HttpURLConnection con = (HttpURLConnection) url.openConnection(); // nothing sent yet
con.setRequestMethod("GET"); // GET is the default anyway
con.setConnectTimeout(5000); // milliseconds
int code = con.getResponseCode(); // sends the request: e.g. 200
System.out.println(code + " " + con.getResponseMessage());
System.out.println("Type: " + con.getContentType());
System.out.println("Length: " + con.getContentLengthLong()); // -1 if unknown
con.disconnect();
}
}
HttpURLConnection (an abstract subclass of URLConnection) adds HTTP specifics: setRequestMethod("GET" | "POST" | …), getResponseCode() with constants HTTP_OK (200), HTTP_NOT_FOUND (404) and HTTP_INTERNAL_ERROR (500), getResponseMessage(), getErrorStream() for the body of an error response, and disconnect(). For a POST, call setDoOutput(true), set the Content-Type header and write the URL-encoded form data to getOutputStream().
Note
For new code, Java 11's java.net.http.HttpClient offers HTTP/2, asynchronous requests and a cleaner API. Exam questions on 'Internet classes' revolve around URL, URLConnection and HttpURLConnection.
05TCP sockets: ServerSocket and Socket
Server side
Bind and listen
new ServerSocket(5000) reserves port 5000 (BindException if it is already in use).
Accept
accept() blocks until a client connects, then returns a new Socket dedicated to that client.
Talk
Wrap the socket's getInputStream() / getOutputStream() in readers and writers.
Close and repeat
Close the client socket and call accept() again; to serve many clients at once, hand each accepted Socket to its own thread.
JavaAn echo server
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class EchoServer {
public static void main(String[] args) throws IOException {
try (ServerSocket server = new ServerSocket(5000)) { // bind + listen on port 5000
System.out.println("Waiting on port 5000 ...");
while (true) {
try (Socket client = server.accept(); // blocks until a client connects
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream(), true)) {
String line = in.readLine(); // one request line
out.println("ECHO: " + line); // autoflush sends it at once
} // this client's socket closes
}
}
}
}
JavaThe matching client (prints: ECHO: hello KSHB, then the two port numbers)
import java.io.*;
import java.net.Socket;
public class EchoClient {
public static void main(String[] args) throws IOException {
try (Socket s = new Socket("localhost", 5000); // connect: TCP 3-way handshake
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()))) {
out.println("hello KSHB"); // send a line
System.out.println(in.readLine()); // ECHO: hello KSHB
System.out.println("local port " + s.getLocalPort() + ", server port " + s.getPort());
}
}
}
Useful Socket methods: getInetAddress() and getPort() (the remote end), getLocalPort() (an ephemeral port picked by the OS for the client), setSoTimeout(ms) (a blocked read then throws SocketTimeoutException), shutdownOutput() and close(). Creating the client Socket throws ConnectException if nothing is listening and UnknownHostException for a bad name.
Watch out
A ServerSocket never carries data itself. accept() hands back a fresh Socket for each client, and all reading and writing goes through that Socket.
06UDP: DatagramSocket, DatagramPacket and MulticastSocket
UDP has no connections, so there is no server-socket class: both ends use a DatagramSocket, and every message travels as a DatagramPacket. A packet to send is built with the data, its length, the destination address and port — new DatagramPacket(data, data.length, address, port); a packet to receive into is just an empty buffer — new DatagramPacket(buf, buf.length). send(p) returns at once; receive(p) blocks until a packet arrives (or a setSoTimeout() deadline passes).
JavaOne program, two sockets: sending and receiving a datagram (prints: Allotment list ready from port … )
import java.net.*;
public class UdpDemo {
public static void main(String[] args) throws Exception {
try (DatagramSocket receiver = new DatagramSocket(6000); // listens on port 6000
DatagramSocket sender = new DatagramSocket()) { // any free local port
byte[] msg = "Allotment list ready".getBytes("UTF-8");
DatagramPacket out = new DatagramPacket(msg, msg.length,
InetAddress.getLoopbackAddress(), 6000); // data + destination
sender.send(out); // no connection, no handshake
byte[] buf = new byte[1024];
DatagramPacket in = new DatagramPacket(buf, buf.length); // an empty box to fill
receiver.receive(in); // blocks until a packet arrives
String text = new String(in.getData(), 0, in.getLength(), "UTF-8");
System.out.println(text + " from port " + in.getPort()); // the sender's port
}
}
}
A received packet reports getData(), getLength() (how many bytes actually arrived), getAddress() and getPort() of the sender — so a server can reply to whoever wrote. One UDP datagram over IPv4 carries at most 65,507 bytes of data; anything larger must be split by the program.
MulticastSocket (a subclass of DatagramSocket) can join a group: a class D address in 224.0.0.0–239.255.255.255. A single packet sent to the group address reaches every member that joined — ideal for announcing something to all branch offices at once. setTimeToLive() limits how many router hops multicast packets may cross.
JavaJoining and leaving a multicast group (fragment)
MulticastSocket ms = new MulticastSocket(4446);
InetAddress group = InetAddress.getByName("230.0.0.1"); // a class D (multicast) address
ms.joinGroup(group); // textbook form; deprecated since Java 14 in favour of// joinGroup(SocketAddress, NetworkInterface)
byte[] buf = new byte[256];
DatagramPacket p = new DatagramPacket(buf, buf.length);
ms.receive(p); // any packet sent to 230.0.0.1:4446 by anyone
ms.leaveGroup(group);
ms.close();
07URLEncoder, URLDecoder and the networking exceptions
Query strings and HTML form data may contain only a limited set of characters. URLEncoder converts text into the application/x-www-form-urlencoded format: letters, digits and the characters .-*_ stay as they are; a space becomes +; every other character is converted to its UTF-8 bytes, each written as %XY in hexadecimal. URLDecoder reverses the process.
JavaEncoding a value for a query string
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
public class Encode {
public static void main(String[] args) {
String raw = "Systems Manager & KSHB: 175/2026";
String enc = URLEncoder.encode(raw, StandardCharsets.UTF_8); // Java 10+ overload
System.out.println(enc); // Systems+Manager+%26+KSHB%3A+175%2F2026
System.out.println(URLDecoder.decode(enc, StandardCharsets.UTF_8)); // the original text
System.out.println("https://example.com/search?q=" + enc); // now safe inside a URL
}
}
// Older form: URLEncoder.encode(raw, "UTF-8") — throws the checked UnsupportedEncodingException.
Exception
Thrown when
UnknownHostException
A host name cannot be resolved to an IP address
MalformedURLException
A URL string has no protocol, an unknown protocol, or cannot be parsed
ConnectException
Nothing is listening at the remote host and port (connection refused)
BindException
The local port is already in use
SocketTimeoutException
accept(), read() or receive() waited longer than setSoTimeout() allows
SocketException
General socket errors, such as a connection reset by the peer
ProtocolException
An invalid request method or HTTP protocol error
Networking exceptions — all are checked subclasses of IOException
PSC favourite
Quick pairs: name → IP = InetAddress; listen and accept = ServerSocket; TCP data = Socket; UDP packet = DatagramPacket; group = MulticastSocket; HTTP status = HttpURLConnection.getResponseCode(); form encoding = URLEncoder.
Step through · A TCP echo exchange with ServerSocket and Socket
step 1 / 10
Step 1: new ServerSocket(5000)
The server binds to port 5000 and starts listening. A BindException would mean the port is already taken.
Worked examples
Try the problem first, then reveal the working one step at a time.
EX 1Taking a URL apart
For new URL("http://www.kshb.example:8080/schemes/list.php?district=TVM#apply") give getProtocol, getHost, getPort, getDefaultPort, getPath, getQuery, getFile and getRef. Then give getPort, getDefaultPort, getPath and getQuery for new URL("https://example.org/").
EX 2What happens during one echo exchange
EchoServer is running. Describe step by step what happens on both sides when EchoClient runs, and what it prints.
EX 3Form-encoding by hand
What does URLEncoder.encode("Kerala PSC: 175/2026", "UTF-8") return, and what does URLDecoder.decode("a%2Bb+c", "UTF-8") return?
EX 4Choosing the right class
Pick TCP or UDP and the java.net class(es) for: (a) uploading a 50 MB scheme document; (b) a live video feed of a site inspection; (c) a DNS-style lookup sent to a custom name server; (d) fetching a web page and checking for a 404; (e) one announcement to every branch office on the LAN.
Practice session
Work each problem on paper first, then check. Marking one solved earns 10 XP.0/5 solved
Q1
What do getPort() and getDefaultPort() return for: (a) http://example.com/a.html (b) https://example.com:8443/ (c) ftp://files.example.com/x.zip?
Q2
Name the java.net class for each job: (a) find all IP addresses of a host; (b) wait for TCP clients on port 9000; (c) hold the bytes and destination of one UDP message; (d) read the Content-Type header of a web resource; (e) receive messages sent to 239.1.1.1; (f) convert "a b" for a query string.
Q3
What does URLEncoder.encode("x=1&y=2 z", "UTF-8") return?
Q4
Write a Java client that connects to a server on host "localhost", port 7, sends the line "ping" and prints the server's one-line reply. Handle the case where no server is running.
Q5
Which exception results? (a) new URL("htp://x") (b) InetAddress.getByName("no.such.host.invalid") (c) new ServerSocket(5000) while another program holds port 5000 (d) new Socket("localhost", 5999) with nothing listening (e) receive() after setSoTimeout(2000) when no packet arrives in 2 seconds.
Exam traps
InetAddress has no public constructor — new InetAddress() does not compile; use getByName(), getAllByName(), getLocalHost() or getByAddress().
getPort() returns −1 when the URL has no explicit port; getDefaultPort() returns the protocol default (80, 443, 21).
A ServerSocket only listens and accepts; data always flows through the Socket that accept() returns.
UDP has no server-socket class — both ends use DatagramSocket, and the DatagramPacket carries the address and port.
URLEncoder turns a space into + (form encoding), not %20; use it on query values, not on a whole URL (it would encode ':' and '/').
MalformedURLException and UnknownHostException are checked (IOException subclasses); openConnection() creates the connection object but sends nothing until connect() or the first read.
Quiz — KPSC style
10 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Internet classes (java.net) · Question 1 of 10✓ 0 · ✗ 0
Which package contains Java's networking classes such as Socket and URL?