My simple library

..of useful code



Chapters

Complete Networking Concepts and Java Socket Programming

Transmission Control Protocol (TCP)

TCP or Transmission Control Protocol allows secure communication between different applications. TCP is a connection-oriented protocol which means that once a connection is established, data can be transmitted in two directions. This protocol is typically used over the Internet Protocol. Therefore, TCP is also referred to as TCP/IP. TCP has built-in methods to examine for errors and ensure the delivery of data in the order it was sent, making it a complete protocol for transporting information like still images, data files, and web pages.

User Datagram Protocol (UDP)

UDP or User Datagram Protocol is a connection-less protocol that allows data packets to be transmitted between different applications. UDP is a simpler Internet protocol in which error-checking and recovery services are not required. In UDP, there is no overhead for opening a connection, maintaining a connection, or terminating a connection. In UDP, the data is continuously sent to the recipient, whether they receive it or not.

Port Number

A port number is a method to recognize a particular process connecting internet or other network information when it reaches a server. The port number is used to identify different applications uniquely. The port number behaves as a communication endpoint among applications. The port number is correlated with the IP address for transmission and communication among two applications. There are 65,535 port numbers, but not all are used every day.

Protocol

A network protocol is an organized set of commands that define how data is transmitted between different devices in the same network. Network protocols are the reason through which a user can easily communicate with people all over the world and thus play a critical role in modern digital communications. For Example - TCP, FTP, POP, etc.

MAC Address

MAC address stands for Media Access Control address. It is a bizarre identifier that is allocated to a NIC (Network Interface Controller/ Card). It contains a 48 bit or 64-bit address, which is combined with the network adapter. MAC address can be in hexadecimal composition. In simple words, a MAC address is a unique number that is used to track a device in a network.

Socket

A socket is one endpoint of a two-way communication connection between the two applications running on the network. The socket mechanism presents a method of inter-process communication (IPC) by setting named contact points between which the communication occurs. A socket is tied to a port number so that the TCP layer can recognize the application to which the data is intended to be sent.

Connection-oriented and connection-less protocol

In a connection-oriented service, the user must establish a connection before starting the communication. When the connection is established, the user can send the message or the information, and after this, they can release the connection. However, In connectionless protocol, the data is transported in one route from source to destination without verifying that the destination is still there or not or if it is ready to receive the message. Authentication is not needed in the connectionless protocol.

Example of Connection-oriented Protocol - Transmission Control Protocol (TCP)

Example of Connectionless Protocol - User Datagram Protocol (UDP)

TCP vs IP

Feature TCP (Transmission Control Protocol) IP (Internet Protocol)
Purpose Ensures reliable, ordered, and error-checked delivery of data between applications. Provides addressing and routing of packets across networks.
Type Connection-oriented Connectionless
Function Manages data transmission between devices, ensuring data integrity and order. Routes packets of data from the source to the destination based on IP addresses.
Error Handling Yes, includes error checking and recovery mechanisms. No, IP itself does not handle errors; relies on upper-layer protocols like TCP.
Flow Control Yes, includes flow control mechanisms. No
Congestion Control Yes, manages network congestion. No
Data Segmentation Breaks data into smaller packets and reassembles them at the destination. Breaks data into packets but does not handle reassembly.
Header Size Larger, 20-60 bytes Smaller, typically 20 bytes
Reliability Provides reliable data transfer Does not guarantee delivery, reliability, or order.
Transmission Acknowledgment Yes, acknowledges receipt of data packets. No

TCP vs UDP

