Showing posts with label Networking. Show all posts
Showing posts with label Networking. Show all posts

Saturday, March 24, 2018

Program Execution Time


This JAVA program will help you to find total time taken by FOR loop of the program. You can extend this JAVA program to find total execution time of the program.

Program will display Total time taken in milliseconds. 

Program Execution Time

class TimeTaken 
{
    public static void main(String[] args) 
    {
        long startTime = System.currentTimeMillis();
        long sum = 0;
        for (int i = 0; i < 10000000; i++) 
        {
            sum = sum + i;
        }
        long endTime = System.currentTimeMillis();
        long timetaken = endTime - startTime;

        System.out.println("FOR loop execution time = " + timetaken + " milliseconds.");
    }
}

Output of program

FOR loop execution time = 14 milliseconds.

Monday, January 1, 2018

Program to display IP Address

C Program to display local IP Address.

#include<stdlib.h>
int main()
{
   system("C:\\Windows\\System32\\ipconfig");
   return 0;
}

Output of program

Program to display IP Address

Note: 
This program tested on Windows 7 OS.
Some of the details are intentionally removed for security reasons.

Tuesday, October 10, 2017

FTP server client simulation using socket program

This JAVA socket program will download webpage (HTML file) from server to client. Downloaded file will be opened into web browser.

SERVER side program

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

public class FTPServer {
  public static void main(String[] args) throws IOException {
    //server will start at port number 12345.
    ServerSocket servsock = new ServerSocket(12345);

    //server will send index1.htm file to client.
    File myFile = new File("D:\\index1.htm");
    System.out.println("Waiting for Client Request...");
    while (true) {
      Socket sock = servsock.accept();
      byte[] mybytearray = new byte[(int) myFile.length()];
      BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));
      bis.read(mybytearray, 0, mybytearray.length);
      OutputStream os = sock.getOutputStream();
      os.write(mybytearray, 0, mybytearray.length);
      os.flush();
      sock.close();
    }
  }
}

SERVER side Output:

Waiting for Client Request...



CLIENT side program

import java.awt.Desktop;
import java.io.*;
import java.net.*;

public class FTPClient {
  public static void main(String[] argv) throws Exception {

    //socket will be created local IP: 127.0.0.1 and port 12345.
    Socket sock = new Socket("127.0.0.1", 12345);
    byte[] mybytearray = new byte[1024];
   
    InputStream is = sock.getInputStream();
    FileOutputStream fos = new FileOutputStream("D:\\index2.htm");
    BufferedOutputStream bos = new BufferedOutputStream(fos);
   
    int bytesRead = is.read(mybytearray, 0, mybytearray.length);
    bos.write(mybytearray, 0, bytesRead);
   
    System.out.println("File downloaded...");
   
    Following code will open index2.htm file in browser.

    String url="D:\\index2.htm";
    File htmlFile=new File(url);
    Desktop.getDesktop().browse(htmlFile.toURI());

    bos.close();
    sock.close();
  }
}

CLIENT side output:

File downloaded...
BUILD SUCCESSFUL (total time: 1 second)



Saturday, March 11, 2017

What is Socket?

Introduction to Socket Programming

  • A Socket is used for communication between two devices.
  • Socket can be defined using IP Address and Port number.
  • Socket programming is possible using C as well as Java.
  • Socket connection is supported by all platforms/OS. (Windows, Unix, Mac, etc.).
  • It is used in a client server application over network.

Sample Applications based on Socket Programming:

  • Echo Client-Server Socket Application
  • Chat Application
  • Math Client-Server Socket Application
  • Simulation of ARP using Socket
  • IP Class Finder using Socket


Thursday, March 2, 2017

AES Encryption Decryption

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.KeyGenerator;

public class AESEncryptionDecryption {
   
