1. UNIVERSITY INSTITUTE OF
ENGINEERING AND TECHNOLOGY
KURUKSHETRA UNIVERSITY,
KURUKSHETRA (SESSION: 2020-2024)
PRACTICAL FILE
Computer Networks Lab
SUBMITTED TO: SUBMITTED BY:
Mr. Amandeep Ankit Garg
Assist professor 252002022
CSE Deptt. B.TECH. - 6 SEM. CSE-A
1
2. INDEX
S.NO AIM TEACHER’S
SIGNATURE
1.
To study various types of networking cables.
2.
Create a socket for HTTP for web page upload and download.
3.
Write a code simulating ARP /RARP protocols.
4. Study of TCP/UDP performance.
5. Performance comparison of MAC protocols
6. Performance comparison of routing protocols.
7.
To flood the server from a spoofed source address
leading to a DoSattack.
8. To sniff and parse packets that pass through using raw sockets.
2
3. 9. To implement simple calculator and invoke arithmetic operations
from a remote client.
10. To simulate a sliding window protocol that uses GO Back N ARQ
3
4. Program – 1
To study various types of networking cables.
Theory:
Twisted Pair Cables
The Twisted pair cable is one type of Ethernet cable. These are used for connection in the
local area networks. The Twisted pair cables are connected to the local router or a modem
so that we can provide internet access to the local devices. One end of the Twisted pair
cable consists of the interface card and the other end plugs are connected to a router sitch
or a modem.
The Below figure represents the Twisted pair cable.
4
5. These Ethernet Twisted pairs are dived into two types
⦁ Unshielded Twisted pairs
⦁ Shielded Twisted pairs
⦁ Unshielded Twisted pair
The Unshielded twisted pairs are the most common type of cables. It consists of four
different color code wires that are twisted into pairs. Now, why do these colors are getting
twisted? To prevent Electromagnetic interference and crosstalk, the Unshielded twisted
pairs are get twisted in pairs. The Twisted pair cables are mostly used in homes and for
many business purposes.
⦁ Shielded Twisted pair
It is similar to the shielded twisted pairs, the main difference between the two is a foil shield
is wrapped around the color-coded pairs alike from the Unshielded twisted pairs. It has an
extra layer of protection to prevent electromagnetic Interference. It is mostly used in
Industries.
For the Twisted pair cables, simply we have to connect the RJ45 connectors at both ends of
the Twisted pairs.
Coaxial Cable
All the specifications of the networking cables are present at the physical layer of the OSI
model. The Below figure represents the coaxial cable.
It consists of a sheath at the outer cover layer. This sheath is a fire-resistant plastic. To
reduce the electromagnetic interference the sheath is established at the outer covers of the
coaxial cable. Under sheath, it consists of a Teflon insulator and a copper conductor is
present at the center of the coaxial cable.
The coaxial cables are used to transmit high-frequency signals with fewer data losses. The
Coaxial cables are mostly used in telephone systems, cable TVs,
and broadband connections. we have many specifications in the coaxial cable, But most of
them use the RG number. RG stands for the Radio guide. Each number uses different data
cables. There are also many types of connectors in the coaxial cable. they are
⦁ BNC connectors
⦁ F-Type connectors
⦁ SMC connectors
⦁ N connectors
BNC and F-type connectors are also called end-type connectors. It can carry information in
the form of microwave signals.
5
6. SMA stands for the Subminiature version. It uses higher-frequency microwave systems and
Wi-Fi systems.
F-type connectors are mainly used in local connections like cable TV and cable Internet
connection.
Fibre Optic cables
The Fibre Optic cables, simply carry the information in the form of light signals. It offers high
maintenance costs and is very expensive than copper networking cables. These Fibre Optic
cables can be of two types
⦁ Single-mode
⦁ Multimode
The below figure represents the structure of the coaxial cable. It consists of a core that
surrounds several protective layers. The Outer layer we call the jacket is used to protect the
inner components.The second layer of the Fibre optic cables, we call the buffer to
encapsulates one or more optical cables to protect them from physical damage. And the
layer around the fiber optic core, we call it the cladding. It is made of glass or a plastic
The cladding has two main properties. It is used to protect the core, the light bouncing and
reflection allow fiber to bend around the corners without affecting the transmission of the
signals.
The last layer of the fiber optic cable is the central core cable, which is made of glass fiber
lights, The LED can travel through the cores.
Single Mode
The single mode is designed to carry the signals with a single mode. It means the light
signal can travel in the same way and in the same pattern.
The single-mode only provides a single ray of light. It has a high data transfer rate event in
long-distance communications.
Single-mode has a very tiny diameter of 9 microns or micrometers and with a width range of
a maximum of 200 microns. The core of the optical cable is not visible without the help of
any special equipment. The Light signals don’t traverse in different paths as the normal
signals. Mostly the single mode is widely used for long-range communications. The best
example is the WAN connection. WAN stands as the wide-area network.
Multimode Fiber
6
7. Multimode fiber is mostly used for short-range communications. Within the campus or
school, the multifiber model is beneficial. It is different from the single mode, the light
disperses in different directions and travels through the cladding core. These Multimedia
links are used with a speed of 100 gigabits per second.
There are many more additional features in the multimode fiber
⦁ It has a higher diameter than the single-mode fiber.
⦁ The generated lights can travel in different directions. and it has greater
attenuation than the single-mode fiber.
7
8. Program – 2
Create a socket for HTTP for web page upload and download
Source Code:-
Client:-
import java.net.*;
import java.io.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import javax.imageio.ImageIO;
public class Client{
public static void main(String args[]) throws Exception{
Socket soc;
BufferedImage img = null;
soc=new Socket("localhost",4000);
System.out.println("Client is running. ");
try {
System.out.println("Reading image from disk. ");
img = ImageIO.read(new File("C:Usersgitesh
Desktop3rd year 6th semcn practicalpracpractical1src
mainjava/hot.jpg"));
ByteArrayOutputStream baos = new
ByteArrayOutputStream();
ImageIO.write(img, "jpg", baos);
baos.flush();
byte[] bytes = baos.toByteArray();
baos.close();
System.out.println("Sending image to server. ");
OutputStream out = soc.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
dos.writeInt(bytes.length);
dos.write(bytes, 0, bytes.length);
System.out.println("Image sent to server. ");
dos.close();
out.close();
}catch (Exception e) { System.out.println("Exception:
" + e.getMessage());
soc.close();
}
soc.close();
8
9. }
}
Server:-
import java.net.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
class Server {
public static void main(String args[]) throws Exception{
try (// ss=null;
ServerSocket ss = new ServerSocket(4000)) {
Socket s=ss.accept();
System.out.println("Server Waiting for image");
System.out.println("Client connected.");
InputStream in =s.getInputStream();
DataInputStream dis = new DataInputStream(in);
int len = dis.readInt();
System.out.println("Image Size: " + len/1024 + "KB");
byte[] data = new byte[len];
dis.readFully(data);
dis.close();
in.close();
InputStream ian = new ByteArrayInputStream(data);
BufferedImage bImage = ImageIO.read(ian);
JFrame f = new JFrame("Server");
ImageIcon icon = new ImageIcon(bImage);
JLabel l = new JLabel();
l.setIcon(icon);
f.add(l);
f.pack();
f.setVisible(true);
}
}
}
9
18. PROGRAM -4
AIM:- Study of TCP/UDP performance.
TCP is represented as a connection-oriented protocol, TCP presents end-to-end
communications. Moreover, when the communication is created among the
transmitter and receiver, the data can be send over that communication. While the
UDP is a simple connectionless protocol. UDP does not constitute a dedicated
endtoend
communication among the transmitter and the receiver before the real
communication takes place. However, the data is being transported in one trend
from
the transmitter to the receiver with no need to verifying the receiver case. Figure 1
shows the segment fields of TCP and UDP.
In our comparison, we have utilized various network behavior metrics among UDP
and
TCP. These metrics are applied to evaluate and analyze protocols performance
1. Packet Delivery Ratio (PDR)
PDR is the percentage of data packets transported to the destination to those
produced
by the sources. PDR is calculated as follow:
2. Average Throughput (TP)
It is the bytes successfully received number and it is calculated as follow:
TP = No. of Bytes Received 8 Simulation Time 1000 kbpsb 8 8 Simulation Time
1000 kbpsb Simulation Time 8 Simulation Time 1000 kbpsb 1000 kbpsb
3. Average End-to-End Delay (e2e delay)
It is the mean time of the successfully transmitted data packet
over the network from the source to the destination. It is
computed as follow:
⦁ Packet Loss (PL)
It is the difference among the data packets transmitted and the
data packets received.
It
is calculated as follow: PL = No. of
Data Packets Sent − No. of Data
18
19. Packets Receive
⦁ Network Metrics
In this our simulation, there are two various kinds of network
parameters which are varying through the simulation
experiments:
⦁ Bandwidth: It is the data number that transfer from the source
to the destination.
⦁ Packet size: A packet is the unit of data which is routed
between the source and destination.
Conclusion
TCP and UDP are a transportation layer protocols which are
considered of the basic protocols of the internet. The performance
of these protocols in various network parameters and scenarios is
still not so clear. Therefore, in this paper, we have analyzed and
compared the behavior of both TCP and UDP in two different
19
20. scenarios to accurately determine which of these protocols is
better. The simulation has been used NS2 to assess the behavior
of TCP and UDP in varying packet size and bandwidth. These
two protocols were measured in terms of the mean end-to-end
delay, mean throughput, packet delivery percentage, and packet
loss ratio. The results have shown that the performance of TCP is
outperformed the UDP in both of the two scenarios. Therefore, it
is concluded that the TCP is more reliable and better than UDP in
terms of
all the performance measures
20
21. PROGRAM -5
Aim: Performance comparison of MAC protocols
Performance Analysis of MAC Layer Protocols in Wireless Sensor
Network
• Media Access Control (MAC) layer protocols have a critical role in making a
typical Wireless Sensor Network (WSN) more reliable and efficient. Choice of
MAC
layer protocol and other factors including number of nodes, mobility, traffic rate
and
playground size dictates the performance of a particular WSN.
• The performance of an experimental WSN is evaluated using different MAC
layer
protocols. In this experiment, a WSN is created using OMNeT++ MiXiM network
simulator and its performance in terms of packet delivery ratio and mean latency
is
evaluated. The simulation results show that IEEE 802.11 MAC layer protocol
performs better than CSMA, B-MAC and IEEE 802.15.4 MAC layer protocols.
• A typical Wireless Sensor Network (WSN) monitors environmental conditions
by
using spatially distributed autonomous sensors. WSN applications lay in the
fields of
energy control system, environmental monitoring, security and surveillance,
health
application, area monitoring and many more.
• A WSN can be a composite of hundreds to thousands of sensor nodes. The
performance of a typical WSN is not the same on different MAC layers. A WSN
is
implemented considering various design factors like mobility of the nodes,
playground size, number of nodes, traffic rate and most importantly MAC layer
protocol.
• It may happen that a particular WSN on a selected MAC layer protocol
performs
really well at the beginning, but as the factors like the number of nodes, mobility
of
the nodes and traffic rate are varied the performance would drop.
• Therefore, the design factors should be carefully adjusted while realizing a
particular WSN. OMNeT++ with MiXiM makes it easier for the designer to plan
and
test a WSN, varying multiple factors and see which MAC layer protocol delivers
better than others.
21
22. MAC Performance Matrices: In order to design good MAC layer protocol for
WSN
attributes such as energy efficiency, latency, throughput, fairness are needed to
be
considered. We mainly observe MAC layer performance for a WSN with respect
to 2
attributes.
Packet Delivery Ratio: The number of packets received at the destination to the
number of packets sent at the source.
Mean Packet Latency: The time taken by the packet to reach to the destination
node
is averaged for all the packets.
A Comparison of MM Protocols for Wireless Local Networks Based
on
Battery Power Consumption
• Energy efficiency is an important issue in mobile wireless networks since the
battery life of mobile terminals is limited. Conservation of battery power has been
addressed using many techniques. This paper addresses energy efficiency in
medium access control (MAC) protocols for wireless networks.
• The performance metrics considered are transmitter and receiver usage times
for packet transmission and reception. The analysis here shows that protocols
that
aim to reduce the number of contentions perform better from energy
consumption
perspective. The receiver usage time, however tends to be higher for protocols
that
require the mobile to sense the medium before attempting transmission. • Third
generation wireless networks will be expected to carry diverse multimedia traffic
types. A number of access protocols have been proposed to support multimedia
traffic [1–8]. These protocols typically address network performance metrics such
as
throughput, efficiency, and packet delay. We believe that energy consumption at
the
MAC level should also be an important consideration in the design of the MAC
protocol for mobile wireless networks.
The objective of MAC protocol design should be minimize energy consumption
while maximizing protocol performance. The protocols should be defined such
that
energy consumption due to the transceiver and CPU is low. The following are
some
principles that may be observed to conserve energy at the MAC level:
1. Collision should be eliminated as far as possible since it results in
retransmissions that leads to unnecessary energy consumption and also to
possibly
unbounded delays. Note that retransmission cannot be completely avoided due
22
23. to
the high link error-rates and due to user mobility. For instance, collision-based
random access could be limited to new user registration.
2. In a typical wireless broadcast environment, the receiver has to be powered
on at
all times resulting in significant energy consumption. The receiver subsystem
typically receives all packets and forwards only the packets destined for this
mobile.
One possible way to reduce receiver power-on time is to broadcast a data
transmission schedule for each mobile. This will enable a mobile be in standby
mode
except during its alloted slots.
3. Significant time and power is spent by the mobile radio in switching from
transmit
to receive modes, and vice-versa. This turnaround is a crucial factor in the
performance of the protocol. A protocol which allocates permission on a slot-by-
slot
basis will suffer significant overhead due to turnaround. In order to reduce
turnaround, a mobile should be allocated contiguous slots for transmission and
reception whenever possible.
4. The IEEE 802.11 standard recommends the following technique for energy
conservation. A mobile that wishes to conserve energy may switch to sleep
mode.
From that point on, the base station buffers packets destined for this mobile. The
base station periodically transmits a beacon which contains information about
such
buffered packets. Upon waking up, the mobile listens for this beacon and informs
the
base station that it is ready to receive. This approach conserves energy at the
mobile but results in additional delays that may affect quality-of-service (QoS).
5. If reservations are used to request bandwidth, it will be more efficient
(powerwise
and bandwidth-wise) to request multiple cells with a single reservation packet.
This suggests that the mobile should request larger chunks of bandwidth to
reduce
the reservation overhead leading to better bandwidth and energy consumption
efficiency.
6. Assume that mobiles transmit requests and that the base station uses a
scheduling algorithm to allocate slots as in [4, 5, 8]. A distributed algorithm where
each mobile computes the schedule independently may not be desirable
because: (i)
It may not receive all the reservation requests due to radio and error constraints,
and
(ii) Schedule computation consumes energy and is thus better relegated to the
base
station. This suggests that a centralized scheduling mechanism will be more
23
24. energy
efficient.
ALGORITHM
Step 1: Start network simulator OTCL editor. Step 2:
Create new simulator using set ns [new Simulator] syntax
Step 3: Create Trace route to Network Animator set nf
[open out.nam w]
$ns namtrace-all $nf
Step 4: Create procedure to trace all path
proc finish {} { global ns
nf $ns flush-trace #Close
the NAM trace file close
$nf
#Execute NAM on the trace file
exec nam out.nam &
exit 0
}
Step 4: Connect with TCP and SINK command.
$ns connect $tcp $sink
Step 5: Setup a FTP over TCP connection set
ftp [new Application/FTP]
$ftp attach-agent $tcp
$ftp set type_ FTP
Step 6: Setup a CBR over UDP connection set
cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set type_ CBR
Step 7: Run and Execute the program.
$ns run
PROGRAM
#Create a simulator object set
ns [new Simulator]
#Define different colors for data flows (for NAM)
$ns color 1 Blue
$ns color 2 Red #Open the
NAM trace file set nf [open
out.nam w] $ns namtraceall
$nf #Define a 'finish'
procedure
24
25. proc finish {} { global ns
nf $ns flush-trace #Close
the NAM trace file close
$nf
#Execute NAM on the trace file
exec nam out.nam &
exit 0
}
#Create four nodes set
n0 [$ns node] set n1
[$ns node] set n2 [$ns
node] set n3 [$ns
node]
#Create links between the nodes
$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns duplex-link $n2 $n3 1.7Mb 20ms DropTail
#Set Queue Size of link (n2-n3) to 10 $ns
queue-limit $n2 $n3 10 #Give node position
(for NAM)
$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n2 $n3 orient right
#Monitor the queue for link (n2-n3). (for NAM)
$ns duplex-link-op $n2 $n3 queuePos 0.5
#Setup a TCP connection set
tcp [new Agent/TCP] $tcp set
class_ 2 $ns attach-agent
$n0 $tcp set sink [new
Agent/TCPSink]
$ns attach-agent $n3 $sink
$ns connect $tcp $sink
$tcp set fid_ 1
#Setup a FTP over TCP connection set
ftp [new Application/FTP]
$ftp attach-agent $tcp
$ftp set type_ FTP #Setup
a UDP connection set udp
[new Agent/UDP] $ns
attach-agent $n1 $udp set
null [new Agent/Null] $ns
attach-agent $n3 $null
$ns connect $udp $null
$udp set fid_ 2
#Setup a CBR over UDP connection set
cbr [new Application/Traffic/CBR]
25
26. $cbr attach-agent $udp
$cbr set type_ CBR
$cbr set packet_size_ 1000
$cbr set rate_ 1mb
$cbr set random_ false
#Schedule events for the CBR and FTP agents
$ns at 0.1 "$cbr start"
$ns at 1.0 "$ftp start"
$ns at 4.0 "$ftp stop"
$ns at 4.5 "$cbr stop"
#Detach tcp and sink agents (not really necessary)
$ns at 4.5 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n3
$sink" #Call the finish procedure after 5 seconds of simulation time $ns
at 5.0 "finish"
#Print CBR packet size and interval puts "CBR
packet size = [$cbr set packet_size_]" puts "CBR
interval = [$cbr set interval_]"
#Run the simulation
$ns run
OUTPUT:-
RESULT:
Thus the MAC Protocols performance compared by using NS-2 and output
verified
by using Network Animator.
26
27. PROGRAM -6
AIM:To compare various Routing Protocols performance using NS-2
SOURCE
CODE:
set ns [new Simulator]
$ns multicast set f
[open out.tr w]
$ns trace-all $f
$ns namtrace-all [open out.nam w]
$ns color 1 red
# prune/graft packets
$ns color 30 purple
$ns color 31 green set
n0 [$ns node] set n1
[$ns node] set n2 [$ns
node] set n3 [$ns
node] # Use automatic
layout$ns duplex-link $n0 $n1 1.5Mb 10ms DropTail
$ns duplex-link $n1 $n2 1.5Mb 10ms DropTail
$ns duplex-link $n1 $n3 1.5Mb 10ms DropTail
$ns duplex-link-op $n0 $n1 orient right
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n1 $n3 orient right-down
$ns duplex-link-op $n0 $n1 queuePos 0.5
set mrthandle [$ns mrtproto DM {}] set cbr0
[new Application/Traffic/CBR] set udp0 [new
Agent/UDP] $cbr0 attach-agent $udp0
$ns attach-agent $n1 $udp0 $udp0
set dst_addr_set cbr1 [new Application/Traffic/CBR]
set udp1 [new Agent/UDP] $cbr1
attach-agent $udp1
$udp1 set dst_addr_
$udp1 set class_ 1 $ns attachagent
$n3 $udp1 set rcvr [new
27
28. Agent/LossMonitor]
#$ns attach-agent $n3 $rcvr
$ns at 1.2 "$n2 join-group $rcvr 0x8002"
$ns at 1.25 "$n2 leave-group $rcvr 0x8002"
$ns at 1.3 "$n2 join-group $rcvr 0x8002"
$ns at 1.35 "$n2 join-group $rcvr 0x8001"
$ns at 1.0 "$cbr0 start"
$ns at 1.1 "$cbr1 start"
$ns at 2.0 "finish" proc
finish {} { global ns $ns
flush-trace puts"running nam..." exec
nam out.nam & exit 0}$ns run
OUTPUT:
28
29. PROGRAM – 7
To flood the server from a spoofed source address leading to a DoS
attack.
DESCRIPTION:
A Denial of Service attack (DoS) is any type of attack on a networking
structure to disable a server from servicing its clients. Attacks range
from sending millions of requests to a server in an attempt to slow it
down, flooding a server with large packets of invalid data, to sending
requests with an invalid or spoofed IP address.
TCP/IP 3-way handshake is done to establish a connection between a
client and a server. The process is:
1. Client --SYN Packet--> Server
2. Server --SYN/ACK Packet --> Client
3. Client --ACK Packet --> Server
SYN Flood DOS attack involves sending too many SYN packets (with a
bad or random source IP) to the destination server. These SYN requests
get queued up on the server's buffer and use up the resources and
30. memory of the server. This can lead to a crash or hang of the server
machine.
After sending the SYN packet it is a half-open connection and it takes
up resources on the server machine. So if an attacker sends SYN packets
faster than memory is being freed up on the server then it would be an
overflow situation. Since the server's resources are used the response to
legitimate users is slowed down resulting in Denial of Service.
IMPLEMENTATION:
Internet Protocol Configuration (ipconfig) is a Windows console
application that has the ability to gather all data regarding current
Transmission Control Protocol/Internet Protocol (TCP/IP) configuration
values and then display this data on a screen. Ipconfig also refreshes the
Domain Name System (DNS) and Dynamic Host Configuration
Protocol (DHCP) settings each time it is invoked. When invoked
without additional parameters, ipconfig simply displays the IP address,
default gateway and subnet mask for all available adapters.
First of all using ipconfig check the current IP Configuration of the
system.
Spoofing is the act of disguising a communication from an unknown
source as being from a known, trusted source. Spoofing can apply to
emails, phone calls, and websites, or can be more technical, such as a
31. computer spoofing an IP address, Address Resolution Protocol (ARP),
or Domain Name System (DNS) server.
Spoofing can be used to gain access to a target’s personal information,
spread malware through infected links or attachments, bypass network
access controls, or redistribute traffic to conduct a denial-of-service
attack. Spoofing is often the way a bad actor gains access in order to
execute a larger cyber attack such as an advanced persistent threat or a
man-in-themiddle attack.
Successful attacks on organizations can lead to infected computer
systems and networks, data breaches, and/or loss of revenue—all liable
to affect the organization’s public reputation. In addition, spoofing that
leads to the rerouting of internet traffic can overwhelm networks or lead
customers/clients to malicious sites aimed at stealing information or
distributing malware.
1. Using netsh utility, change IP address i.e. spoofing
Now, we have our IP changed that means we have a Spoofed IP.
32. Spoofed IP address
IP address spoofing is one of the most frequently used spoofing attack
methods. In an IP address spoofing attack, an attacker sends IP packets
from a false (or “spoofed”) source address in order to disguise it.
Denial-of-service attacks often use IP spoofing to overload networks
and devices with packets that appear to be from legitimate source IP
addresses.
There are two ways that IP spoofing attacks can be used to overload
targets with traffic. One method is to simply flood a selected target with
packets from multiple spoofed addresses. This method works by directly
sending a victim more data than it can handle. The other method is to
spoof the target’s IP address and send packets from that address to many
different recipients on the network. When another machine receives a
packet, it will automatically transmit a packet to the sender in response.
Since the spoofed packets appear to be sent from the target’s IP address,
all responses to the spoofed packets will be sent to (and flood) the
target’s IP address.
2. Using notepad, create a .bat file as shown. Here mention the
IP address of the target server which you want to ping.
33. Save this file as .bat extension.
3. Now run this .bat file. This will result in a dos attack on the
target server as it will keep pinging the server until it
becomes overflow.
34. PROGRAM – 8
AIM: To sniff and parse packets that pass through using raw
sockets.
Program for Code:
//---cat rawtcp.c---
// Run as root or SUID 0, just datagram no data/payload
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
// Packet length
#define PCKT_LEN 8192
// May create separate header file (.h) for all
// headers' structures // IP header's structure
struct ipheader { unsigned char iph_ihl:5, /*
Little-endian */ iph_ver:4; unsigned
char iph_tos; unsigned short int iph_len;
unsigned short int iph_ident; unsigned char
iph_flags; unsigned short int iph_offset;
unsigned char iph_ttl; unsigned char
iph_protocol; unsigned short int iph_chksum;
35. unsigned int iph_sourceip; unsigned int
iph_destip;
};
/* Structure of a TCP header */ struct tcpheader { unsigned
short int tcph_srcport; unsigned short int tcph_destport;
unsigned int tcph_seqnum; unsigned int tcph_acknum;
unsigned char tcph_reserved:4, tcph_offset:4; // unsigned
char tcph_flags; unsigned int tcp_res1:4, /*little-endian*/
tcph_hlen:4, /*length of tcp header in 32-bit words*/
tcph_fin:1, /*Finish flag "fin"*/ tcph_syn:1, /*Synchronize
sequence numbers to start a connection*/ tcph_rst:1, /*Reset
flag */ tcph_psh:1, /*Push, sends data to the application*/
tcph_ack:1, /*acknowledge*/ tcph_urg:1, /*urgent pointer*/
tcph_res2:2; unsigned short int tcph_win; unsigned short int
tcph_chksum; unsigned short int tcph_urgptr;
};
// Simple checksum function, may use others such as Cyclic
//Redundancy Check, CRC unsigned short csum(unsigned
short *buf, int len)
{
unsigned long sum; for(sum=0;
len>0; len--) sum += *buf++;
sum = (sum >> 16) +
(sum &0xffff); sum += (sum >>
16); return (unsigned short)(~sum);
36. } int main(int argc, char
*argv[])
{ int sd;
// No data, just datagram char buffer[PCKT_LEN]; // The
size of the headers struct ipheader *ip = (struct ipheader
*) buffer; struct tcpheader *tcp = (struct tcpheader *)
(buffer + sizeof(struct ipheader)); struct sockaddr_in sin,
din; int one = 1; const int *val =
&one; memset(buffer, 0, PCKT_LEN); if(argc != 5)
{ printf(" - Invalid parameters!!! n"); printf(" - Usage: %s <source hostname/IP>
<source port> <target hostname/IP> <target
port>n", argv[0]); exit( -1);
}
sd = socket(PF_INET, SOCK_RAW, IPPROTO_TCP);
if(sd < 0) {
perror("socket()
error"); exit( -1);
}
else printf("socket() -SOCK_RAW and tcp protocol is
OK. n");
// The source is redundant, may be used later if needed
// Address family sin.sin_family
= AF_INET;
//sin_family = AF_INET;
37. // Source port, can be any, modify as needed
sin.sin_port = htons(atoi(argv[2])); din.sin_port
= htons(atoi(argv[4])); // Source IP, can be any,
modify as needed sin.sin_addr.s_addr =
inet_addr(argv[1]); din.sin_addr.s_addr =
inet_addr(argv[3]);
// IP structure ip
->iph_ihl =
5; ip
->iph_ver = 4; ip
->iph_tos =
16; ip
->iph_len = sizeof(struct ipheader) + sizeof(struct
tcpheader); ip ->iph_ident = htons(54321); ip -
>iph_offset = 0; ip -
>iph_ttl = 64; ip
->iph_protocol = 6; // TCP ip>iph_chksum
= 0; // Done by kernel
// Source IP, modify as needed, spoofed, we accept through
//command line argument ip->iph_sourceip
= inet_addr(argv[1]);
// Destination IP, modify as needed, but here we accept
//through command line argument ip->iph_destip
= inet_addr(argv[3]);
38. // The TCP structure. The source port, spoofed, we accept
//through the command line tcp->tcph_srcport =
htons(atoi(argv[2])); // The destination port, we
accept through command line tcp-
>tcph_destport = htons(atoi(argv[4])); tcp>tcph_seqnum =
htonl(1); tcp->tcph_acknum =
0; tcp->tcph_offset = 5; tcp->tcph_syn = 1;
tcp>tcph_ack = 0; tcp->tcph_win =
htons(32767); tcp->tcph_chksum = 0; // Done by
kernel tcp>tcph_urgptr = 0; // IP checksum
calculation ip>iph_chksum = csum((unsigned
short *) buffer,
(sizeof(struct ipheader) + sizeof(struct tcpheader)));
// Inform the kernel do not fill up the headers' structure, //we
fabricated our own if(setsockopt(sd, IPPROTO_IP,
IP_HDRINCL, val, sizeof(one))
< 0) { perror("setsockopt()
error"); exit(-1); } else
printf("setsockopt() is
OKn");
printf("Using:::::Source IP: %s port: %u, Target IP: %s port: %u.n", argv[1], atoi(argv[2]),
argv[3], atoi(argv[4]));
// sendto() loop, send every 2 second for 50 counts
unsigned int count; for(count = 0; count < 20;
count++)
40. Practical No. 9
Aim: To implement simple calculator and invoke arithmetic operations from a
remote client.
Calculator import java.rmi.*; public
interface Calculator extends Remote
{ public int sum(int a,int b) throws
RemoteException; public int sub(int a,int b) throws
RemoteException; public int mul(int a,int b) throws
RemoteException;
}
CalculatorServer import java.rmi.*; import java.rmi.server.*; public class
CalculatorServer extends UnicastRemoteObject implements Calculator
{ public CalculatorServer() throws
RemoteException
{
System.out.println("Server is Instantiated");
} public int sum(int first,int second) throws
RemoteException { return first+second;
} public int sub(int first,int second) throws
RemoteException { return first-second; } public int mul(int
first,int second) throws RemoteException { return
first*second; }
public static void main(String args[])
{
41. try
{
CalculatorServer p = new CalculatorServer();
Naming.rebind ("Cal",p);
} catch(Exception
ex)
{
System.out.println("Exception occured: " + ex.getMessage()); }
}
}
CalculatorClient import
java.rmi.*; import
java.io.*; public class
calculatorclient
{
public static void main(String args[])
{
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Calculator
p
=(Calculator)Naming.lookup("Cal");
System.out.println("Enter first number:");
String strFirst = br.readLine();
System.out.println("Enter second number:");
String strSecond = br.readLine();