0% found this document useful (0 votes)
49 views23 pages

COMPUTER NETWORKS-3, Nitheesh.T, 21MIS0401

The document contains code and descriptions for several computer network programs including: 1. A TCP/IP socket based ATM system that validates login credentials and allows transactions if authorized. 2. A UDP program to transfer an image file from a client to a server. 3. A UDP client/server program that finds the physical address of a host when given its logical/IP address using ARP protocol. 4. A DNS client/server using UDP sockets where the client inputs a URL and the server returns the corresponding IP address.

Uploaded by

nitheesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views23 pages

COMPUTER NETWORKS-3, Nitheesh.T, 21MIS0401

The document contains code and descriptions for several computer network programs including: 1. A TCP/IP socket based ATM system that validates login credentials and allows transactions if authorized. 2. A UDP program to transfer an image file from a client to a server. 3. A UDP client/server program that finds the physical address of a host when given its logical/IP address using ARP protocol. 4. A DNS client/server using UDP sockets where the client inputs a URL and the server returns the corresponding IP address.

Uploaded by

nitheesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

COMPUTER NETWORKS

LAB DA-3

NAME: NITHEESH.T
REG NO: 21MIS0401

1.The finance office of VIT wishes to make the transactions more


secured. If you are a programmer how you will implement a system
to validate the login credentials obtained from the user thereby
denying them access to unauthorized users.
• Understating of HTTPS for transactions.
• Encryption and decryption of each transaction of message data
with security algorithms.
• Code for generation of a key for encryption and decryption using
TCP/IP client server sockets for validation and verification of
authorized users. Implement a TCP/IP socket based ATM System.
Make the server to maintain the customer details (name, card no,
pin and balance). When a client wants to withdraw amount, validate
his login with card no & pin, display a welcome message and perform
the withdraw operation if he is having sufficient balance or display a
warning message.