Basis Transmission Control Protocol (TCP) User Datagram Protocol (UDP)
Type of Service TCP is a connection-oriented protocol. Connection orientation means that the communicating devices should establish a connection before transmitting data and should close the connection after transmitting the data. UDP is the Datagram-oriented protocol. This is because there is no overhead for opening a connection, maintaining a connection, or terminating a connection. UDP is efficient for broadcast and multicast types of network transmission.
Reliability TCP is reliable as it guarantees the delivery of data to the destination router. The delivery of data to the destination cannot be guaranteed in UDP.
Error checking mechanism TCP provides extensive error-checking mechanisms. It is because it provides flow control and acknowledgment of data. UDP has only the basic error-checking mechanism using checksums.
Acknowledgment An acknowledgment segment is present. No acknowledgment segment.
Sequence Sequencing of data is a feature of Transmission Control Protocol (TCP). this means that packets arrive in order at the receiver. There is no sequencing of data in UDP. If the order is required, it has to be managed by the application layer.
Speed TCP is comparatively slower than UDP. UDP is faster, simpler, and more efficient than TCP.
Retransmission Retransmission of lost packets is possible in TCP, but not in UDP. There is no retransmission of lost packets in the User Datagram Protocol (UDP).
Header Length TCP has a (20-60) bytes variable length header. UDP has an 8 bytes fixed-length header.
Weight TCP is heavy-weight. UDP is lightweight.
Handshaking Techniques Uses handshakes such as SYN, ACK, SYN-ACK It's a connectionless protocol i.e. No handshake
Broadcasting TCP doesn't support Broadcasting. UDP supports Broadcasting.
Protocols TCP is used by HTTP, HTTPS, FTP, SMTP and Telnet. UDP is used by DNS, DHCP, TFTP, SNMP, RIP, and VoIP.
Stream Type The TCP connection is a byte stream. UDP connection is a message stream.
Overhead Low but higher than UDP. Very low.
Applications This protocol is primarily utilized in situations when a safe and trustworthy communication procedure is necessary, such as in email, on the web surfing, and in military services. This protocol is used in situations where quick communication is necessary but where dependability is not a concern, such as VoIP, game streaming, video, and music streaming, etc.

Java Networking Classes

The java.net package of the Java programming language includes various classes that provide an easy-to-use means to access network resources. The classes covered in the java.net package are given as follows:

CacheRequest

The CacheRequest class is used in java whenever there is a need to store resources in ResponseCache. The objects of this class provide an edge for the OutputStream object to store resource data into the cache.

CookieHandler

The CookieHandler class is used in Java to implement a callback mechanism for securing up an HTTP state management policy implementation inside the HTTP protocol handler. The HTTP state management mechanism specifies the mechanism of how to make HTTP requests and responses.

CookieManager

The CookieManager class is used to provide a precise implementation of CookieHandler. This class separates the storage of cookies from the policy surrounding accepting and rejecting cookies. A CookieManager comprises a CookieStore and a CookiePolicy.

DatagramPacket

The DatagramPacket class is used to provide a facility for the connectionless transfer of messages from one system to another. This class provides tools for the production of datagram packets for connectionless transmission by applying the datagram socket class.

InetAddress

The InetAddress class is used to provide methods to get the IP address of any hostname. An IP address is expressed by a 32-bit or 128-bit unsigned number. InetAddress can handle both IPv4 and IPv6 addresses.

ServerSocket

The ServerSocket class is used for implementing system-independent implementation of the server-side of a client/server Socket Connection. The constructor for ServerSocket class throws an exception if it can't listen on the specified port. For example - it will throw an exception if the port is already being used.

Socket

The Socket class is used to create socket objects that help the users in implementing all fundamental socket operations. The users can implement various networking actions such as sending, reading data, and closing connections. Each Socket object built using java.net.Socket class has been connected exactly with 1 remote host; for connecting to another host, a user must create a new socket object.

DatagramSocket

The DatagramSocket class is a network socket that provides a connection-less point for sending and receiving packets. Every packet sent from a datagram socket is individually routed and delivered. It can further be practiced for transmitting and accepting broadcast information. Datagram Sockets is Java's mechanism for providing network communication via UDP instead of TCP.

Proxy

A proxy is a changeless object and a kind of tool or method or program or system, which serves to preserve the data of its users and computers. It behaves like a wall between computers and internet users. A Proxy Object represents the Proxy settings to be applied with a connection.

URL

The URL class in Java is the entry point to any available sources on the internet. A Class URL describes a Uniform Resource Locator, which is a signal to a "resource" on the World Wide Web. A source can denote a simple file or directory, or it can indicate a more difficult object, such as a query to a database or a search engine.

URLConnection

The URLConnection class in Java is an abstract class describing a connection of a resource as defined by a similar URL. The URLConnection class is used for assisting two distinct yet interrelated purposes. Firstly it provides control on interaction with a server(especially an HTTP server) than a URL class. Furthermore, with a URLConnection, a user can verify the header transferred by the server and can react consequently. A user can also configure header fields used in client requests using URLConnection.

Java Networking Interfaces

The java.net package of the Java programming language includes various interfaces also that provide an easy-to-use means to access network resources. The interfaces included in the java.net package are as follows:


CookiePolicy