    public static void main(String[] args) {
      try{
          Cipher cipher = Cipher.getInstance("AES");
          KeyGenerator kg = KeyGenerator.getInstance("AES");
          Key key = kg.generateKey();

          cipher.init(Cipher.ENCRYPT_MODE, key);
          CipherInputStream cipt=new CipherInputStream(new FileInputStream(new File("D:\\PlainTextInput.txt")), cipher);
          FileOutputStream fip=new FileOutputStream(new File("D:\\EncryptedText.txt"));

          int i;
          while((i=cipt.read())!=-1)
          {
             fip.write(i);
          }

          cipher.init(Cipher.DECRYPT_MODE, key);
          CipherInputStream ciptt=new CipherInputStream(new FileInputStream(new File("D:\\EncryptedText.txt")), cipher);
          FileOutputStream fop=new FileOutputStream(new File("D:\\DecryptedText.txt"));

          int j;
          while((j=ciptt.read())!=-1)
          {
             fop.write(j);
          }

        }
        catch(Exception e) {
           e.printStackTrace();
        }
      System.out.println("Encryption and Decryption of plain text file performed successfully.");
    }
}

Output of the program:

Encryption and Decryption of plain text file performed successfully.

Content of PlainTextInput.txt file: HelloStudent

Content of EncryptedText.txt file: ùóà ¬x9f¯—©c aá

Content of DecryptedText.txt file: HelloStudent 

Note: You need to create PlainTextInput.txt file in D:\ drive of computer. Execution of program will create EncryptedText.txt and DecryptedText.txt file in D:\ drive.

Tuesday, February 28, 2017

Count Server Socket

Definition: Program to demonstrate use of Page views count on server.
Count server program will increment page view counter for every client request.

Count Server Socket Program

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

public class CountServer {

    public static void main(String[] args) throws IOException {

        ServerSocket ss = new ServerSocket(1234);
        Socket cs = null;
        System.out.println("Waiting for connection.....");
        int count=0;
        while(true){
            cs = ss.accept();          
            count++;
            System.out.println("Total visitors:"+count);
            cs.close();
        }
        //ss.close();
    }
}

Output on Server screen

Waiting for connection.....
Total visitors:1

//Validations and exception handling to be added.

Count Client Socket Program

/* This program will just create socket with server. Note: try-catch clauses are not added to keep logic simple…*/

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

public class CountClient
{
   public static void main(String[] args) throws IOException
   {
         Socket s1 = new Socket("localhost", 1234);
         System.out.println("Hello");
         s1.close();
   }
}

Output on Client screen

Hello

Monday, February 27, 2017

Chat Server Socket

Following two socket programs demonstrate basic Chat application. You need to add additional functionalities and exception handling according to your needs.

Chat Server Socket Program

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

public class ChatServer {
    public static void main(String[] args) throws IOException {

        ServerSocket ss = new ServerSocket(1234);
        Socket cs = null;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Waiting for connection.....");
        cs = ss.accept();      
        BufferedReader in = new BufferedReader(new InputStreamReader(cs.getInputStream()));
        PrintWriter out = new PrintWriter(cs.getOutputStream(), true);
        String inputLine, serverInput;
        while(true){
            inputLine = in.readLine();
            System.out.println("Client: " + inputLine);
            System.out.print("Server:");
            serverInput = br.readLine();
            out.println(serverInput);
        }
        out.close();
        in.close();
        cs.close();
        ss.close();
    }
}
//You may add exit condition in while loop of server socket.

Output on server screen:

Waiting for connection.....
Client: hello
Server:hello client
Client: how are you?
Server:I am fine...what about you?


Chat Client Socket Program

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

public class ChatClient {
    public static void main(String[] args) throws IOException
   {
         Socket s1 = new Socket("localhost", 1234);
         DataInputStream is = new DataInputStream(s1.getInputStream());
        // String request = "Hello";
         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
         PrintWriter out = new PrintWriter(s1.getOutputStream(),true);
         System.out.print("Client:");
         String request = br.readLine();
         while(!(request.contentEquals("bye"))){
            out.println(request);
            String reply = is.readLine();
            System.out.println("Server:" + reply);
            System.out.print("Client:");
            request = br.readLine();
         }
         out.close();                   
         is.close();
         s1.close();
   }
}

Output on Client Screen:

Client:hello
Server:hello client
Client:how are you?
Server:I am fine...what about you?
Client:bye

Echo Client Server Socket

Following two programs are written in JAVA. You have to run Server program first, and then run client program. Server program will reply the message sent by client.


Simple Echo Server Program

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