CODE:
package com.encoding;
import java.io.UnsupportedEncodingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
public class DesEncrypter {
Cipher ecipher;
Cipher dcipher;
DesEncrypter(SecretKey key) {
try {
ecipher = Cipher.getInstance("DES");
dcipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
} catch (javax.crypto.NoSuchPaddingException e) {
} catch (java.security.NoSuchAlgorithmException e) {
} catch (java.security.InvalidKeyException e) {
}
}
public String encrypt(String str) {
try {
byte[] utf8 = str.getBytes("UTF8");
byte[] enc = ecipher.doFinal(utf8);
return new sun.misc.BASE64Encoder().encode(enc);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}
public String decrypt(String str) {
try {
byte[] dec = new
sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] utf8 = dcipher.doFinal(dec);
return new String(utf8, "UTF8");
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}
}
Server:

import java.io.*;
import java.net.*;
class Serverside{
public static void main(String args[]) throws Exception
{
int p_no;
String c_no;
String name[]={"Nitheesh","Sanjay","Monish","Benson"};
String
user[]={"21MIS0401","21MIS0274","21MIS0409","21MIS0404",
"21MIS0351"};
int pass[]={123,456,789,012,345};
int I=-1;
while(true)
{
ServerSocket ss = new ServerSocket(1080);
Socket s = ss.accept();
InetAddress IA = InetAddress.getByName("localhost");
InputStream is = s.getInputStream();
InputStreamReader ir = new InputStreamReader(is);
BufferedReader br = new BufferedReader(ir);
OutputStream os = s.getOutputStream();
PrintStream ps = new PrintStream(os);
c_no=br.readLine();
System.out.println("\nValidating the Username...");
for(int i=0;i<5;i++)
{
if(c_no.equals(user[i]))
{ I=i;
ps.println("valid");
}}
if(I==-1) {
ps.println("invalid");
break;
}
System.out.println("\nUsername validation completed");
p_no=Integer.valueOf(br.readLine());
System.out.println("\nValidating the password...");
if(p_no==pass[I])
{ ps.println("valid");
ps.println(name[I]);
} else {
ps.println("invalid");
break;
}
System.out.println("\nPassword validation completed");
File file = new File("Clienttext.java");
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
OutputStream o = s.getOutputStream();
byte[] contents;
long fileLength = file.length();
long current = 0;
long start = System.nanoTime();
while(current!=fileLength)
{
int size = 10000;
if(fileLength-current>=size)
{
current+=size;
}
else {
size =(int)(fileLength-current);
current = fileLength;
}
contents = new
byte[size];
bis.read(contents,0,size);
o.write(contents);
}
System.out.println("Sending file");
o.flush();
s.close();
ss.close();
System.out.println("File sent succesfully");
}
}
}

Output:

C:\Users\Nitheesh>cd documents\18BIT0100
C:\Users\Nitheesh>cd documents\18BIT0100>javac Serverside.java
C:\Users\Nitheesh>cd documents\18BIT0100>javac Serverside
Validating the Username…
Username validation completed
Validating the Password…
Password validation completed
Sending file
File sent successfully

2. Write a UDP program to implement an image transfer from client


to server.
CLIENT:

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class udpBaseClient_2


{
public static void main(String args[]) throws IOException
{
Scanner sc = new Scanner(System.in);
DatagramSocket ds = new DatagramSocket();
InetAddress ip = InetAddress.getLocalHost();
byte buf[] = null;
while (true)
{
String inp = sc.nextLine();
buf = inp.getBytes();
DatagramPacket DpSend = new
DatagramPacket(buf, buf.length, ip, 1234);
ds.send(DpSend);
if (inp.equals("bye"))
break;
}
}
}

SERVER:

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class udpBaseServer_2


{
public static void main(String[] args) throws IOException
{
DatagramSocket ds = new DatagramSocket(1234);
byte[] receive = new byte[65535];
DatagramPacket DpReceive = null;
while (true)
{
DpReceive = new DatagramPacket(receive,
receive.length);
ds.receive(DpReceive);
System.out.println("Client:-" + data(receive));
if (data(receive).toString().equals("bye"))
{
System.out.println("Client sent
bye.....EXITING");
break;
}
receive = new byte[65535];
}
}
public static StringBuilder data(byte[] a)
{
if (a == null)
return null;
StringBuilder ret = new StringBuilder();
int i = 0;
while (a[i] != 0)
{
ret.append((char) a[i]);
i++;
}
return ret;
}}
OUTPUT:

Client:- Hello
Client:- I am client.

Client:- bye
Client sent bye.....EXITING

3. Find the physical address of a host when its logical address is


known (ARP protocol) using UDP.

Client:
import java.io.*;
import java.net.*;
import java.util.*;
class Clientarp
{
public static void main(String args[])
{
try
{
BufferedReader in=new BufferedReader(new
InputStreamReader(System.in));
Socket clsct=new Socket("127.0.0.1",5604);
DataInputStream din=new DataInputStream(clsct.getInputStream());
DataOutputStream dout=new
DataOutputStream(clsct.getOutputStream());
System.out.println("Enter the Logical address(IP):");
String str1=in.readLine();
dout.writeBytes(str1+'\n');
String str=din.readLine();
System.out.println("The Physical Address is: "+str);
clsct.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}

Server:
import java.io.*;
import
java.net.*;
import
java.util.*;
class Serverarp
{
public static void main(String args[])
{
try
{
ServerSocket obj=new
ServerSocket(5604);
Socket obj1=obj.accept();
while(true)
{
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStream dout=new
DataOutputStream(obj1.getOutputStream()); String
str=din.readLine();
String ip[]={"165.165.80.80","165.165.79.1"};
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
for(int i=0;i<ip.length;i++)
{
if(str.equals(ip[i]))
{
dout.writeBytes(mac[i]+'\n');
break;
}
}
obj.close();
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Output:

E:\networks>java Serverarp
E:\networks>java Clientarp
Enter the Logical address(IP):
165.165.80.80
The Physical Address is: 6A:08:AA:C2

4. Implement a DNS server and client using UDP sockets. Client


should give URL as the input and server should send the respective IP
address.
Server:
import java.io.*;
import java.net.*;
public class dnsserver
{
private static int indexOf(String[] array, String str)
{
str = str.trim();
for (int i=0; i < array.length; i++)
{
if (array[i].equals(str)) return i;
}
return -1;
}
public static void main(String arg[])throws IOException
{
String[] hosts = {"zoho.com", "gmail.com","google.com",
"facebook.com"};
String[] ip = {"172.28.251.59", "172.217.11.5","172.217.11.14",
"31.13.71.36"}; System.out.println("Press Ctrl + C to Quit");
while (true)
{
DatagramSocket serversocket=new DatagramSocket(1362);
byte[] senddata = new byte[1021];
byte[] receivedata = new byte[1021];
DatagramPacket recvpack = new DatagramPacket(receivedata,
receivedata.length);
serversocket.receive(recvpack);
String sen = new String(recvpack.getData());
InetAddress ipaddress = recvpack.getAddress();
int port = recvpack.getPort();
String capsent;
System.out.println("Request for host " + sen);
if(indexOf (hosts, sen) != -1)
capsent = ip[indexOf (hosts, sen)];
else
capsent = "Host Not Found"; senddata = capsent.getBytes();
DatagramPacket pack = new DatagramPacket (senddata,
senddata.length,ipaddress,port);
serversocket.send(pack);
serversocket.close();
}
}
}
Client:
import java.net.*;
public class dnsclient
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
DatagramSocket clientsocket = new DatagramSocket();
InetAddress ipaddress;
if (args.length == 0)
ipaddress = InetAddress.getLocalHost();
else
ipaddress = InetAddress.getByName(args[0]);
byte[] senddata = new byte[1024];
byte[] receivedata = new byte[1024];
int portaddr = 1362;
System.out.print("Enter the hostname : ");
String sentence = br.readLine();
senddata = sentence.getBytes();
DatagramPacket pack = new
DatagramPacket(senddata,senddata.length,
ipaddress,portaddr);
clientsocket.send(pack);
DatagramPacket recvpack =new
DatagramPacket(receivedata,receivedata.length);
clientsocket.receive(recvpack);
String modified = new String(recvpack.getData());
System.out.println("IP Address: " + modified);
clientsocket.close();
}
}

OUTPUT:
Server:
E:\nwlab>java dnsserver
Press Ctrl + C to Quit
Request for host google.com
Request for host flipkart.com
Client:
E:\nwlab>java dnsclient
Enter the hostname : google.com
IP Address: 172.217.11.14
E:\nwlab>java dnsclient
Enter the hostname : flipkart.com
IP Address: Host Not Found

5. Implement a UDP based socket program for the game “Guess It”.
The game is played by client and server. The game proceeds as
follows: The server will think a “magic number”. Magic number is
greater than zero and less than 100. Prompt for the “magic number”
from the client. The server should print out “Higher” if the magic
number is higher than the guess and “Lower” if the magic number is
less than the guess. Give 10 chances for the client to guess the
number. When the magic number has been guessed print "Great"
and then end. If the client cannot guess the number in 10 attempts
then print the message "Better luck next time:)" and end.
Server:
using System;
using System.Net.Sockets;
using System.Threading;

namespace TcpGames
{
public class GuessMyNumberGame : IGame
{
private TcpGamesServer _server;
private TcpClient _player;
private Random _rng;
private bool _needToDisconnectClient = false;
public string Name
{
get { return "Guess My Number"; }
}
public int RequiredPlayers
{
get { return 1; }
}
public GuessMyNumberGame(TcpGamesServer server)
{
_server = server;
_rng = new Random();
}

CLIENT:
public bool AddPlayer(TcpClient client)
{
if (_player == null)
{
_player = client;
return true;
}

return false;
}
public void DisconnectClient(TcpClient client)
{
_needToDisconnectClient = (client == _player);
}
public void Run()
{
bool running = (_player != null);
if (running)
{
Packet introPacket = new Packet("message",
"Welcome player, I want you to guess my number.\n" +
"It's somewhere between (and including) 1 and 100.\n");
_server.SendPacket(_player,
introPacket).GetAwaiter().GetResult();
}
else
return;
int theNumber = _rng.Next(1, 101);
Console.WriteLine("Our number is: {0}", theNumber);
bool correct = false;
bool clientConncted = true;
bool clientDisconnectedGracefully = false;

while (running)
{
Packet inputPacket = new Packet("input", "Your guess: ");
_server.SendPacket(_player,
inputPacket).GetAwaiter().GetResult();

Packet answerPacket = null;


while (answerPacket == null)
{
answerPacket =
_server.ReceivePacket(_player).GetAwaiter().GetResult();
Thread.Sleep(10);
}
if (answerPacket.Command == "bye")
{
_server.HandleDisconnectedClient(_player);
clientDisconnectedGracefully = true;
}
if (answerPacket.Command == "input")
{
Packet responsePacket = new Packet("message");

int theirGuess;
if (int.TryParse(answerPacket.Message, out theirGuess))
{
if (theirGuess == theNumber)
{
correct = true;
responsePacket.Message = "Correct! You win!\n";
}
else if (theirGuess < theNumber)
responsePacket.Message = "Too low.\n";
else if (theirGuess > theNumber)
responsePacket.Message = "Too high.\n";
}
else
responsePacket.Message = "That wasn't a valid
number, try again.\n";
_server.SendPacket(_player,
responsePacket).GetAwaiter().GetResult();
}
Thread.Sleep(10);

if (!_needToDisconnectClient &&
!clientDisconnectedGracefully)
clientConncted &=
!TcpGamesServer.IsDisconnected(_player);
else
clientConncted = false;

running &= clientConncted;


}
if (clientConncted)
_server.DisconnectClient(_player, "Thanks for playing
\"Guess My Number\"!");
else
Console.WriteLine("Client disconnected from game.");

Console.WriteLine("Ending a \"{0}\" game.", Name);


}
}}

You might also like