The CookiePolicy interface in the java.net package provides the classes for implementing various networking applications. It decides which cookies should be accepted and which should be rejected. In CookiePolicy, there are three pre-defined policy implementations, namely ACCEPT_ALL, ACCEPT_NONE, and ACCEPT_ORIGINAL_SERVER.

Socket Class Methods

S No. Method Description
1 public void connect(SocketAddress host, int timeout) This method is used to connect the socket to the particularized host. This method is required only when the user instantiates the Socket applying the no-argument constructor.
2 public int getPort() This method is used to return the port to which the socket is pinned on the remote machine.
3 public InetAddress getInetAddress() This method is used to return the location of the other computer to which the socket is connected.
4 public int getLocalPort() This method is used to return the port to which the socket is joined on the local machine.
5 public SocketAddress getRemoteSocketAddress() This method returns the location of the remote socket.
6 public InputStream getInputStream() This method is used to return the input stream of the socket. This input stream is combined with the output stream of the remote socket.
7 public OutputStream getOutputStream() This method is used to return the output stream of the socket. The output stream is combined with the input stream of the remote socket.
8 public void close() This method is used to close the socket, which causes the object of the Socket class to no longer be able to connect again to any server.

ServerSocket Class Methods

S no. Method Description
1 public int getLocalPort() This method is used to return the port that the server socket is monitoring on. This method is beneficial if a user passed 0 as the port number in a constructor and lets the server find a port for him.
2 public void setSoTimeout(int timeout) This method is used to set the time-out value for the time in which the server socket pauses for a client during the accept() method.
3 public Socket accept() This method waits for an incoming client. This method is blocked till either a client combines to the server on the specified port or the socket times out, considering that the time-out value has been set using the setSoTimeout() method. Otherwise, this method will be blocked indefinitely.
4 public void bind(SocketAddress host, int backlog) This method is used to bind the socket to the particularized server and port in the object of SocketAddress. The user should use this method if he has instantiated the ServerSocket using the no-argument constructor.

Socket Programming

Java Socket programming is practiced for communication between the applications working on different JRE. Sockets implement the communication tool between two computers using TCP. Java Socket programming can either be connection-oriented or connection-less. In Socket Programming, Socket and ServerSocket classes are managed for connection-oriented socket programming. However, DatagramSocket and DatagramPacket classes are utilized for connection-less socket programming.

A client application generates a socket on its end of the communication and strives to combine that socket with a server. When the connection is established, the server generates an object of socket class on its communication end. The client and the server can now communicate by writing to and reading from the socket.

Steps to establishing a TCP connection between two computing devices using Socket Programming


The following are the steps that occur on establishing a TCP connection between two computers using socket programming are given as follows:

  • Step 1 - The server instantiates a ServerSocket object, indicating at which port number communication will occur.
  • Step 2 - After instantiating the ServerSocket object, the server requests the accept() method of the ServerSocket class. This program pauses until a client connects to the server on the given port.
  • Step 3 - After the server is idling, a client instantiates an object of Socket class, defining the server name and the port number to connect to.
  • Step 4 - After the above step, the constructor of the Socket class strives to connect the client to the designated server and the port number. If communication is authenticated, the client forthwith has a Socket object proficient in interacting with the server.
  • Step 5 - On the server-side, the accept() method returns a reference to a new socket on the server connected to the client's socket.


After the connections are stabilized, communication can happen using I/O streams. Each object of a socket class has both an OutputStream and an InputStream. The client's OutputStream is correlated to the server's InputStream, and the client's InputStream is combined with the server's OutputStream. Transmission Control Protocol (TCP) is a two-way communication protocol. Hence information can be transmitted over both streams at the corresponding time.

Client Side Example

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

public class clientSide {
    // initialize socket and input output streams
    private Socket socket = null;
    private DataInputStream input = null;
    private DataOutputStream out = null;

    // constructor to put ip address and port
    public clientSide(String address, int port) {
        // establish a connection
        try {
            socket = new Socket(address, port);
            System.out.println("Connected");

            // takes input from terminal
            input = new DataInputStream(System.in);

            // sends output to the socket
            out = new DataOutputStream(socket.getOutputStream());
        }
        catch (UnknownHostException u) {
            System.out.println(u);
        }
        catch (IOException i) {
            System.out.println(i);
        }

        // string to read message from input
        String line = "";

        // keep reading until "End" is input
        while (!line.equals("End")) {
            try {
                line = input.readLine();
                out.writeUTF(line);
            }
            catch (IOException i) {
                System.out.println(i);
            }
        }

        // close the connection
        try {
            input.close();
            out.close();
            socket.close();
        }
        catch (IOException i) {
            System.out.println(i);
        }
    }