public class SimpleEchoServer1 {
 public static void main(String[] args) throws IOException    {

    ServerSocket ss = new ServerSocket(123);
    Socket cs = null;     
    System.out.println ("Waiting for connection.....");
   
    cs = ss.accept();     
    System.out.println ("Waiting for input.....");

    BufferedReader in = new BufferedReader(new InputStreamReader(cs.getInputStream()));
    PrintWriter out = new PrintWriter(cs.getOutputStream(),true);

    String inputLine = in.readLine();
    out.println(inputLine);
    System.out.println ("Reply sent...");

    out.close();    
    in.close();    
    cs.close();    
    ss.close();
   }
}

Output on server:

Waiting for connection.....
Waiting for input.....
Reply sent...


Simple Echo Client Program

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

public class SimpleEchoClient1 {
   public static void main(String[] args) throws IOException   {
         Socket s1 = new Socket("localhost", 123);
         DataInputStream is = new DataInputStream(s1.getInputStream());
         System.out.print("Enter your string:");
         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
         String request = br.readLine();
    
         PrintWriter out = new PrintWriter(s1.getOutputStream(),true);
         out.println(request);       
         String reply = is.readLine();
         System.out.println("Echo from Server:" + reply);
         
         out.close();           
      is.close();         
      s1.close();
   } 
}

Output on Client Screen:

Enter your string:hello
Echo from Server:hello



Saturday, February 4, 2017

ARP Simulation

This program will find Physical Address for the given IP address. 


/* Sample arp.txt file generated using arp -a command
  192.168.3.3           f4-f4-9c-18-bb-4b     dynamic   
  192.168.3.2           ca-f8-87-a3-ee-20     dynamic   
  192.168.90.255        ff-ff-ff-ff-ff-ff     static    
  221.0.0.251           03-01-ef-00-ff-fc     static    
  29.253.251.20         02-01-ed-ff-00-fa     static
*/
#include<stdio.h>
#include<stdlib.h>
int main()
{
  FILE *f1, *fopen();
  int ch;
  char str1[80], *token;
  const char str[80] = "", s[2] = " ";
  f1 = fopen("arp.txt","r");
  if ( f1 == NULL )     /* check does file exist*/ 
 
printf("Cannot open file for reading \n" ); 
exit(1);    
 
  while(fgets(str1,80,f1)!=NULL){
  token = strtok(str1,s);
  while (token != NULL){
      if (strcmp(token,"192.168.3.2") ==0)
  {
  token = strtok(NULL, s);
  printf("Your Physical address is %s",token);
      }
      else
      token = strtok(NULL, s);
    }
  }
  fclose(f1);
  return 0;
}

Output of the program

Your Physical address is ca-f8-87-a3-ee-20


Tuesday, January 31, 2017

Program to Print Process ID

Following C program will print Process ID.

#include<stdio.h>
int main(void)
{
printf("My process ID %ld",getpid());
return 0;
}

Output of the program:

My process ID 2213.

Note: You will get different process ID on your system.

* * * * *

Saturday, January 28, 2017

Bit Stuffing Simulation

Networking  >> Bit Stuffing Simulation Program


In bit stuffing processing, we add 0 after five consecutive 1's in databits.

#include<stdio.h>
int main()
{
 int i=0,count=0;
 char databits[80];

 printf("Enter Data Bits: ");
 scanf("%s",databits);

 printf("Data Bits Before Bit Stuffing:%s",databits);
 printf("\nData Bits After Bit stuffing :");
 
 for(i=0; i<strlen(databits); i++)
 {
    if(databits[i]=='1')
        count++;
    else
        count=0;
printf("%c",databits[i]);
  if(count==5)
    {
        printf("0");
        count=0;
    }
 }
 return 0;
}

Output of the Program:

Enter Data Bits: 101111111000
Data Bits Before Bit Stuffing:101111111000
Data Bits After Bit stuffing :1011111011000

Back to Networking Page >


Playfair Key Matrix Generation: Keyword validation according to the specification given in the algorithm.


/*Playfair Key Matrix Generation: Keyword validation according to the specification given in the algorithm.*/

#include<stdio.h>

