Implement the data link layer framing methods such as Bit stuffing in java program

import java.util.*;
public class BitStuffing {
    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        System.out.print("Enter the number of bit String :");
        int n = s.nextInt();
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = s.nextInt();
        }
        String flag = "01111110";
        String s2 = "";
        int count = 0;
        int c = 0;// Number of Stuffing Bits
        for (int i = 0; i < n; i++) {
            if (arr[i] == 1) {
                count++;
                s2 += arr[i];
            } else {
                count = 0;
                s2 += arr[i];
            }
            if (count == 5 && i != n - 1) {
                i++;
                if (arr[i] == 1) {
                    s2 += '0';
                    c++;
                    i--;
                } else {
                    s2 += arr[i];
                }
                count = 0;
            }
        }
        System.out.println(flag + " " + s2 + " " + flag);
        System.out.println("Total Number of Stuffing Bits : " + c);
    }

} 

Write a program to implement character stuffing.👇

import java.util.Scanner;
public class CharStuffing {
    public static void main(String[] args) {
        String a, fs = " ", t, s, d, x, y;
        char sd, ed;
        int i;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter characters to be stuffed:");
        a = sc.nextLine();
        System.out.print("\nEnter a character that represents starting delimiter:");
        sd = sc.next().charAt(0);
        System.out.print("\nEnter a character that represents ending delimiter:");
        ed = sc.next().charAt(0);
        x = s = String.valueOf(sd);
        x += s += "";
        y = d = String.valueOf(ed);
        d += y += "";
        fs += x;
        for (i = 0; i < a.length(); i++) {
            t = String.valueOf(a.charAt(i));
            if (t.equals(String.valueOf(sd)))
                fs += s;
            else if (t.equals(String.valueOf(ed)))
                fs += d;
            else
                fs += t;
        }
        fs += y;
        System.out.println("\nAfter stuffing:" + fs);
        sc.close();
    }
}

Write a program to implement Dijkstra algorithm to compute shortest path through graph. 

class DijkastraAlgorithm {
    public static void dijkstra(int[][] graph, int source) {
        int count = graph.length;
        boolean[] visitedVertex = new boolean[count];
        int[] distance = new int[count];
        for (int i = 0; i < count; i++) {
            visitedVertex[i] = false;
            distance[i] = Integer.MAX_VALUE;
        }
        distance[source] = 0;
        for (int i = 0; i < count; i++) {
            int u = findMinDistance(distance, visitedVertex);
            visitedVertex[u] = true;
            for (int v = 0; v < count; v++) {
                if (!visitedVertex[v] && graph[u][v] != 0 && (distance[u] + graph[u][v] < distance[v])) {
                    distance[v] = distance[u] + graph[u][v];
                }
            }
        }
        for (int i = 0; i < distance.length; i++) {
            System.out.println(String.format("Distance from %s to %s is %s", source, i, distance[i]));
        }
    }

    private static int findMinDistance(int[] distance, boolean[] visitedVertex) {
        int minDistance = Integer.MAX_VALUE;
        int minDistanceVertex = -1;
        for (int i = 0; i < distance.length; i++) {
            if (!visitedVertex[i] && distance[i] < minDistance) {
                minDistance = distance[i];
                minDistanceVertex = i;
            }
        }
        return minDistanceVertex;
    }

    public static void main(String[] args) {
        int graph[][] = new int[][] { { 0, 0, 1, 2, 0, 0, 0 },
                { 0, 0, 2, 0, 0, 3, 0 },
                { 1, 2, 0, 1, 3, 0, 0 },
                { 2, 0, 1, 0, 0, 0, 1 },
                { 0, 0, 3, 0, 0, 2, 0 },
                { 0, 3, 0, 0, 2, 0, 1 },
                { 0, 0, 0, 1, 0, 1, 0 } };
        dijkstra(graph, 0);
    }
}

Write a program to implement Distance vector routing.

import java.util.Arrays;

public class DistanceVectorRouting {
    private static final int INF = Integer.MAX_VALUE;

    public static void main(String[] args) {
        int[][] graph = {
                { 0, 2, INF, 1, INF },
                { 2, 0, 3, 2, INF },
                { INF, 3, 0, INF, 1 },
                { 1, 2, INF, 0, 1 },
                { INF, INF, 1, 1, 0 }
        };
        int numNodes = graph.length;
        int[][] distanceTable = new int[numNodes][numNodes];
        // Initialize the distance table with the initial graph
        for (int i = 0; i < numNodes; i++) {
            distanceTable[i] = Arrays.copyOf(graph[i], numNodes);
        }
        // Perform distance vector routing algorithm
        for (int k = 0; k < numNodes; k++) {
            for (int i = 0; i < numNodes; i++) {
                for (int j = 0; j < numNodes; j++) {
                    if (distanceTable[i][j] > distanceTable[i][k] + distanceTable[k][j]) {
                        distanceTable[i][j] = distanceTable[i][k] + distanceTable[k][j];
                    }
                }
            }
        }
        // Print the final routing table
        System.out.println("Final Routing Table:");
        for (int i = 0; i < numNodes; i++) {
            for (int j = 0; j < numNodes; j++) {
                System.out.print(distanceTable[i][j] == INF ? "INF\t" : distanceTable[i][j] + "\t");
            }
            System.out.println();
        }
    }
}

Write a program to implement DES algorithm

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.util.Base64;
import java.util.Scanner;

class DESExample {
    Cipher ecipher;
    Cipher dcipher;

    DESExample(SecretKey key) throws Exception {
        ecipher = Cipher.getInstance("DES");
        dcipher = Cipher.getInstance("DES");
        ecipher.init(Cipher.ENCRYPT_MODE, key);
        dcipher.init(Cipher.DECRYPT_MODE, key);
    }