    public static void main(String[] args) {
        clientSide client = new clientSide("127.0.0.1", 5000);
    }
}

Server Side Example

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

public class serverSide {
    // initialize socket and input stream
    private Socket socket = null;
    private ServerSocket server = null;
    private DataInputStream in = null;

    // constructor with port
    public serverSide(int port) {
        // starts server and waits for a connection
        try {
            server = new ServerSocket(port);
            System.out.println("Server started");
            System.out.println("Waiting for a client ...");

            socket = server.accept();
            System.out.println("Client accepted");

            // takes input from the client socket
            in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));

            String line = "";

            // reads message from client until "End" is sent
            while (!line.equals("End")) {
                try {
                    line = in.readUTF();
                    System.out.println(line);
                }
                catch (IOException i) {
                    System.out.println(i);
                }
            }

            System.out.println("Closing connection");

            // close connection
            socket.close();
            in.close();
        }
        catch (IOException i) {
            System.out.println(i);
        }
    }

    public static void main(String[] args) {
        serverSide server = new serverSide(5000);
    }
}

Advantages and Disadvantages

Advantages of TCP/IP Model

  • Interoperability: The TCP/IP model allows different types of computers and networks to communicate with each other, promoting compatibility and cooperation among diverse systems.
  • Scalability: TCP/IP is highly scalable, making it suitable for both small and large networks, from local area networks (LANs) to wide area networks (WANs) like the internet.
  • Standardization: It is based on open standards and protocols, ensuring that different devices and software can work together without compatibility issues.
  • Flexibility: The model supports various routing protocols, data types, and communication methods, making it adaptable to different networking needs.
  • Reliability: TCP/IP includes error-checking and retransmission features that ensure reliable data transfer, even over long distances and through various network conditions.

Disadvantages of TCP/IP Model

  • Complex Configuration: Setting up and managing a TCP/IP network can be complex, especially for large networks with many devices. This complexity can lead to configuration errors.
  • Security Concerns: TCP/IP was not originally designed with security in mind. While there are now many security protocols available (such as SSL/TLS), they have been added on top of the basic TCP/IP model, which can lead to vulnerabilities.
  • Inefficiency for Small Networks: For very small networks, the overhead and complexity of the TCP/IP model may be unnecessary and inefficient compared to simpler networking protocols.
  • Limited by Address Space: Although IPv6 addresses this issue, the older IPv4 system has a limited address space, which can lead to issues with address exhaustion in larger networks.
  • Data Overhead: TCP, the transport protocol, includes a significant amount of overhead to ensure reliable transmission. This can reduce efficiency, especially for small data packets or in networks where speed is crucial.

Advantages of UDP

  • Speed: UDP is faster than TCP because it does not have the overhead of establishing a connection and ensuring reliable data delivery.
  • Lower latency: Since there is no connection establishment, there is lower latency and faster response time.
  • Simplicity: UDP has a simpler protocol design than TCP, making it easier to implement and manage.
  • Broadcast support: UDP supports broadcasting to multiple recipients, making it useful for applications such as video streaming and online gaming.
  • Smaller packet size: UDP uses smaller packet sizes than TCP, which can reduce network congestion and improve overall network performance.
  • User Datagram Protocol (UDP) is more efficient in terms of both latency and bandwidth.

Disadvantages of UDP

  • No reliability: UDP does not guarantee delivery of packets or order of delivery, which can lead to missing or duplicate data.
  • No congestion control: UDP does not have congestion control, which means that it can send packets at a rate that can cause network congestion.
  • Vulnerable to attacks: UDP is vulnerable to denial-of-service attacks, where an attacker can flood a network with UDP packets, overwhelming the network and causing it to crash.
  • Limited use cases: UDP is not suitable for applications that require reliable data delivery, such as email or file transfers, and is better suited for applications that can tolerate some data loss, such as video streaming or online gaming.

How is UDP used in DDoS attacks?

A UDP flood attack is a type of Distributed Denial of Service (DDoS) attack where an attacker sends a large number of User Datagram Protocol (UDP) packets to a target port.

UDP Protocol: Unlike TCP, UDP is connectionless and doesn't require a handshake before data transfer. When a UDP packet arrives at a server, it checks the specified port for listening applications. If no app is found, the server sends an ICMP "destination unreachable" packet to the supposed sender (usually a random bystander due to spoofed IP addresses).