int main(){

  char key[10];
  int i,j,flag=0, cnt=0, key_check[26]={};

  printf("Enter your keyword:");
  scanf("%s",key);

  //Logic to count character frequency in MONARCHY
  for(i=0; i<strlen(key); i++)
  {
key_check[key[i]%65]++;
  }

  for(i=0; i<26; i++)
  {
if(key_check[i] > 1)
flag=1;
//Logic to display frequency
//printf("%c=%d \n",i+65, key_check[i]);
  }

  if(flag==1)
printf("Keyword %s is not suitable for generating Playfair Key Matrix.", key);
  else
printf("Keyword %s is ok for generating Playfair Key Matrix.", key);

  return 0;
}

//This program will check only keywords enter in Capital letters.

Output - 1
Enter your keyword:MONARCHY
Keyword MONARCHY is ok for generating Playfair Key Matrix.

Output - 2
Enter your keyword:HELLO
Keyword HELLO is not suitable for generating Playfair Key Matrix.


Sunday, December 25, 2016

Networking - Simulation of Framing Concept.

Networking: Simulation of Framing Concept using C language.

Assumptions:

1. Header contains following parameters:
    FrameNumber, SourceIP, DestinationIP,FiveCharacters of Data
2. SourceIP=192.168.1.1
3. DestinationIP=192.168.1.2
4. Input data is taken from input.txt file.
5. Generated Frames will be stored in output.txt file.

#include <stdio.h>
int main()  
{
  FILE *fp1, *fp2, *fopen(); 
  int i;
  char c,cnt=49; 
  fp1 = fopen("input.txt","r");  
  // open for reading
  fp2 = fopen("output.txt","w") ; 
  //open for writing

  if ( fp1 == NULL )
 
printf("Cannot open input.txt." ); 
exit(1);    
 
  else if ( fp2 == NULL ) 
 
printf("Cannot open output.txt."); 
exit(1);    
 
  else 
  {
  c = getc(fp1) ;  
  while ( c != EOF) 
 
putc(cnt++,fp2);
fputs(",192.168.1.1,192.168.1.2,",fp2);
//Logic to track 5 characters
for(i=0;i<5;i++) 
{
putc( c,  fp2); //Write to Output.txt 
c =  getc( fp1 ) ;
//putc(10,fp2);
}
putc(10,fp2);
  }
  printf("Frames generated in Output.txt file.");
  fclose(fp1); //close files
  fclose(fp2); 
  }
  return 0; 
}

Output of the program:

Frames generated in Output.txt file.

Sample content in input.txt file is as under:

Hello students, how are you?

After execution of program content of output.txt file:

1,192.168.1.1,192.168.1.2,Hello
2,192.168.1.1,192.168.1.2, stud
3,192.168.1.1,192.168.1.2,ents,
4,192.168.1.1,192.168.1.2, how 
5,192.168.1.1,192.168.1.2,are y
6,192.168.1.1,192.168.1.2,ou?ÿÿ

* * * * *




Saturday, December 24, 2016

Networking - UDP Header implementation

This C program generates UDP Header with following assumptions:

1. Sample data in input.txt file: ABC
2. Source Port=1100, Destination Port=1101
3. Total length=50
4. You may use your logic for Checksum calculation.


#include <stdio.h>
void main()  
{
FILE *fp1, *fp2, *fopen(); 
int src_port=1100, dest_port=1101, total_len=50,checksum=0;
char c;

fp1 = fopen( "input.txt",  "r" );       /* open for reading */ 
fp2 = fopen( "UDPHeader.txt", "w" ) ; /* open for writing */

if ( fp1 == NULL )     /* check file exist/not  */ 
{
printf("Cannot open input.txt for reading." ); 
exit(1);     /* Exit program */ 

else if ( fp2 == NULL ) 
{
printf("Cannot open UDPHeader.txt for writing."); 
exit(1);     /* Exit program */ 

else 
{
c = getc(fp1) ;
while ( c != EOF) 
{
checksum = checksum + c;
c =  getc( fp1 ) ;

fprintf(fp2,"%d,%d,%d,",src_port,dest_port,total_len);
fprintf(fp2,"%d",checksum);
printf("UDP Header created successfully in UDPHeader.txt file.");
fclose(fp1); /*close files */
fclose(fp2); 


}

Output of the program

UDP Header created successfully in UDPHeader.txt file.

Data after program execution in UDPHeader.txt file:

1100,1101,50,198
* * * * *