    public String encrypt(String str) throws Exception {hello
        // Encode the string into bytes using utf-8
        byte[] utf8 = str.getBytes("UTF8");
        // Encrypt
        byte[] enc = ecipher.doFinal(utf8);
        // Encode bytes to base64 to get a string
        return Base64.getEncoder().encodeToString(enc);
    }

    public String decrypt(String str) throws Exception {
        // Decode base64 to get bytes
        byte[] dec = Base64.getDecoder().decode(str);
        byte[] utf8 = dcipher.doFinal(dec);
        // Decode using utf-8
        return new String(utf8, "UTF8");
    }

    public static void main(String[] argv) throws Exception {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter secret Text");
        final String secretText = sc.nextLine();
        System.out.println("SecretText: " + secretText);
        SecretKey key = KeyGenerator.getInstance("DES").generateKey();
        DESExample encrypter = new DESExample(key);
        String encrypted = encrypter.encrypt(secretText);
        System.out.println("Encrypted Value: " + encrypted);
        String decrypted = encrypter.decrypt(encrypted);
        System.out.println("Decrypted: " + decrypted);
    }
}

Write a program to perform LAN Connectivity.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

class LANConnectivity {
    private static final int PORT = 12345;

    public static void main(String[] args) {
        startServer();
        startClient();
    }

    private static void startServer() {
        new Thread(() -> {
            try {
                ServerSocket serverSocket = new ServerSocket(PORT);
                System.out.println("Server started. Waiting for incoming connections...");
                Socket clientSocket = serverSocket.accept();
                System.out.println("Client connected: " + clientSocket.getInetAddress().getHostAddress());
                BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
                // Read and process client messages
                String message;
                while ((message = in.readLine()) != null) {
                    System.out.println("Received from client: " + message);
                    out.println("Server acknowledges: " + message);
                }
                // Close resources
                in.close();
                out.close();
                clientSocket.close();
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    private static void startClient() {
        new Thread(() -> {
            try {
                Socket socket = new Socket("localhost", PORT);
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                // Send messages to server
                out.println("Hello, server!");
                String response = in.readLine();
                System.out.println("Received from server: " + response);
                out.println("How are you?");
                response = in.readLine();
                System.out.println("Received from server: " + response);
                // Close resources
                in.close();
                out.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

Write a program to implement CRC Polynomial.

import java.util.*;
public class CRC_Polynomials {
    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        System.out.println("Enter the number of message bit m :");
        int m = s.nextInt();
        int msg[] = new int[m];
        System.out.println("Enter the message in  form of '0' & '1' ");
        for (int i = 0; i < m; i++) {
            msg[i] = s.nextInt();
        }
        System.out.println("Enter the number of deviser bit d :");
        int d = s.nextInt();
        int dev[] = new int[d];
        System.out.println("Enter thr deviser in form of '0' & '1' ");
        for (int i = 0; i < d; i++) {
            dev[i] = s.nextInt();
        }
        int rem[] = divideDataWithDivisor(msg, dev);
        for (int i = 0; i < rem.length - 1; i++) {
            System.out.print(rem[i]);
        }
        System.out.println("\nGenerated CRC code is: ");
        for (int i = 0; i < msg.length; i++) {
            System.out.print(msg[i]);
        }
        for (int i = 0; i < rem.length - 1; i++) {
            System.out.print(rem[i]);
        }
        System.out.println();
        int sentData[] = new int[msg.length + rem.length];
        System.out.println("Enter bits in the array which you want to send: ");
        System.out.println("Enter bit " + (sentData.length - 1) + ":");
        for (int i = 0; i < sentData.length - 1; i++) {
            sentData[i] = s.nextInt();
        }
        receiveData(sentData, dev);
    }

    static int[] divideDataWithDivisor(int oldData[], int dev[]) {
        int rem[] = new int[dev.length];
        int i;
        int data[] = new int[oldData.length + dev.length];
        System.arraycopy(oldData, 0, data, 0, oldData.length);
        System.arraycopy(data, 0, rem, 0, dev.length);
        for (i = 0; i < oldData.length; i++) {
            System.out.println((i + 1) + ".) First data bit is : " + rem[0]);
            System.out.print("Remainder : ");
            if (rem[0] == 1) {
                for (int j = 1; j < dev.length; j++) {
                    rem[j - 1] = exorOperation(rem[j], dev[j]);
                    System.out.print(rem[j - 1]);
                }
            } else {
                for (int j = 1; j < dev.length; j++) {
                    rem[j - 1] = exorOperation(rem[j], 0);
                    System.out.print(rem[j - 1]);
                }
            }
            rem[dev.length - 1] = data[i + dev.length];
            System.out.println(rem[dev.length - 1]);
        }
        return rem;
    }

    static int exorOperation(int x, int y) {
        if (x == y) {
            return 0;
        }
        return 1;
    }

    static void receiveData(int msg[], int dev[]) {

        int rem[] = divideDataWithDivisor(msg, dev);
        for (int i = 0; i < rem.length; i++) {
            if (rem[i] != 0) {
                System.out.println("Currupted data received...");
                return;
            }
        }
        System.out.println("Data received without any error.");
    }
}
Tausif

Hi! My name is TAUSIF AHMAD I have completed B.Tech in Computer Science from Maulana Azad National Urdu University Hyderabad. I am always ready to have new experiences meet new people and learn new things. 1. I am very interested in Frontend Development. 2. I love video editing and graphics designing. 3. I enjoy challenges that enables to grow. 4. I am part time Blogger.

Post a Comment (0)
Previous Post Next Post