Attack Process:

  1. The attacker sends UDP packets with spoofed IP sender addresses to random ports on the target system.
  2. The server checks each incoming packet's port for a listening application (usually not found due to random port selection).
  3. The server sends ICMP "destination unreachable" packets to the spoofed sender (random bystanders).
  4. The attacker floods the victim with UDP data packets, overwhelming its resources.

HTTP and JSON Examples

HTTP Request Example

// Step 1: Create a neat value object to hold the URL
URL url = new URL("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY");

// Step 2: Open a connection on the URL and cast the response
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

// Now it's "open", we can set the request method, headers etc.
connection.setRequestProperty("accept", "application/json");

// This line makes the request
InputStream responseStream = connection.getInputStream();

JSON Processing Examples

Reading JSON from URL

private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
        sb.append((char) cp);
    }
    return sb.toString();
}

public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    try {
        BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
        String jsonText = readAll(rd);
        JSONObject json = new JSONObject(jsonText);
        return json;
    } finally {
        is.close();
    }
}

public static void main(String[] args) throws IOException, JSONException {
    JSONObject json = readJsonFromUrl("https://graph.facebook.com/19292868552");
    System.out.println(json.toString());
    System.out.println(json.get("id"));
}

Creating and Parsing JSON Objects

public static void main(String[] args) {
    // Converting JSON data into Java String format
    String k = "{\"Full Name\":\"Ritu Sharma\", \"Tuition Fees\":65400.0, \"Roll No.\":1704310046}";
    Object file = JSONValue.parse(k);

    // In java JSONObject is used to create JSON object
    JSONObject jsonObjectdecode = (JSONObject)file;

    // Converting into Java Data type
    // format From Json is the step of Decoding.
    String name = (String)jsonObjectdecode.get("Full Name");
    double fees = (Double)jsonObjectdecode.get("Tuition Fees");
    long rollno = (Long)jsonObjectdecode.get("Roll No.");
    System.out.println(name + " " + fees + " " + rollno);
}

Creating JSON Document

// Program for print data in JSON format.
public class JavaJsonEncoding {
    public static void main(String args[]) {
        // In java JSONObject is used to create JSON object
        // which is a subclass of java.util.HashMap.
        JSONObject file = new JSONObject();

        file.put("Full Name", "Ritu Sharma");
        file.put("Roll No.", new Integer(1704310046));
        file.put("Tuition Fees", new Double(65400));

        // To print in JSON format.
        System.out.print(file);
    }
}

Loading JSON from File

public static void main(String[] args) throws Exception {
    File f = new File("file.json");
    if (f.exists()){
        InputStream is = new FileInputStream("file.json");
        String jsonTxt = IOUtils.toString(is, "UTF-8");
        System.out.println(jsonTxt);
        JSONObject json = new JSONObject(jsonTxt);
        String a = json.getString("1000");
        System.out.println(a);
    }
}

Creating and Writing JSON to File

public class CreatingJSONDocument {
    public static void main(String[] args) {
        //Creating a JSONObject object
        JSONObject jsonObject = new JSONObject();
        //Inserting key-value pairs into the json object
        jsonObject.put("ID", "1");
        jsonObject.put("First_Name", "Shikhar");
        jsonObject.put("Last_Name", "Dhawan");
        jsonObject.put("Date_Of_Birth", "1981-12-05");
        jsonObject.put("Place_Of_Birth", "Delhi");
        jsonObject.put("Country", "India");
        try {
            FileWriter file = new FileWriter("E:/output.json");
            file.write(jsonObject.toJSONString());
            file.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("JSON file created: "+jsonObject);
    }
}

HTTP Components

HTTP Components Action performed
HttpClient.Builder A builder of HTTP Clients.
HttpRequest.BodyPublisher A BodyPublisher converts high-level Java objects into a flow of byte buffers suitable for sending as a request body.
HttpRequest.Builder A builder of HTTP requests.
HttpResponse<T> An HTTP response.
HttpResponse.BodyHandler<T> A handler for response bodies.
HttpResponse.BodySubscriber<T> A BodySubscriber consumes response body bytes and converts them into a higher-level Java type.
HttpResponse.PushPromiseHandler<T> A handler for push promises.
HttpResponse.ResponseInfo Initial response information supplied to a BodyHandler when a response is initially received and before the body is processed.