Skip to content
Tutorials Center
My learning

Topics

Lesson 140 of 201 Β· Networking

Networking Basics

Learn the networking basics every Java developer needs - IP addresses, ports, TCP vs UDP, DNS, InetAddress, parsing URIs and URLs, and talking to 127.0.0.1.

Almost every Java program you'll write professionally talks over a network: a web server answering browsers, a service calling another service, an app reading from a database on another machine. Before you open sockets or send HTTP requests, you need a clear picture of the pieces involved: addresses that identify machines, ports that identify programs on a machine, protocols (TCP and UDP) that move bytes between them, and URIs that name resources.

This lesson explains those ideas and the Java classes that model them: InetAddress, InetSocketAddress, URI and URL. The following lessons build on it with TCP Sockets, UDP and the HTTP Client.

Our code runner has no internet access. DNS lookups of real hostnames fail, and nothing outside the sandbox can be reached. Every example here talks to 127.0.0.1, the loopback address, which means "this same machine", so a server and a client can live in one program. On your own computer, the same code works against real hosts.

IP addresses

An IP address identifies a network interface on a machine. There are two versions in use:

  • IPv4: 32 bits, written as four decimal numbers from 0 to 255: 192.168.1.20. There are only about 4.3 billion of them, which ran out long ago.
  • IPv6: 128 bits, written as eight groups of hexadecimal digits, with one run of zero groups shortened to ::: 2001:db8::8a2e:370:7334.

Some addresses have special meanings:

Address Meaning
127.0.0.1 (IPv4), ::1 (IPv6) loopback: this machine; traffic never leaves it
0.0.0.0, :: "any address": a server bound here listens on every interface
10.x.x.x, 172.16.x.x–172.31.x.x, 192.168.x.x private ranges used inside homes and companies, not routable on the internet
224.0.0.0–239.255.255.255 multicast groups

In Java, java.net.InetAddress represents an IP address, with subclasses Inet4Address and Inet6Address.

Java Working with InetAddress

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

getHostAddress() prints IPv6 addresses in full (0:0:0:0:0:0:0:1 for ::1). Look at the raw bytes: 192 and 168 print as -64 and -88. Java's byte is signed (βˆ’128 to 127), so values above 127 wrap around. Use Byte.toUnsignedInt(b) when you need 0–255. toString() shows hostname/address, with the hostname part empty when none is known.

DNS: from names to addresses

People use names like api.example.com; networks use addresses. DNS (Domain Name System) translates between them. InetAddress.getByName("api.example.com") asks the operating system's resolver, which consults the local hosts file and DNS servers. getAllByName returns every address for a name, since big sites often have several IPv4 and IPv6 addresses.

Lookups can be slow and can fail, so they throw the checked UnknownHostException. The JVM also caches results (successful lookups for 30 seconds by default; you can tune it with the networkaddress.cache.ttl security property).

Java Name lookups and failure

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

localhost resolves through the machine's hosts file, so it works here (you may see 127.0.0.1, ::1 or both, depending on the system). example.com fails in our sandbox only because there's no internet; on your computer it resolves. The .invalid top-level domain is reserved and never resolves anywhere, which makes it handy in tests.

Ports

An IP address gets data to the right machine; a port gets it to the right program on that machine. A port is a 16-bit number, 0 to 65535. A server listens on a port; a client connects to address + port, and the client's own side automatically gets a temporary ephemeral port chosen by the OS.

Range Name Examples
0–1023 well-known (often need admin rights to listen on) 22 SSH, 25 SMTP, 53 DNS, 80 HTTP, 443 HTTPS
1024–49151 registered 3306 MySQL, 5432 PostgreSQL, 6379 Redis, 8080 alternative HTTP
49152–65535 dynamic / ephemeral picked by the OS for client sockets

Only one program can listen on a given address and port at a time. Java models an address + port pair as InetSocketAddress. Asking for port 0 means "any free port, please", which is perfect for tests and for the examples in these lessons.

Java Ports, InetSocketAddress and BindException

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The actual port number differs every run, so the example only checks that one was assigned. BindException: Address already in use is the error you'll see when you start a server twice, or when another program already uses the port.

TCP vs UDP

Two transport protocols carry almost all traffic on top of IP:

