←Back to Subject
Notes
Notes
Study material and explanations
Diagrams
Diagrams
Visualize concepts easily
Mnemonics
Mnemonics
Tricks to remember faster
One Night Prep
One Night Prep
Short and focused revision
Revision
Revision
Quick summary and key points
Important Questions
Important Questions
Practice most relevant questions
Notes

Networking Basics, Networking Classes & Using java.net Package

Study material and explanations for Unit 4

Networking Basics, Networking Classes & Using java.net Package

1. Networking Basics in Java

Java Networking (Network Programming) is the concept of connecting two or more computing devices together over a network (LAN or the Internet) so that Java programs running on different machines can share data and communicate with each other.

Java provides built-in networking support through the java.net package.

5 Fundamental Networking Terms You Must Know:

Figure 4.4: Core Building Blocks of Java Network Communication
1. IP Address
Unique numerical street address of a computer on the network (e.g., 192.168.1.1)
2. Port Number (0–65535)
16-bit apartment/door number identifying a specific application on that computer (e.g., HTTP = 80)
3. Protocol
Set of communication rules: TCP (Reliable, Connection-oriented) & UDP (Fast, Connectionless)
4. Socket (IP + Port)
The two-way communication endpoint connecting a Client and a Server
  1. IP Address (Internet Protocol Address): A unique logical address assigned to every machine on a network (e.g., IPv4 142.250.193.14 or localhost 127.0.0.1).
    • Analogy: The Building Address of a hostel.
  2. Port Number: A single computer can run many network applications at once (Web browser, Email client, MySQL server). A Port Number (16-bit integer from 0 to 65,535) uniquely identifies a specific application/process on that computer (e.g., Port 80 for HTTP, Port 3306 for MySQL).
    • Analogy: The specific Room Number inside that hostel building!
  3. Protocol: A set of rules governing how data is transmitted across a network:
    • TCP (Transmission Control Protocol): Connection-oriented, reliable, guaranteed delivery in order (like a phone call).
    • UDP (User Datagram Protocol): Connectionless, fast, best-effort delivery of independent packets called Datagrams (like sending a postcard/SMS).
  4. MAC Address: Physical 48-bit hardware address burned into the Network Interface Card (NIC).
  5. Socket: The combination of an IP Address + Port Number that serves as one endpoint of a two-way communication link between two programs on a network.

2. Overview of the java.net Package (Classes & Interfaces)

The java.net package provides all the classes and interfaces required for both low-level (Socket/Datagram) and high-level (URL/Web) network programming:

Core Classes in java.net:

  1. InetAddress: Represents an IP address (both IPv4 and IPv6) and resolves Domain Names (DNS) into IP addresses.
  2. URL (Uniform Resource Locator): Represents a web address pointing to a resource on the World Wide Web.
  3. URLConnection & HttpURLConnection: Represents an active communication link to a URL resource to read headers and content.
  4. Socket: Implements the Client-side endpoint for reliable TCP communication.
  5. ServerSocket: Implements the Server-side endpoint that listens for incoming TCP client requests.
  6. DatagramSocket: A socket for sending and receiving connectionless UDP datagram packets.
  7. DatagramPacket: Represents the actual data packet sent or received via UDP.

Core Interfaces in java.net:

  • SocketOptions: Declares methods to get and set low-level socket configuration options.
  • ContentHandlerFactory & URLStreamHandlerFactory: Used to handle custom MIME types and protocols.
  • FileNameMap: Maps between a filename and a MIME type string.

3. The InetAddress Class (Working with IP Addresses & DNS)

The InetAddress class encapsulates both the Host Name (e.g., "www.google.com") and the numerical IP Address (e.g., "142.250.193.14").

  • Important Viva Fact: InetAddress has no public constructors! You cannot write new InetAddress(). Instead, you create an InetAddress object using static Factory Methods!

Important Factory & Instance Methods of InetAddress:

  1. static InetAddress getLocalHost(): Returns the InetAddress object of your own local computer.
  2. static InetAddress getByName(String host): Connects to DNS and returns the InetAddress for the given domain name.
  3. static InetAddress[] getAllByName(String host): Returns an array of all IP addresses mapped to a large website.
  4. String getHostName(): Returns the domain/computer name as a String.
  5. String getHostAddress(): Returns the raw IP address string (e.g., "192.168.1.5").

Example Program (InetAddressDemo.java):

import java.net.*;

public class InetAddressDemo {
    public static void main(String[] args) {
        try {
            // 1. Get Local Machine's IP and Name
            InetAddress local = InetAddress.getLocalHost();
            System.out.println("Local Computer Name: " + local.getHostName());
            System.out.println("Local IP Address   : " + local.getHostAddress());

            // 2. Resolve a Website's IP Address via DNS
            InetAddress web = InetAddress.getByName("www.dauniv.ac.in");
            System.out.println("DAVV Host Name     : " + web.getHostName());
            System.out.println("DAVV IP Address    : " + web.getHostAddress());
        } catch (UnknownHostException e) {
            System.out.println("Could not find host: " + e.getMessage());
        }
    }
}

4. The URL and URLConnection Classes

A URL (Uniform Resource Locator) is the address of a resource on the Internet. It consists of 4 parts:

https://www.campusnotes.in:443/davv/bca/java.html
├─ Protocol  : https
├─ Host Name : www.campusnotes.in
├─ Port      : 443
└─ File Path : /davv/bca/java.html

A. Methods of the URL Class:

  • getProtocol(): Returns protocol string (e.g., "https").
  • getHost(): Returns host name (e.g., "www.campusnotes.in").
  • getPort(): Returns explicit port number (or -1 if default port is used).
  • getDefaultPort(): Returns default port for the protocol (80 for HTTP, 443 for HTTPS).
  • getFile() / getPath(): Returns the resource path ("/davv/bca/java.html").
  • openConnection(): Returns a URLConnection object connected to that webpage!

B. The URLConnection Class

Once you call url.openConnection(), the URLConnection object allows you to inspect HTTP response headers (getContentType(), getContentLength(), getDate()) and read the actual HTML source code of the webpage using getInputStream()!

Complete Program Demonstrating URL and URLConnection:

import java.net.*;
import java.io.*;

public class URLDemo {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://www.example.com:443/index.html");

            // 1. Inspect URL components
            System.out.println("Protocol : " + url.getProtocol());
            System.out.println("Host Name: " + url.getHost());
            System.out.println("Port No  : " + url.getPort());
            System.out.println("File Path: " + url.getFile());

            // 2. Open URLConnection to inspect metadata
            URLConnection conn = url.openConnection();
            System.out.println("Content Type  : " + conn.getContentType());
            System.out.println("Content Length: " + conn.getContentLength());

        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

💡 Exam Preparation Tips for DAVV BCA

  • If asked “How do you create an object of InetAddress?”, emphasize that InetAddress has no public constructor and uses Factory Methods (getLocalHost(), getByName(), getAllByName()).
  • Always write the 4 parts of a URL (Protocol, Host, Port, File Path) along with their getter methods (getProtocol(), getHost(), getPort(), getFile()).