Computer Networks Lab Manual
Computer Networks Lab Manual
VishwakarmaInstituteofTechnology, Pune-37
(AnautonomousInstituteofSavitribaiPhulePuneUniversity)
CourseOutcomes:
Upon completion of the course, post graduates will be able to –
1. Demonstrate computer architecture concepts related to design of modern processors, memories
and I/Os.
2. Illustrate the micro operations sequencing.
3. Evaluate various alternatives in processor organization.
4. Understand concepts related to memory & IO organization
5. Adapt the knowledge based on Pipeline and its performance
6. Design real world applications using processors.
Required H/WandS/W:Linux OS
INDEX
Sr. TitleofExperiments Page No
No.
1 Study and implement various networking commands 3
on terminal
2 Use socket programming to create client and server 19
to send hello message
3 Write a program for error detection and correction for 25
7/8 bits ASCII codes using HammingCodes for
CRC.Demonstratethr packets capured traces using
Wireshark Packet AnalyzerTool for peer-to-peer
mode.
4. Write a program to simulate Go back N and selective 42
repeate modes of sliding WindowProtocol in peer-to-
peer mode
5. Write a program to find class and type of a given IP 50
address
6. Write a program to demonstrate subnetting and find 54
the subnet masks.
7. 59
Write a program using TCP socket for wired network for
following a. Say Hello to Each other ( For all students)
b. File transfer ( For all students) c. Calculator (Arithmetic)
(50% students) d. Calculator (Trigonometry) (50%
students)
2|DepartmentofInformation Technology
3|DepartmentofInformation Technology
ExperimentNo:1
Title: Study Networking commands
ProblemStatement:Study and implement various networking commands on terminal
Description:
Linux networking commands are used extensively to inspect, analyze, maintain, and
troubleshoot the network/s connected to the system.
Let us first know the list of the basic networking commands used in Linux followed by a
detailed explanation of each.
1. ifconfig
2. ip
3. traceroute
4. tracepath
5. ping
6. netstat
7. ss
8. dig
9. nslookup
10. route
11. host
12. arp
13. iwconfig
14. hostname
15. curl or wget
16. mtr
17. whois
18. ifplugstatus
19. iftop
20. tcpdum
Details of Linux Networking Commands
1. ifconfig
Linux ifconfig stands for interface configurator. It is one of the most basic commands
used in network inspection.
ifconfig is used to initialize an interface, configure it with an IP address, and enable or
disable it. It is also used to display the route and the network interface.
Basic information displayed upon using ifconfig are:
1. IP address
3|DepartmentofComputerEngineering
ExperimentNo:1
2. MAC address
3. MTU(Maximum Transmission Unit)
To get all the details using ifconfig
Syntax:
Ifconfig
Output:
This picture shows the IP address of 3 networks, Ethernet, local network, and WLAN.
To get details of specific interface
Using this command, you can get details of a specific interface. This is shown below.
Commands:
ifconfig eth0
ifconfig lo
ifconfig wlan0
To assign an IP address and Gateway to an interface
This command can also be used to assign an IP address and Gateway to an interface.
However, these details will be reset after the system reboot.
Syntax:
ifconfig eth0 <address> netmask <address>
To enable or disable an interface
ifconfig can be used to enable or disable an interface.
To enable an interface
Syntax:
ifup eth0
To disable an interface
Syntax:
ifdown eth0
To set the size of MTU
By default, MTU has a size of 1500. This can be however set externally by the user using
ifconfig.
Syntax:
Ifconfig eth0 mtuxxxx
XXXX can be replaced by the size of your choice.
4|DepartmentofComputerEngineering
ExperimentNo:1
2. ip
This is the latest and updated version of ifconfig command.
Syntax:
1. ip a
2. ipaddr
This command gives the details of all networks like ifconfig.
This command can also be used to get the details of a specific interface.
Commands to get details are:
Syntax:
ip a show eth0
ip a show lo
ip a show wlan0
3.traceroute
Linux traceroute is one of the most useful commands in networking. It is used to
troubleshoot the network. It detects the delay and determines the pathway to your
target. It basically helps in the following ways:
1. It provides the names and identifies every device on the path.
2. It follows the route to the destination
3. It determines where the network latency comes from and reports it.
traceroute <destination>
If you don't have the traceroute service installed in your system, you can install it using
the following command:
sudo apt-get install inetutils-traceroute
Example:
Command:
$ traceroute google.com
The output provides the following information:
1. The specified hostname
2. Size of the packets
3. The maximum number of hops required.
4. The IP address.
To avoid the reverse DNS lookup, add -n in the command syntax.
Command:
$ traceroute -n google.com
5|DepartmentofComputerEngineering
ExperimentNo:1
The output indicates the network delays. The asterisks shown in the output indicates a
potential problem in reaching that host. They indicate the packet loss during
communication to the network.
Generally, the traceroute command sends UDP packets. It can as well send TCP or ICMP
packets.
To specifically send in ICMP, use this,
Command:
$ sudo traceroute -I google.com
To send a variant of TCP, use this,
Command:
$ sudo traceroute -T google.com
4.tracepath
Linux tracepath is similar to traceroute command. It is used to detect network delays.
However, it doesn't require root privileges.
It is installed in Ubuntu by default.
It traces the route to the specified destination and identifies each hop in it. If your
network is weak, it recognizes the point where the network is weak.
Syntax:
tracepath<destination>
Example:
tracepath mindmajix.com
Output:
5.ping
Linux ping is one of the most used network troubleshooting commands. It basically
checks for the network connectivity between two nodes.
ping stands for Packet INternet Groper.
The ping command sends the ICMP echo request to check the network connectivity.
It keeps executing until it is interrupted.
Use Ctrl+C Key to interrupt the execution.
Syntax:
ping <destination>
Example:
Command:
$ ping google.com
6|DepartmentofComputerEngineering
ExperimentNo:1
The ping shows a successful connection to google.com
You can also use the IP address to ping directly.
You can limit the number of packets by including "-c" in the ping command.
Syntax:
ping -c <number><destination>
You can specify the c count and limit the response packets to that.
Functions:
The command is used to measure the average response. If there is no response for the
ping command, you can assume one of the following issues with the network:
There is a physical issue causing network loss.
The destination address might be dysfunctional or incorrect.
The ping request is blocked due to a target.
There might be a problem with the routing table.
Note: The response rate of the ping command will be affected by the connection at
your system and also the location of the server you are pinging too. So expect a delay in
the response if the connection at your point is weak.
6.netstat
Linux netstat command refers to the network statistics.
It provides statistical figures about different interfaces which include open sockets,
routing tables, and connection information.
Syntax:
netstat
Output:
Observe the output displaying all the open sockets.
Variations in netstat command
Below are few variations of the netstat command used.
1) To display the programs
Syntax:
netstat -p
This displays the programs associated with the open socket.
2) To get the details of the ports
Syntax:
netstat -s
This gives detailed statistics of all the ports.
7|DepartmentofComputerEngineering
ExperimentNo:1
3) To get the information of the routing table
Syntax:
netstat -r
This gives information related to the routing table.
7.ss
Linux ss command is the replacement for netstat command. It is regarded as a much
faster and more informative command than netstat.
The faster response of ss is possible as it fetches all the information from within the
kernel userspace.
Syntax:
ss
This command gives information about all TCP, UDP, and UNIX socket connections.
You can use -t, -u, -x in the command respectively to show TCP/UDP or UNIX sockets.
You can combine each of these with "a" to show the connected and listening sockets.
Syntax:
ss -ta
ss -ua
ss -xa
If you want to see only the listening sockets of TCP/UDP or UNIX sockets, combine it
with "l"
Syntax:
ss -lt
ss -lu
ss -lx
To get a list of all the established sockets of TCP for IPV4,
Command:
$ ss -t4 state established
To get a list of all closed TCP sockets,
Command:
$ ss -t4 state closed
To get a list of all connected ports for a specific IP address:
Command:
$ ss dst XXX.XXX.XXX.XXX
8|DepartmentofComputerEngineering
ExperimentNo:1
8.dig
Linux dig command stands for Domain Information Groper. This command is used in
DNS lookup to query the DNS name server. It is also used to troubleshoot DNS related
issues.
It is mainly used to verify DNS mappings, MX Records, host addresses, and all other
DNS records for a better understanding of the DNS topography.
This command is an improvised version of nslookup command.
Syntax:
dig <domainName>
Example:
$ dig google.com
Output:
dig command outputs the A records by default. If you want to specifically search for MX
or NS type, use the syntax below.
Command:
$ dig google.com MX
To get all types of records at once, use the keyword ANY ass below:
Command:
$ dig google.com ANY
The dig command does the query on the servers listed in /etc/resolv.conf.
9.nslookup
Linux nslookup is also a command used for DNS related queries. It is the older version
of dig.
Syntax:
nslookup<domainName>
Example:
nslookup mindmajix.com
Output:
As we see in the output above, it displays the record information relating to
mindmajix.com
10.route
Linux route command displays and manipulates the routing table existing for your
system.
9|DepartmentofComputerEngineering
ExperimentNo:1
A router is basically used to find the best way to send the packets across to a
destination.
Syntax:
route
Output:
The above output displays all the existing routing table entries for the system. It says
that if the destination address is within the network range of 10.0.0.0 to 10.0.0.255,
then the gateway is *, which 0.0.0.0. This is a special address that indicates a non-
existent destination.
The packets which lie outside this network range will be forwarded to the default
gateway, which is further routed.
Displaying numerical IP address
You can use -n in the option in the syntax to display the output incomplete numerical
form.
Syntax:
route -n
To add a gateway
The packets that are not within the range are forwarded to the specific gateway. You
can specify the gateway address using the following command.
Syntax:
route add default gw<IP address>
To get routing information
The kernel maintains all the routing cache information in a table for faster routing. To
list the routing cache information, use the following command,
Syntax:
route -Cn
11.host
Linux host command displays the domain name for a given IP address and IP address
for a given hostname. It is also used to fetch DNS lookup for DNS related query.
Example:
host mindmajix.com
host 149.77.21.18
You can combine the host command with -t, and get DNS resource records like SOA,
NS, A, PTR, CNAME, MX, SRV.
10|DepartmentofComputerEngineering
ExperimentNo:1
Syntax:
host -t <resourceName>
12.arp
Linux arp command stands for Address Resolution Protocol. It is used to view and add
content to the kernel's ARP table.
Syntax:
arp
All the systems maintain a table of IP addresses and their corresponding MAC
addresses. This table is called the ARP Lookup table. When a destination is requested to
connect through IP address, your router will check for the MAC address in this table. If
it is cached, the table will not be used.
By default, arp displays the hostnames. You can get the IP addresses, by using :
Command:
$ arp -n
You can also delete the entries from the arp table, as shown below.
Command:
$ arp -d HWADDR
13.iwconfig
Linux iwconfig is used to configure the wireless network interface. It is used to set and
view the basic WI-FI details like SSID and encryption. To know more about this
command, refer to the man page.
Syntax:
iwconfig
Output:
14.hostname
Linux hostname is the simple command used to view and set the hostname of a
system.
Syntax:
hostname
Output:
To set the hostname
Use the syntax below to set the hostname.
Syntax:
sudo hostname <newName>
11|DepartmentofComputerEngineering
ExperimentNo:1
The hostname set through this command is not permanent. It will be reset to the name
in the hostname file back when the system reboots.
In order to permanently set a hostname, you have to re-write the hostname in the
hostname file, present on the server. Once set, you have to reboot the box.
In Ubuntu, /etc/hostname file is used.
In RHEL, /etc/sysconfig/network is used.
15.curl &wget
Linux curl and wget commands are used in downloading files from the internet through
CLI. The curl command has to be used with the option "O" to fetch the file, while the
wget command is used directly.
Below are the syntax and the example for the two commands.
a) Curl
Syntax:
curl -O <fileLink>
Example:
curl -O google.com/doodles/childrens-day-2014-multiple-countries
b) wget
Syntax:
wget<fileLink>
Example:
wget google.com/doodles/new-years-day-2012
Output:
16.mtr
Linux mtr command is a combination of ping and the traceroute command. It
continuously displays information regarding the packets sent with the ping time of each
hop. It is also used to view the network issues.
Syntax:
mtr<path>
Example:
$ mtr google.com
Output:
You can use mtr with –report option. It sends 10 packets to each hop that is found on
the way.
12|DepartmentofComputerEngineering
ExperimentNo:1
Syntax:
$ mtr --report <path>
17.whois
Linux whois command is used to fetch all the information related to a website. You can
get all the information about a website including the registration and the owner
information.
Syntax:
whois<websiteName>
Example:
whois mindmajix.com
Output:
18.ifplugstatus
Linux ifplugstatus command is used to check if a cable is plugged into the network
interface. This command is not directly available on Ubuntu. You can install this using
the command below:
Command:
sudo apt-get install ifplugd
Syntax:
ifplugstatus
Output:
In the output above, "link beat detected" means that the cable is plugged in.
19.iftop
Linux iftop command is used in traffic monitoring.
Use the following command to download iftop on your system.
Command:
$ wget http://www.ex-parrot.com/pdw/iftop/download/iftop-0.17.tar.gz
This will give a zip file. To extract it, use the following command,
Command:
$ tarzxvf iftop-0.17.tar.gz
You can compile this using,
Commands:
$ cd iftop-0.17
$ ./configure
13|DepartmentofComputerEngineering
ExperimentNo:1
$ make
$ make install
Now, run the tool as a root user,
$ sudoiftop -I <interface>
Output:
You can view the ports using the -P option in command like this,
Command:
$ sudoiftop -P
You can use the -B command to get the data in bytes, instead of bits (which is shown by
default).
Command:
$ iftop -B
20.tcpdump
Linux tcpdump command is the most used command in network analysis among
other Linux network commands. It captures the traffic that is passing through the
network interface and displays it.
This kind of access to the packet will be crucial when troubleshooting the network.
Syntax:
$ tcpdump -i<network_device>
Output:
You can also specify the protocol (TCP, UDP, ICMP, and others) in the command like
this,
Command:
$ tcpdump -i<network_device>tcp
To specify the port, use the command,
Command:
$ tcpdump -i<network_device> port 80
tcpdump command keeps executing and sending packets unless canceled. Hence you
can specify the number of events to be captured to control the continuous execution.
Command:
$ tcpdump -c 20 -i<network_device>
You can also specify the IP you are capturing from, using the tag src or dst.
14|DepartmentofComputerEngineering
ExperimentNo:1
Command:
$ tcpdump -c 20 -i<network_device>src XXX.XXX.XXX.XXX
You can save the network traffic captured at an instant, into a file and use it later. This
can be done using the command below,
a) Save into a file
Command:
$ tcpdump -w /path/ -i<network_device>
b) Read from the file
Command:
$ tcpdump -r /path
These were the most essential network commands in Linux that are used frequently for
network analysis and troubleshooting.
15|DepartmentofComputerEngineering
ExperimentNo:2
Title:TCP/UDP programming
Problem Statement: Use Socket programming to create Client and Server to
send Hello message
description:
1. Socket creation:
16|DepartmentofComputerEngineering
ExperimentNo:2
type: communication type
int setsockopt(int sockfd, int level, int optname, const void *optval,
socklen_toptlen);
3. Bind:
After creation of the socket, bind function binds the socket to the address
and port number specified in addr(custom data structure). In the example
code, we bind the server to the localhost, hence we use INADDR_ANY to
specify the IP address.
17|DepartmentofComputerEngineering
ExperimentNo:2
4. Listen:
It puts the server socket in a passive mode, where it waits for the client to
approach the server to make a connection. The backlog, defines the
maximum length to which the queue of pending connections for sockfd
may grow. If a connection request arrives when the queue is full, the client
may receive an error with an indication of ECONNREFUSED.
5. Accept:
18|DepartmentofComputerEngineering
ExperimentNo:2
Socket connection: Exactly same as that of server’s socket creation
Connect: The connect() system call connects the socket referred to by the
file descriptor sockfd to the address specified by addr. Server’s address and
port is specified in addr.
19|DepartmentofComputerEngineering
ExperimentNo:2
//client Program
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
int main()
{
//create Socket
int clientsocket;
//char serverresponse[256];
struct sockaddr_inserveraddress;
clientsocket=socket(AF_INET,SOCK_STREAM,0);
//SOCKET function returns the intger
if(clientsocket<0)
printf("socket is not created\n");
else
printf("socket is created succesfully\n");
serveraddress.sin_family=AF_INET;
serveraddress.sin_port=htons(9000);
//serveraddress.sin_addr.s_addr= htons("192.168.56.1);
serveraddress.sin_addr.s_addr= INADDR_ANY;
if(constatus==-1)
printf("there was an error in the connection\n");
char serverresponse[256];
recv(clientsocket,&serverresponse,sizeof(serverresponse),0);
close(clientsocket);
return 0;
//server program
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
int main()
{
int serversocket,client_socket,bindstatus;
20|DepartmentofComputerEngineering
ExperimentNo:2
char servermessage[256]="Hello";
struct sockaddr_inserveraddress;
serversocket=socket(AF_INET,SOCK_STREAM,0);
serveraddress.sin_family=AF_INET;
serveraddress.sin_port=htons(9000);
//serveraddress.sin_addr.s_addr= htons("192.168.56.1");
serveraddress.sin_addr.s_addr= INADDR_ANY;
listen(serversocket,3);
printf("Send reply to the client\n");
send(client_socket,servermessage,sizeof(servermessage),0);
close(serversocket);
return 0;
21|DepartmentofComputerEngineering
ExperimentNo:3
Title:CRC/FCS
Problem Statement:
Write a program for error detection and correction for 7/8 bits ASCII codes using
Hamming Codes or CRC. Demonstrate the packets captured traces using Wireshark
Packet Analyzer Tool for peer to peer mode.( 50% students will perform Hamming
Code and others will perform CRC)
Description:
1 1 0 1 0 1 1
x 1 1 1 0 1
1 1 1 0 1 1
1 1 0 1 0 1 1
x 0 1 1 1 0
0 1 1 1 0 1 nd
0 0 0 0 0 0
1 1 1 0 1 0
1 1 0 1 0 1 1
22|DepartmentofComputerEngineering
ExperimentNo:3
x 0 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 0
1 1 0 1 0 1 1
x 0 1 0 1 1 0
0 0 0 0 0 0 0
x 1 0 1 1 0 0
1 1 0 1 0 1 1
x 1 1 0 0 1 0
1 1 0 1 0 1 1
F= Remainder = R x x 0 1 1 1 0 0
23|DepartmentofComputerEngineering
ExperimentNo:3
n
Therefore F = 01110T = M 2 + F
36
101000110100000
+ 01110
101000110101110
At the receiver , it receives T =101000110101110
At receiving end, it divides T by same P =110101
110101
1 0 1 0 0 0 1 1 0 1 0 1 1 1 0 Q
1 1 0 1 0 1 1
x 1 1 1 0 1
1 1 1 0 1 1
1 1 0 1 0 1 1
x 0 1 1 1 0
0 1 1 1 0 1 nd
0 0 0 0 0 0
1 1 1 0 1 0
1 1 0 1 0 1 1
x 0 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 0
1 1 0 1 0 1 1
x 0 1 0 1 1 1
0 0 0 0 0 0 0
x 1 0 1 1 1 1
1 1 0 1 0 1 1
x 1 1 0 1 0 1
1 1 0 1 0 1 1
0 0 0 0 0 0
F= Remainder = R x x 0 0 0 0 0 0
24|DepartmentofComputerEngineering
ExperimentNo:3
37
25|DepartmentofComputerEngineering
ExperimentNo:3
9
x ++x
6
-------------------------------
7 3
x ++x
7 4
x ++x
------------------------------
4 3
x +x
4
x +x
-------------------------------
3
x +x
3
x +1
--------------------------------
Remainder R=F x + 1
9 7 6 3
T(x) = x + x + x + x + x +1
At receiver
-------------------------------
3 9 7 6 3 6
x + 1 ) x + x + x + x + x + 1(x +
4 9
x +x+1x ++x
6
-------------------------------
7 3
x ++x
7 4
x +x
------------------------------
4 3
x +x +x
4
x +x
--------------------------------
3
x + 1 and finally 0
M: 11100110
Enter Predetermined Divisor P: 1 1 0 0 1
P: 11001
T: 111001100000
R after the fisttime : 00101
1R= 001011
1S= 00000
26|DepartmentofComputerEngineering
ExperimentNo:3
2R= 010111
2S= 11001
3R= 011100
3S= 11001
4R= 001010
4S= 00000
38
5R= 010100
5S= 11001
6R= 011010
6S= 11001
7R= 000110
7S= 00000
CRC = 0110
Final T: x9 + x7 + x6 + x5 +
S: x9 + x8 + x5 + x-1 + x-1 + x-1 +
==================================================
====== 9 cut off
5 cut off
T after putting -1s: x-1 + x7 + x6 + x-1 +
Now T after sorting 1 : x-1 + x-1 + x6 + x7 +
T after appending elements of S: x8 + x6 + x7 +
Final T: x8 + x7 + x6 +
S: x8 + x7 + x4 + x-1 + x-1 + x-1 + x-1 + x-1 + x-1 +
==================================================
====== 8 cut off
7 cut off
T after putting -1s: x-1 + x-1 + x6 +
27|DepartmentofComputerEngineering
ExperimentNo:3
Now T after sorting 1 : x-1 + x-1 + x6 +
T after appending elements of S: x4 + x6 +
Final T: x6 + x4 +
S: x6 + x5 + x2 + x-1 + x-1 + x-1 + x-1 + x-1 + x-1 + x-1 + x-1 + x-1
+
==================================================
====== 6 cut off
T after putting -1s: x-1 + x4 +
Now T after sorting 1 : x-1 + x4 +
39
T after appending elements of S: x2 + x5 + x4 +
Final T: x5 + x4 + x2 +
S: x5 + x4 + x1 + x-1 + x-1 + x-1 + x-1 + x-1 + x-1 + x-1 + x-1 + x-1 + x-1 + x-
1 + x-1 +
======================================================== 5
cut off
4 cut off
T after putting -1s: x-1 + x-1 + x2 +
Now T after sorting 1 : x-1 + x-1 + x2 +
S: x2 + x1 + x-1 + x-1 + x-1 + x-1 + x-1 + x-1 + x-1 + x-1 + x-1 + x-1 + x-1 +
x-1 + x-1 + x-1 + x-1 + x-2 +
==================================================
====== -------FINAL ANSWER: CRC = x2 + x1 +
28|DepartmentofComputerEngineering
ExperimentNo:3
//CRC
//client
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<unistd.h>
int main()
{
if(socket_client<0)
printf("Socket is NOT created:(\n");
else
printf("socket is created succesfully:)\n");
strcat(new_data , data);
length_new_data = strlen(new_data);
for(int i=0; i<=(length_new_data-n);)
{
for (int j=0 ; j<n; j++)
{
new_data[i+j] = new_data[i+j]==crc_g[j] ? '0' : '1';
}
while(i<length_new_data&&new_data[i]!='1')
{
i++;
}
char data1[100];
strcat(data1,data);
strcat(data1,new_data);
printf("\n\nData to be send to receiver is %s ",data1);
int a=5;
while(a!=2)
{
printf("\nDo you want to send error in code \n1=yes \n0=NO \n2=exit :");
scanf("%d",&a);
if(a==1)
{ printf("\nEnter the position where you want to change data:");
int pos;
scanf("%d",&pos);
if(data1[pos]=='0')
{
data1[pos]='1';
}
else
{
data1[pos]='0';
}
}
30|DepartmentofComputerEngineering
ExperimentNo:3
printf("\n");
write(socket_client, data1 , 100);
write(socket_client, crc_g , 100);
printf("\n");
char msg[256];
read(socket_client , msg , 256);
printf("\nMessage from the server is : %s",msg);
printf("\n");
close(socket_client);
//SERVER
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<unistd.h>
int main()
{
if (bindstatus<0)
printf("Binding Failed\n");
else
31|DepartmentofComputerEngineering
ExperimentNo:3
printf("Binding is successful\n");
listen(socket_server , 10);
printf("Send reply to the client\n");
char data1[100],crc_g[100];
int n, length_data1;
n = strlen(crc_g);
length_data1 = strlen(data1);
}
else if(data1[length_data1-1]!='1' && data1[length_data1]!='1')
{
32|DepartmentofComputerEngineering
ExperimentNo:3
char msg[256] = "NO Error in Communication! Can be proceed
further:)";
write(clientsocketfd , msg , sizeof(msg));
}
}
printf("\n\n");
close(socket_server);
return 0;
//Hamming Code
/ /Client
#include <stdio.h>
#include <math.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<unistd.h>
char input1[32];
int input[32];
int code[32];
char code1[100];
int ham_calc(int,int);
void main()
{
int n,i,c_l,p_n=0,j,k;
33|DepartmentofComputerEngineering
ExperimentNo:3
}
}
i=0;
while(n>(int)pow(2,i)-(i+1))
{
p_n++;
i++;
}
c_l = p_n + n;
j=k=0;
for(i=0;i<c_l;i++)
{
if(i==((int)pow(2,k)-1))
{
code[i]=0;
k++;
}
else
{
code[i]=input[j];
j++;
}
}
for(i=0;i<p_n;i++)
{
int position = (int)pow(2,i);
int value = ham_calc(position,c_l);
code[position-1]=value;
}
printf("\nThe calculated Code Word is: ");
for(i=0;i<c_l;i++)
printf("%d",code[i]);
}
int n1=sizeof(code)/sizeof(code[0]);
printf("\n");
for(i=0;i<c_l;i++)
{
if(code[i]==1)
{
code1[i]='1';
}
else
{
code1[i]='0';
}
}
printf("\n %s",code1);
printf("final data:\n");
for(i=0;i<c_l;i++)
printf("%d",code[i]);
int client_socket;
client_socket=socket(AF_INET,SOCK_STREAM,0);
if(client_socket<0)
printf("\n Prolem in socket creation");
else
printf("\nSocket is created");
struct sockaddr_inclient_address;
client_address.sin_family=AF_INET;
client_address.sin_addr.s_addr=INADDR_ANY;
client_address.sin_port =htons(9000);
int con_status=connect(client_socket,(struct
sockaddr*)&client_address,sizeof(client_address));
if(con_status<0)
printf("\nProblem in connection");
else
printf("\nconnect is established") ;
write(client_socket,code1,sizeof(code1));
write(client_socket,&p_n,sizeof(p_n));
write(client_socket,&n,sizeof(n));
//Server
#include <stdio.h>
#include <math.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<unistd.h>
#include<string.h>
int input[32];
int code[50];
char code1[100];
int ham_calc(int,int);
void main()
{
int n,i,p_n=0,c_l,j,k;
int server_socket,client_socket;
server_socket=socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_inserver_address,client_address;
server_address.sin_family=AF_INET;
server_address.sin_addr.s_addr=INADDR_ANY;
server_address.sin_port=htons(9000);
int bind_status=bind(server_socket,(struct
sockaddr*)&server_address,sizeof(server_address));
if(bind_status<0)
printf("\n problem in binding.....");
else
printf("\nbinded...........");
listen(server_socket,5);
int clength=sizeof(client_address);
client_socket=accept(server_socket,(struct
sockaddr*)&client_address,&clength);
read(client_socket,code1,sizeof(code1));
read(client_socket,&p_n,sizeof(p_n));
read(client_socket,&n,sizeof(n));
int n1=strlen(code1);
for(i=0;i<n1;i++)
36|DepartmentofComputerEngineering
ExperimentNo:3
{
if(code1[i]=='1')
{
code[i]=1;
}
else
{
code[i]=0;
}
}
printf("\n p_n=%d,n=%d,n1=%d",p_n,n,n1);
c_l=p_n+n;
for(i=0;i<p_n;i++)
{
int position = (int)pow(2,i);
int value = ham_calc(position,c_l);
if(value != 0)
error_pos+=position;
}
if(error_pos == 0)
printf("The received Code Word is correct.\n");
else
printf("Error at bit position: %d\n",error_pos-1);
}
int ham_calc(int position,intc_l)
{
int count=0,i,j;
i=position-1;
while(i<c_l)
{
for(j=i;j<i+position;j++)
{
if(code[j] == 1)
count++;
}
i=i+2*position;
}
if(count%2 == 0)
return 0;
else
37|DepartmentofComputerEngineering
ExperimentNo:3
return 1;
}
38|DepartmentofComputerEngineering
ExperimentNo:4
Title:Program to implement sliding window protocol
Problem Statement:
Description:
The basic idea of sliding window protocol is that both sender and receiver keep a
``window'' of acknowledgment. The sender keeps the value of expected
acknowledgment; while the receiver keeps the value of expected receiving
frame. When it receives an acknowledgment from the receiver, the sender
advances the window. When it receives the expected frame, the receiver
advances the window.
For example, supposing a fixed window size of m packets, a sender may send
out packets before receiving any acknowledgement. If
acknowledgement arrives from the receiver for packet n, then the range
(window) of unacknowledged
packets slides to , and the sender is able to send out packet (n + m).
In some way, "sliding" signifies a FIFO operation, trimming the range at one
end, extending it at the other end.
39|DepartmentofComputerEngineering
ExperimentNo:4
41
The purpose of the sliding window is to increase throughput. Let's denote the
round trip time with RTT. The time necessary to transfer and acknowledge K (a
big number of) packets is roughly (in one round trip, 2m packets and
2m ACKs are delivered). However, the size of the window (in bytes) should not
grow above "capacity of the path" (the sum of affected network buffer sizes of
all hops along the path): windows that are too big do not increase throughput;
they only increase latency, the number of packets transmitted out-of-order, and
memory usage.
In practice, protocols often adapt the window size to the link's speed and actual
saturation or congestion.
The receiver process keeps track of the sequence number of the earliest frame it
has not received, and sends that number with every ACK it sends. If a frame
from the sender does not reach the receiver, the sender continues to send
subsequent frames until it has emptied its window. The receiver continues to fill
its receiving window with the subsequent frames, replying each time with an
ACK containing the sequence number of the earliest missing frame. Once the
sender has sent all the frames in its window, it re-sends the frame number given
by the ACKs, and then continues where it left off.
The size of the sending and recieving windows must be equal, and half the maximum
sequence number (assuming that sequence numbers are numbered from 0 to n-1) to
avoid miscommunication in all cases of packets being dropped. The sender moves its
window for every packet that is acknowledged.
42
Sample Output:
43
APPLICATION
40|DepartmentofComputerEngineering
ExperimentNo:4
1. The sliding window implements reliability at both the data-link
layer and the transport layer of the network protocol stack, like
TCP/IP.
FAQS
//GO Back N
Client
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<unistd.h>
int main()
{;
printf("\nEnter the size:");
int n;
scanf("%d",&n);
printf("\nEnter the frame size:");
int f;
scanf("%d",&f);
int client_socket;
client_socket=socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_inclient_addr;
client_addr.sin_addr.s_addr=INADDR_ANY;
client_addr.sin_family=AF_INET;
client_addr.sin_port=htons(9000);
int con=connect(client_socket,(struct
sockaddr*)&client_addr,sizeof(client_addr));
if(con<0) printf("\n Falied to connect");
write(client_socket,&n,sizeof(n));
write(client_socket,&f,sizeof(f));
int j=0,ack=0,pre=-1,count=1,c=1;
41|DepartmentofComputerEngineering
ExperimentNo:4
for(int i=0;i<n+f;i++)
{
if(i<f)
{
write(client_socket,&i,sizeof(j));
printf("\nbit sent:%d",i);
}
else
{
read(client_socket,&ack,sizeof(j));
c=1;
if(ack!=pre+1&&count!=2)
{
i=pre+1;
count=2;
c=2;
//server
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<unistd.h>
int main()
{
printf("\nserver");
int n;
int client_socket,server_socket;
client_socket=socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_inclient_addr,server_addr;
42|DepartmentofComputerEngineering
ExperimentNo:4
client_addr.sin_addr.s_addr=INADDR_ANY;
client_addr.sin_family=AF_INET;
client_addr.sin_port=htons(9000);
int con=bind(client_socket,(struct
sockaddr*)&client_addr,sizeof(client_addr));
if(con<0) printf("\n Falied to bind");
listen(client_socket,5);
int clength=sizeof(server_addr);
client_socket=accept(client_socket,(struct sockaddr*)&server_addr,&clength);
int j=0,f,ack=0,count=1,c=1;
read(client_socket,&n,sizeof(n));
read(client_socket,&f,sizeof(n));
for(int i=0;i<n+f;i++)
{
if(i<f)
{
read(client_socket,&j,sizeof(j));
printf("\nbitrecieved:%d",j);
}
else
{
c=1;
if(i==f+2&&count!=2)
{
printf("\n do you want to send ack for bit=%d??y/n:",ack);
char ans;
scanf("%c",&ans);
if(ans=='n'&&count!=2)
{
i=ack;
ack-=1;
count=2;
c=2;
}
}
write(client_socket,&ack,sizeof(ack));
if(c!=2&&ack<n)
printf("\nsending ack for:%d",ack);
if(i<n){
read(client_socket,&j,sizeof(j));
printf("\n bit received:%d",j);
}
ack++;
}
}
}
43|DepartmentofComputerEngineering
ExperimentNo:4
Selective Repeat
//Server
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<unistd.h>
int main()
{
printf("\nserver");
int n;
int client_socket,server_socket;
client_socket=socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_inclient_addr,server_addr;
client_addr.sin_addr.s_addr=INADDR_ANY;
client_addr.sin_family=AF_INET;
client_addr.sin_port=htons(9000);
int con=bind(client_socket,(struct
sockaddr*)&client_addr,sizeof(client_addr));
if(con<0) printf("\n Falied to bind");
listen(client_socket,5);
int clength=sizeof(server_addr);
client_socket=accept(client_socket,(struct sockaddr*)&server_addr,&clength);
int j=0,f,ack=0,count=1,c=1;
read(client_socket,&n,sizeof(n));
read(client_socket,&f,sizeof(n));
for(int i=0;i<n+f;i++)
{
if(i<f)
{
read(client_socket,&j,sizeof(j));
printf("\nbitrecieved:%d",j);
}
else
{
c=1;
if(i==f+2&&count!=2)
{
printf("\n do you want to send ack for bit=%d??y/n:",ack);
char ans;
scanf("%c",&ans);
if(ans=='n'&&count!=2)
{
44|DepartmentofComputerEngineering
ExperimentNo:4
ack-=1;
count=2;
c=2;
write(client_socket,&ack,sizeof(ack));
ack++;
printf("\n sending ack for :%d",ack);
read(client_socket,&j,sizeof(j));
printf("\nbit received:%d",j);
}
}
write(client_socket,&ack,sizeof(ack));
if(c!=2&&ack<n)
printf("\nsending ack for:%d",ack);
if(i<n){
read(client_socket,&j,sizeof(j));
printf("\n bit received:%d",j);
}
ack++;
}
}
}
//Client
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<unistd.h>
int main()
{;
printf("\nEnter the size:");
int n;
scanf("%d",&n);
printf("\nEnter the frame size:");
int f;
scanf("%d",&f);
int client_socket;
client_socket=socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_inclient_addr;
client_addr.sin_addr.s_addr=INADDR_ANY;
client_addr.sin_family=AF_INET;
45|DepartmentofComputerEngineering
ExperimentNo:4
client_addr.sin_port=htons(9000);
int con=connect(client_socket,(struct
sockaddr*)&client_addr,sizeof(client_addr));
if(con<0) printf("\n Falied to connect");
write(client_socket,&n,sizeof(n));
write(client_socket,&f,sizeof(f));
int j=0,ack=0,pre=-1,count=1,c=1;
for(int i=0;i<n+f;i++)
{
if(i<f)
{
write(client_socket,&i,sizeof(j));
printf("\nbit sent:%d",i);
}
else
{
read(client_socket,&ack,sizeof(j));
c=1;
if(ack!=pre+1&&count!=2)
{
count=2;
c=2;
ack+=1;
}
if(c!=2&&ack<=n)
printf("\n ack received:%d",ack);
if(i<n){
write(client_socket,&i,sizeof(ack));
printf("\nbit sent:%d",i);
}
pre++;
}
}
}
46|DepartmentofComputerEngineering
ExperimentNo:5
Title:TCP/UDP programming
Problem Statement: Write a program to find class and type of a given IP address
Description:
Approach
For determining the class: The idea is to check the first octet of the IP addresses. As we know, for class A first octet
will range from 1 – 126, for class B first octet will range from 128 – 191, for class C first octet will range from 192- 223,
for class D first octet will range from 224 – 239, for class E first octet will range from 240 – 255.
For determining the Network and Host ID: We know that Subnet Mask for Class A is 8, for Class B is 16 and for Class C
is 24 whereas Class D and E are not divided into Network and Host ID.
For 2nd Example, the first octet is 130. So, it belongs to Class B. Class B has a subnet mask of 16. So, the first 16 bit or
first two octets are the Network ID part and the rest is the Host ID part.
Hence, the Network ID is 130.45 and the Host ID is 151.154
#include<stdio.h>
#include<string.h>
// Class A
47|DepartmentofComputerEngineering
ExperimentNo:5
if (ip>=1 &&ip<= 126)
return 'A';
// Class B
else if (ip>= 128 &&ip<= 191)
return 'B';
// Class C
else if (ip>= 192 &&ip<= 223)
return 'C';
// Class D
else if (ip>= 224 &&ip<= 239)
return 'D';
// Class E
else
return 'E';
}
i = 0;
j++;
50|DepartmentofComputerEngineering
Experiment No :6
Title:TCP/UDP programming
Problem Statement: Write a program to demonstrate subnetting and find the subnet masks.
Description:
import java.io.*;
import java.net.InetAddress;
System.out.println("ENTER IP:");
String ip = br.readLine();
51|DepartmentofComputerEngineering
Experiment No : 6
int cc = Integer.parseInt(checkclass);
if(cc>0)
if(cc<=127)
mask = "255.0.0.0";
System.out.println("Class A IP Address");
System.out.println("SUBNET MASK:\n"+mask);
mask = "255.255.0.0";
System.out.println("Class B IP Address");
System.out.println("SUBNET MASK:\n"+mask);
52|DepartmentofComputerEngineering
}
Experiment No : 6
mask = "255.255.255.0";
System.out.println("Class C IP Address");
System.out.println("SUBNET MASK:\n"+mask);
mask = "255.0.0.0";
53|DepartmentofComputerEngineering
if(cc>=240 && cc<=254)
mask = "255.0.0.0";
String networkAddr="";
String lastAddr="";
String[] ipAddrParts=ip.split("\\.");
String[] maskParts=mask.split("\\.");
for(int i=0;i<4;i++){
int x=Integer.parseInt(ipAddrParts[i]);
int y=Integer.parseInt(maskParts[i]);
int z=x&y;
networkAddr+=z+".";
54|DepartmentofComputerEngineering
int w=z|(y^255);
lastAdd
55|DepartmentofComputerEngineering
r+=w+".";
56|DepartmentofComputerEngineering
Experiment No :7
OBJECTIVES:
PROBLEM STATEMENT
Write a program using TCP socket for wired network for following
a. Say Hello to Each other ( For all students)
b. File transfer ( For all students)
c. Calculator (Arithmetic) (50% students)
d. Calculator (Trigonometry) (50% students)
Demonstrate the packets captured traces using Wireshark Packet Analyzer Tool for peer to peer
mode.
LINUX SOCKET PROGRAMMING
The Berkeley socket interface, an API, allows communications between hosts or between processes on one
computer, using the concept of a socket. It can work with many different I/O devices and drivers, although
support for these depends on the operating-system implementation. This interface implementation is
implicit for TCP/IP, and it is therefore one of the fundamental technologies underlying the Internet. It was
first developed at the University of California, Berkeley for use on Unix systems. All modern operating
systems now have some implementation of the Berkeley socket interface, as it has become the standard
interface for connecting to the Internet.
Programmers can make the socket interfaces accessible at three different levels, most powerfully
and fundamentally at the RAW socket level. Very few applications need the degree of control over
outgoing communications that this provides, so RAW sockets support was intended to be available
only on computers used for developing Internet related technologies. In recent years, most
operating systems have implemented support for it anyway, including Windows XP.
The Berkeley socket development library has many associated header files. They include:
<sys/socket.h>
Definitions for the most basic of socket structures with the BSD socket
API <sys/types.h>
Basic data types associated with structures within the BSD socket API
<netinet/in.h>
Definitions for the socketaddr_in{} and other base data structures.
<sys/un.h>
Definitions and data type declarations for SOCK_UNIX streams
57|DepartmentofComputerEngineering 45
TCP
TCP provides the concept of a connection. A process creates a TCP socket by calling the socket()
function with the parameters PF_INET or PF_INET6 and SOCK_STREAM.
Server
Setting up a simple TCP server involves the following steps:
∙ Binding the socket to the listen port, with a call to bind(). Before calling bind(), a
programmer must declare a sockaddr_in structure, clear it (with bzero() or memset()), and the
sin_family (AF_INET or AF_INET6), and fill its sin_port (the listening port, in network byte
order) fields. Converting a short int to network byte order can be done by calling the function
htons() (host to network short).
∙ Preparing the socket to listen for connections (making it a listening socket), with a call to
listen().
∙ Accepting incoming connections, via a call to accept(). This blocks until an incoming
connection is received, and then returns a socket descriptor for the accepted connection. The
initial descriptor remains a listening descriptor, and accept() can be called again at any time
with this socket, until it is closed.
∙ Communicating with the remote host, which can be done through send() and recv().
∙ Eventually closing each socket that was opened, once it is no longer needed, using close(). Note
that if there were any calls to fork(), each process must close the sockets it knew about (the
kernel keeps track of how many processes have a descriptor open), and two processes should
not use the same socket at once.
Client
Setting up a TCP client involves the following steps:
∙ Connecting to the server with the use of connect, passing a sockaddr_in structure with the
sin_family set to AF_INET or AF_INET6, sin_port set to the port the endpoint is listening
(in network byte order), and sin_addr set to the IPv4 or IPv6 address of the listening server
(also in network byte order.)
∙ Communicating with the server by send()ing and recv()ing.
∙ Terminating the connection and cleaning up with a call to close(). Again, if there were any
calls to fork(), each process must close() the socket.
58|DepartmentofComputerEngineering
46
Functions
socket()
socket() creates an endpoint for communication and returns a descriptor. socket() takes three
arguments:
∙ domain, which specifies the protocol family of the created socket. For example: o
PF_INET for network protocol IPv4 or
o PF_INET6 for IPv6).
∙ type, one of:
o SOCK_STREAM (reliable stream-oriented
service) o SOCK_DGRAM (datagram service)
o SOCK_SEQPACKET (reliable sequenced packet service), or
o SOCK_RAW (raw protocols atop the network layer).
∙ protocol, usually set to 0 to represent the default transport protocol for the specified domain
and type values (TCP for PF_INET or PF_INET6 and SOCK_STREAM, UDP for those PF_
values and SOCK_DGRAM), but which can also explicitly specify a protocol.
The function returns -1 if an error occurred. Otherwise, it returns an integer representing the
newly-assigned descriptor.
Prototype:
int socket(int domain, int type, int protocol);
connect()
connect() It returns an integer representing the error code: 0 represents success, while -1 represents
an error.
Certain types of sockets are connectionless, most commonly user datagram protocol sockets. For
these sockets, connect takes on a special meaning: the default target for sending and receiving data
gets set to the given address, allowing the use of functions such as send() and recv() on
connectionless sockets.
Prototype:
int connect(int sockfd, const struct sockaddr *serv_addr, socklen_taddrlen); 47
bind()
bind() assigns a socket an address. When a socket is created using socket(), it is given an address
59|DepartmentofComputerEngineering
family, but not assigned an address. Before a socket may accept incoming connections, it must be
bound. bind() takes three arguments:
∙ sockfd, a descriptor representing the socket to perform the bind on ∙ my_addr, a
pointer to a sockaddr structure representing the address to bind to. ∙ addrlen, a socklen_t
field representing the length of the sockaddr
Prototype:
int bind(int sockfd, struct sockaddr *my_addr, socklen_taddrlen);
listen()
listen() prepares a bound socket to accept incoming connections. This function is only applicable to
the SOCK_STREAM and SOCK_SEQPACKET socket types. It takes two arguments:
∙ backlog, an integer representing the number of pending connections that can be queued up at
any one time. The operating system usually places a cap on this value.
Prototype:
int listen(int sockfd, int backlog);
accept()
Programmers use accept() to accept a connection request from a remote host. It takes the
following arguments:
∙ sockfd, the descriptor of the listening socket to accept the connection from. ∙ cliaddr, a
pointer to the sockaddr structure that accept() should put the client's address information
into.
∙ addrlen, a pointer to the socklen_t integer that will indicate to accept() how large the sockaddr
structure pointed to by cliaddr is. When accept() returns, the
48
socklen_t integer then indicates how many bytes of the cliaddr structure were actually
used.
The function returns a socket corresponding to the accepted connection, or -1 if an error occurs.
Prototype:
60|DepartmentofComputerEngineering
int accept(int sockfd, struct sockaddr *cliaddr, socklen_t *addrlen);
A socket is typically set to blocking or nonblocking mode using the fcntl() or ioctl()
functions.
Cleaning up
The system will not release the resources allocated by the socket() call until a close() call occurs.
This is especially important if the connect() call fails and may be retried. Each call to socket()
must have a matching call to close() in all possible execution paths.
IP Address: 172.21.0.202
#definebuffsize 150
int main(void)
{
struct sockaddr_inservaddr,clientaddr;
char buff[buffsize];
char buff1[buffsize];
int listenfd,connfd;
int sin_size;
49
//Creation of Socket //
if((listenfd=socket(AF_INET,SOCK_STREAM,0))==-1)
perror("Socket Creation Error.\n");
else
printf("Socket Created Successfully\n");
printf("Enter the message :");
bzero(buff,150);
fgets( buf f,1 5 0,std in);
// scanf("%s",buff1);
// strcpy(buff,buff1);
bzero((char *) &servaddr, sizeof(servaddr));
// Naming of Socket //
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=inet_addr("172.21.0.202");
servaddr.sin_port=htons(5000);
// Registration of socket at the network Layer //
61|DepartmentofComputerEngineering
if(bind(listenfd, (struct sockaddr *)&se r va d dr ,siz e of (se r va d dr )) == -1)
perror("Bind Error\n");
// Put the socket in Listening Mode //
listen(listenfd,4);
// Accept the Connection from remote client // sin_size =
sizeof(struct sockaddr_in);
}
Client Program Code:
#include<sys/types.h>
#include<sys/socket.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdlib.h>
#definebuffsize 150
int main(void)
{
// Declaration Section //
struct sockaddr_inclientaddr;
char recvline[buffsize];
int sockfd,n;
50
if((so ck fd = s oc k et( A F _ I N E T ,S O CK _ ST R E A M , 0 ) )< 0 )
perror("Socket Creation Erro r .\n" );
else
printf("Socket Created Successfully\n");
bzero((char *) &clientaddr, sizeof(clientaddr));
clientaddr.sin_family=AF_INET;
clientaddr.sin_addr.s_addr=inet_addr("172.21.0.202");
clientaddr.sin_port=htons(5000);
read(sockfd,recvline,buffsize);
if(fputs(recvline,stdout)==EOF)
perror("fputs Error.\n");
// strcpy(recvline,"Thank You Server\n");
APPLICATION
51
63|DepartmentofComputerEngineering
Experiment No 8
FAQS
1. What is a socket?
2. What is the difference between a connection- less and a connection- oriented communication system?
How are they implemented?
3. Which of them is more reliable?
4. Why is the port number required?
5. How is the socket programming in linux different from that in windows? 52
64|DepartmentofComputerEngineering
Experiment No 8
Problem Statement:
Description:
Programmers can make the socket interfaces accessible at three different levels,
most powerfully and fundamentally at the RAW socket level. Very few
applications need the degree of control over outgoing communications that this
provides, so RAW sockets support was intended to be available only on
computers used for developing Internet related technologies. In recent years,
most operating systems have implemented support for it anyway, including
Windows XP.
The Berkeley socket development library has many associated header files. They include:
<sys/socket.h>
Definitions for the most basic of socket structures with the BSD socket
65|DepartmentofComputerEngineering
Experiment No 8
API <sys/types.h>
Basic data types associated with structures within the BSD socket API
<netinet/in.h>
Definitions for the socketaddr_in{} and other base data structures.
<sys/un.h>
Definitions and data type declarations for SOCK_UNIX streams
UDP
UDP address space, the space of UDP port numbers (in ISO terminology, the
TSAPs), is completely disjoint from that of TCP ports.
Server
sock = socket(PF_INET,SOCK_DGRAM,0);
sa.sin_addr.s_addr = INADDR_ANY;
sa.sin_port = htons(7654);
bind() binds the socket to an address/port pair. listen() sets the length of
the new connections queue.
while (1) {
printf ("recv test....\n");
recsize = recvfrom(sock, (void *)hz, 100, 0, (struct sockaddr *)&sa,
fromlen);
printf ("recsize: %d\n ",recsize);
if (recsize< 0)
fprintf(stderr, "%s\n", strerror(errno));
sleep(1);
printf("datagram: %s\n",hz);
}
66|DepartmentofComputerEngineering
Experiment No 8
This infinite loop receives any UDP datagrams to port 7654 using recvfrom().
It uses the parameters:
∙ socket
∙ size of buffer
54
∙ flags (same as in read or other receive socket function)
Client
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
67|DepartmentofComputerEngineering
Experiment No 8
68|DepartmentofComputerEngineering
Title:Title: To Create TCP/IP packets using include files
Problem Statement:
Write a program to prepare TCP and UDP packets using header files and
send the packets to destination machine in peer to peer mode. Demonstrate the
packets captured traces using Wireshark Packet Analyzer Tool for peer to peer
mode
To use tcp.h and ip.h header files and create the packets.
#include <netinet/in.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
main()
int tcp_socket;
struct send_tcp
{
struct iphdrip;
struct tcphdrtcp;
} packet;
62
packet.ip.check = 14536; /* IP checksum */
packet.ip.saddr = inet_addr("1.2.3.4"); /* source address */ packet.ip.daddr =
inet_addr("127.0.0.1"); /* destination address */
peer.sin_family = AF_INET;
peer.sin_port = htons(80);
peer.sin_addr.s_addr = inet_addr("127.0.0.1"); tcp_socket =
close(tcp_socket);
70|DepartmentofComputerEngineering
Experiment No :10
OBJECTIVES:
PROBLEM STATEMENT
PROTOCOL ANALYZER
The special network device driver used for some packet sniffing software
is said to operate in "promiscuous mode" as it listens to everything on the
wire.
71|DepartmentofComputerEngineering
∙ Gain information for effecting a network intrusion.
59
∙ Reverse engineer protocols used over the network.
Example uses
∙ A packet sniffer for a token ring network could detect that the token
has been lost or the presence of too many tokens (verifying the
protocol).
∙ A packet sniffer could detect that messages are being sent to a network
adapter; if the network adapter did not report receiving the messages
then this would localize the failure to the adapter.
∙ A packet sniffer could detect excessive messages being sent by a port,
detecting an error in the implementation.
∙ A packet sniffer could collect statistics on the amount of traffic (number
of messages) from a process detecting the need for more bandwidth or
a better method.
∙ A packet sniffer could be used to extract messages and reassemble into a
compete form the traffic from a process, allowing it to be reverse
engineered.
Ethereal
∙ Data can be captured "off the wire" from a live network connection, or
read from a capture file.
∙ Ethereal can read capture files from tcpdump and a lot of other
formats ∙ Live data can be read from Ethernet, FDDI, PPP,
Token-Ring, IEEE 802.11, Classical IP over ATM, and loopback
interfaces.
∙ Captured network data can be browsed via a GUI, or via the
TTY-mode "tethereal" program.
∙ Capture files can be programmatically edited or converted via
command-line switches to the "editcap" program.
∙ 750 protocols can currently be dissected
60
∙ gather information, such as baseline traffic patterns and network-
utilization metrics ∙ identify unused protocols so that you can remove
APPLICATION
74|DepartmentofComputerEngineering