TCP UDP
Connection yes: a handshake sets up a connection first no: each datagram stands alone
Delivery reliable: lost data is resent best effort: datagrams may be lost
Order bytes arrive in the order sent datagrams may arrive out of order or duplicated
Data model a continuous stream of bytes, no message boundaries separate messages (datagrams) up to ~64 KB
Overhead higher (acknowledgments, flow and congestion control) very low
Used by HTTP/1.1 and HTTP/2, databases, SSH, email DNS queries, video calls, games, metrics; QUIC (HTTP/3) builds on it
Java classes Socket, ServerSocket, SocketChannel DatagramSocket, DatagramChannel

The "stream with no boundaries" point surprises many beginners: if a TCP client sends "Hello" and then "World", the server may read "HelloWorld" in one call or "Hel" and "loWorld" in two. Applications add their own framing, such as one message per line or a length prefix. You'll do exactly that in TCP Sockets.

A first conversation over TCP

Here's a preview of the next lesson: a tiny server and client in one program. The server runs on its own thread, accepts one connection, reads one line and replies. The client connects to 127.0.0.1 on the server's port. Lines (\n) frame the messages.

Java A server and a client on 127.0.0.1

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The server's line and the client's first line can appear in either order, since they're printed by different threads. Notice the pieces from this lesson: the server binds to the loopback address on a free port, the client gets its own ephemeral port, TCP carries the bytes reliably, and the line ending frames the message. Explicit StandardCharsets.UTF_8 makes the text encoding independent of the platform (Character Sets and Encoding).

URIs and URLs

A URI (Uniform Resource Identifier) names a resource; a URL is a URI that also says how to reach it. The general shape is:

TEXT
  https://ana:[email protected]:8443/books/search?q=java&page=2#results
  \___/   \________/ \______________/ \__/\___________/ \___________/ \_____/
 scheme    userinfo        host       port    path          query     fragment

In Java, use java.net.URI for parsing, building and comparing. It's a pure value class: it never touches the network. java.net.URL is older, its constructors are deprecated since Java 20, and its equals may even do DNS lookups. Create a URL only when an API needs one, with uri.toURL().

Java Parsing and resolving URIs

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Things to notice:

  • getPort() returns -1 when the URI has no explicit port; the scheme's default (443 for https) is implied, not filled in.
  • resolve follows the same rules a browser uses for relative links, and normalize removes . and .. segments.
  • URLEncoder encodes text for query strings and form data (application/x-www-form-urlencoded): spaces become +, & becomes %26, and non-ASCII letters become their UTF-8 bytes in %XX form. Always pass the charset. Don't use it for path segments, where a space must be %20.
  • URI.create throws IllegalArgumentException (wrapping URISyntaxException) for illegal characters such as a raw space. new URI(...) throws the checked URISyntaxException directly.

Networking terms in one place

A few words come up in every networking book. Here they are in one table, with the Java class that matches each:

Term Meaning In Java
Protocol The rules two programs follow to talk: message format, order, error handling (HTTP, FTP, SMTP, DNS) URL.getProtocol(), HttpClient, your own line protocol
IP address The number that identifies a host on a network (192.168.1.5, ::1) InetAddress
Port A number from 0 to 65535 that identifies one program on a host int in Socket, InetSocketAddress
Socket One endpoint of a conversation: an address plus a port Socket, ServerSocket, DatagramSocket
Connection-oriented protocol Both sides set up a connection first, and the protocol guarantees delivery and order (TCP) Socket and ServerSocket
Connectionless protocol Each message stands alone, with no setup and no guarantee (UDP) DatagramSocket, DatagramPacket
Client / server The server waits at a known address; the client starts the conversation ServerSocket.accept() and new Socket(host, port)
MAC address The hardware address of a network card, used inside a local network NetworkInterface.getHardwareAddress()
Localhost / loopback The computer talking to itself (127.0.0.1, ::1) InetAddress.getLoopbackAddress()

Asking about this computer and about a URL

InetAddress.getLocalHost() returns the address that the machine's own host name resolves to, and getHostName() gives you the name back (it may do a reverse DNS lookup, so it can be slow). Neither is reliable for "my address on the network": a computer can have many addresses, so use NetworkInterface when you need them all. For programs that only talk to themselves, getLoopbackAddress() always works.

