Networking

networking1InetAddress

Path
pkg10networking/networking1InetAddress.java
Package
pkg10networking
Study order
1
Run
Single-file source launch
Command
java pkg10networking/networking1InetAddress.java
Lesson
Back to the chapter

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg10networking/networking1InetAddress.java
1package pkg10networking;2 3import java.net.InetAddress;4import java.net.NetworkInterface;5import java.net.UnknownHostException;6import java.util.Enumeration;7 8/*9 * networking1InetAddress.java10 * ---------------------------11 * Identifying hosts: IP addresses, hostnames, and local network interfaces.12 *13 * DEFINITION:14 *   InetAddress represents an IP address (v4 or v6). It maps between hostnames15 *   and addresses (DNS) and lets you inspect the machine's own interfaces.16 *17 * KEY POINTS:18 *   - getLocalHost() returns this machine; getByName() resolves any host (needs DNS).19 *   - getLoopbackAddress() (127.0.0.1 / ::1) always works offline.20 *   - isReachable() does an ICMP/echo-style ping (may need privileges).21 *   - NetworkInterface enumerates real NICs (Ethernet, Wi-Fi, loopback).22 */23public class networking1InetAddress {24 25    public static void main(String[] args) throws Exception {26        // Loopback is always available, no network required27        InetAddress loop = InetAddress.getLoopbackAddress();28        System.out.println("Loopback : " + loop.getHostName() + " -> " + loop.getHostAddress());29 30        // This machine31        try {32            InetAddress local = InetAddress.getLocalHost();33            System.out.println("Localhost: " + local.getHostName() + " -> " + local.getHostAddress());34        } catch (UnknownHostException e) {35            System.out.println("Localhost: (could not resolve) " + e.getMessage());36        }37 38        // DNS resolution of an external name (skipped gracefully if offline)39        try {40            InetAddress[] all = InetAddress.getAllByName("dns.google");41            System.out.println("\ndns.google resolves to:");42            for (InetAddress a : all) System.out.println("  " + a.getHostAddress());43        } catch (UnknownHostException e) {44            System.out.println("\nDNS lookup skipped (offline): " + e.getMessage());45        }46 47        // Local network interfaces48        System.out.println("\nNetwork interfaces:");49        Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();50        while (nics != null && nics.hasMoreElements()) {51            NetworkInterface nic = nics.nextElement();52            System.out.printf("  %-20s up=%-5s loopback=%s%n",53                    nic.getDisplayName(), nic.isUp(), nic.isLoopback());54        }55    }56}