A URL knows its default port: getDefaultPort() returns 80 for http, 443 for https and 21 for ftp, while getPort() returns -1 when the URL doesn't spell a port out. A URLConnection can also map file names to MIME types: URLConnection.getFileNameMap() returns a FileNameMap whose single method, getContentTypeFor(String fileName), looks at the extension and returns something like text/html, or null if the extension is unknown. That is how a simple file server decides which Content-Type header to send.

Java Default ports and file name to MIME type

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The runner prints null for archive.xyz because the table does not know that extension. Always handle null and fall back to application/octet-stream.

Caching HTTP responses (ResponseCache)

java.net.ResponseCache is a hook for caching what URLConnection/HttpURLConnection downloads. You subclass it, register one instance with the static ResponseCache.setDefault(cache), and from then on every URLConnection asks your cache first. A cache implements two methods: get(URI, String requestMethod, Map<String, List<String>> requestHeaders) returns a CacheResponse if it has a stored answer (or null for a miss), and put(URI, URLConnection) is called for each response and may return a CacheRequest whose getBody() stream receives a copy of the body. The classes CacheRequest and CacheResponse are the two halves: one to write into the cache, one to read out of it. Because this needs real web servers, the code is read-only:

Java
ResponseCache.setDefault(new ResponseCache() {
    private final Map<URI, byte[]> store = new ConcurrentHashMap<>();

    @Override public CacheResponse get(URI uri, String method, Map<String, List<String>> headers) {
        byte[] body = store.get(uri);
        if (body == null) return null;                    // miss: go to the network
        return new CacheResponse() {
            @Override public Map<String, List<String>> getHeaders() { return Map.of("Content-Type", List.of("text/html")); }
            @Override public InputStream getBody() { return new ByteArrayInputStream(body); }
        };
    }

    @Override public CacheRequest put(URI uri, URLConnection connection) {
        ByteArrayOutputStream copy = new ByteArrayOutputStream();
        return new CacheRequest() {
            @Override public OutputStream getBody() { return copy; }          // the JDK writes the body here
            @Override public void abort() { }                                 // discard on failure
        };
    }
});

The newer java.net.http.HttpClient does not use ResponseCache; it has no built-in cache, so store responses yourself if you need them.

Where to go from here

The rest of this chapter turns these concepts into working programs. TCP Sockets builds an echo server with proper framing and closing. UDP with DatagramSocket sends independent datagrams. The Java HTTP Client uses java.net.http.HttpClient, the modern way to call web APIs. Real network code waits a lot, which is exactly what virtual threads are good at.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. What does URI.create("https://example.com/shop").getPort() return?

    getPort returns -1 when the URI doesn't contain a port. The default port of the scheme is implied but not stored.
  2. 2. A TCP client sends "Hi" and then "there" with two separate writes. What might a single read on the server return?

    TCP delivers bytes reliably and in order but doesn't preserve write boundaries. Applications frame messages, for example with line endings.
  3. 3. Which address should a test server bind to so that only programs on the same machine can reach it?

    The loopback address never leaves the machine. 0.0.0.0 listens on every interface, including ones reachable from the network.
  4. 4. What does new ServerSocket(0) do?

    Port 0 asks the OS for a free ephemeral port. Read it back with getLocalPort().
  5. 5. What does URLEncoder.encode("a b&c", StandardCharsets.UTF_8) return?

    URLEncoder uses form encoding, where a space becomes + and & becomes %26.

Summary

  • An IP address (IPv4 or IPv6) identifies a machine's interface; 127.0.0.1/::1 is loopback, 0.0.0.0 means all interfaces. Java models addresses with InetAddress.
  • DNS turns names into addresses; InetAddress.getByName and getAllByName look them up and throw UnknownHostException on failure. Literal IPs need no lookup.
  • A port (0–65535) identifies a program on a machine; InetSocketAddress is address + port; port 0 asks for any free port; a busy port gives BindException.
  • TCP is a reliable, ordered byte stream with connections; UDP sends independent, unreliable datagrams with little overhead.
  • Use URI to parse, build, resolve and normalize; convert to URL only when an API requires it. Encode query values with URLEncoder and an explicit charset.
  • Our sandbox has no internet: examples run a server and client together on 127.0.0.1.

Next: TCP Sockets, where you'll build a complete echo server and client with ServerSocket and Socket.