Wireshark Lap

Download as pdf or txt
Download as pdf or txt
You are on page 1of 82

Jawaharlal Nehru Engineering College

Laboratory Manual

Internetworking Protocol

For

Second Year Students IT

Dept: Information Technology

Ó Author JNEC, Aurangabad


FOREWARD

It is my great pleasure to present this laboratory manual for Second year Information Technology
engineering students for the subject of Internetworking Protocol keeping in view the vast
coverage required for visualization of concepts of Computer Networks with simple language.

As a student, many of you may be wondering with some of the questions in your mind regarding
the subject and exactly what has been tried is to answer through this manual.

As you may be aware that MGM has already been awarded with ISO 9000 certification and it is
our endure to technically equip our students taking the advantage of the procedural aspects of
ISO 9000 Certification.

Faculty members are also advised that covering these aspects in initial stage itself, will greatly
relived them in future as much of the load will be taken care by the enthusiasm energies of the
students once they are conceptually clear.

Dr. H. H. Shinde

Principal
LABORATORY MANUAL CONTENTS

This manual is intended for the Second year students of IT in the subject of Internetworking
Protocol. This manual typically contains practical/Lab Sessions related Computer Network
covering various aspects related the subject to enhanced understanding.

Although, as per the syllabus, only programs and simulation using Wireshark of various
protocols are prescribed. We have made the efforts to cover various aspects of the subject
covering computer hardware components, software components networking aspects, Operating
System concepts and programming aspects will be complete in itself to make it meaningful,
elaborative understandable concepts and conceptual visualization.

Students are advised to thoroughly go through this manual rather than only topics mentioned in
the syllabus as practical aspects are the key to understanding and conceptual visualization of
theoretical aspects covered in the books.

Good Luck for your Enjoyable Laboratory Sessions

Prof. S. C. Tamne Mrs. M. B. Kawarkhe

HOD, IT Asst. Prof., IT Dept.


MGM’s
Jawaharlal Nehru Engineering College, Aurangabad

Department of Information Technology

Vision of IT Department:

To develop expertise of budding technocrats by imparting technical knowledge and

human value based education.

Mission of the IT Department:

A. Equipping the students with technical skills, soft skills and professional attitude.

B. Providing the state of art facilities to the students to excel as competent professionals,

entrepreneurs and researchers.


Program Specific Outcomes

PSO1. An ability to design, develop and implement computer programs in the areas related to

Algorithms, Multimedia, Website Design, System Software, DBMS and Networking.

PSO2. Develop software systems that would perform tasks related to Research, Education and

Training and/or E governance.

PSO3. Design, develop, test and maintain application software that would perform tasks related

to information management and mobiles by utilizing new technologies to an individual or

organizations.

Program Educational Objectives

PEO1. The graduates will utilize their expertise in IT industry and solve industry technological

problems.

PEO2. Graduates should excel in engineering positions in industry and other organizations that

emphasize design & implementation of IT applications.

PEO3. Graduates will be innovators & professionals in technology development,


deployment

& system implementation.

PEO4. Graduates will be pioneers in engineering, engineering management, research and higher

education.

PEO5. Graduates will be good citizens & cultured human being with full appreciation of

importance of IT professional ethical & social responsibilities.


Program Outcomes:

• PO1. Engineering Knowledge


• PO2. Problem Analysis
• PO3. Design/Development of Problem
• PO4. Conduct Investigation of Complex Problem
• PO5. Modern Tool Usage
• PO6. The Engineer and society
• PO7. Environment and Sustainability
• PO8. Ethics
• PO9. Individual and Team work
• PO10. Communication
• PO11. Project Management
• PO12. Life Long Learning
DOs and DON’Ts in Laboratory:

1. Do not handle any equipment before reading the instructions/Instruction manuals


3. Observe type of sockets of equipment power to avoid mechanical damage

4. Do not forcefully place connectors to avoid the damage

5. Strictly observe the instructions given by the teacher/Lab Instructor

Instructions for Laboratory Teachers:

1. Submission related to whatever lab work has been completed should be done during the next
lab session. The immediate arrangements for printouts related to submission on the day of
practical assignments.
2. Students should be taught for taking the printouts under the observation of lab teacher.

3. The promptness of submission should be encouraged by way of marking and evaluation


patterns that will benefit the sincere students.
LIST OF EXPERIMENTS:

1. Conversion of IP addresses (e.g. I/P: 10.24.164.254 O/P:


00001010.00011000.10000000.11111110 and I/P: binary dotted O/P: decimal dotted)

2. Configuration of IP address, Subnet Mask and Default Gateway.

3. Installation and introduction to Wireshark.

4. Wireshark Lab: Ethernet and ARP

5. To find out shortest path from source to destination using Dijkstras Algorithm.

6. To establish a straight over and cross over cable in LAN.

7. Implement for a leacky bucket algorithm congestion control.

8. Creating workgroup of computers and resource sharing (file & printer) (WindowsOS
preferred)

9. Installation of Cisco Packet Tracer and demonstration of simple network topology using Cisco
Packet Tracer.

10. Socket programming for TCP .


Experiment No.1

Aim:- Conversion of IP address 00001010.00011000.10000000.11111110 and I/P: binary


dotted O/P: decimal dotted)

Objective: IP Addressing Internet Architecture IPv4 Addressing IP address Classes Subnets and
subnet mask Subnets design with IP addressing.

Hardware Requirement: Intel based desktop pc: RAM 512 MB

Software Requirement: Turbo C/Borland C

Theory:

IP enables hosts to communicate with each other at the Network layer. In IPv4 each packet
contains a source and destination address. That’s how the routers on the network knows where
the packet is coming from and where they must forward the packet. The IP addresses fields are
represented in 32 bits. Routers know how to interpret those numbers, but for a human to
understand them would be too difficult. From our point of view, we use what’s called a dotted
decimal address. A dotted decimal address is the human representation of the binary address. For
example, the address 192.168.10.1 is a dotted decimal address. In its binary form, the address is
11000000101010000000101000000001. IP addresses have 4 octets. For example, 192 is the first
octet, 168 the second, 10 the third and 1 the last octet. In its binary form, 11000000 is the first
octet, 10101000 the second, 00001010 the third and 00000001 the last octet. Every octet, in its
decimal form, can get a value from 0 to 255.

In the binary system there are only 1s and 0s. Depending on their position in the octet, they get
different values. Each position is a power of 2. To get the decimal number you have to sum up
those number.

For example, we know that 10101000 is 168. But let’s see if we get the same number after we
make the calculations. 2^7 * 1 + 2^6 * 0 + 2^5 * 1 + 2^4 * 0 + 2^3 * 1 + 2^2 * 0 + 2^1 * 0 + 2^0
* 0 = 128 + 32 + 8 = 168 Let’s now learn how to convert those numbers from decimal to binary.
The decimal to binary conversion is similar to binary to decimal conversion. Keep in mind those
powers of 2. When you calculate the binary value, you take those powers of 2 and compare them
with your number. If your number is greater, you write down 1 and you subtract that power of 2
from the number. If your number is lower than the power of 2, you write down 0. You continue
to make the calculations until you reach 2^0. Class A addresses were the ones from 0.0.0.0 to
127.255.255.255.

A class A network is has a default netmask of 255.0.0.0 allowing for up to 16,777,214 hosts per
network ( 2^24 – 2). However, there’s possible to create only 128 network from the whole class
A space. Or at least it was, back in the days, when classless routing was not used.

Class B addresses are from 128.0.0.0 to 191.255.255.255. The whole class B was able to create
16,384 networks (2^14) with a maximum number of 65,534 hosts per network (2^16 – 2). The
default netmask si 255.255.0.0.

Class C networks were found within the 192.0.0.0 – 223.255.255.255 range. This class allowed
for more networks -2,097,150 ( 2^21 ) but the maximum hosts per network was only 254 (2^8 –
2).

The class D and the class E address blocks are the same used today for multicasting,
respectively the experimental addresses.

Program:-

Int main()

{ char bin[4][8];

char bin2[4][9];

intipaddr[4];

if(!readIpAddress(ipaddr))

break;

convertDecToBin(ipaddr,bin2);

printf("The address converted to binary is :%8s %8s %8s %8s \n",

bin2[0],bin2[1],bin2[2],bin2[3]);

break;

}
voidconvertDecToBin(intdec[],char bin[4][9])

{ inti,j;

for(i=0;i=0;j--)

{ bin [i][j]=(dec[i]& 1)+'0';

dec[i]/=2; }

bin[i][8]=0; }

Conclusion: - We implement conversion from a dotted decimal IP form to 32 bit binary IP form.
Experiment No.2

Aim: Configuration of IP address, Subnet Mask and Default Gateway.

Theory:

Step 1

Click Start->Control Panel->select and double click Network and internet connections-
>select and double click Network Connections.

Step 2

Double-click the Local Area Connection icon; highlight Internet Protocol (TCP/IP) tab in the
Local Area Connection Properties window that appears:

Step 3
Double click it or click Properties. The TCP/IP Properties window will display.

Step 4
Now you have two ways to configure the TCP/IP protocol below:
1. Assigned by DHCP Sever
Select Obtain an IP address automatically and Obtain DNS Server address automatically,
as shown in the figure below. These may be selected by default. Then click OK to save setting.

2.Assigned manually
1) Select Use the following IP address, as shown in the following figure.
If the router’s LAN IP address is 192.168.1.1, please type in IP address 192.168.1.x (x is from
2 to 253), subnet mask 255.255.255.0, and default gateway 192.168.1.1.

2) Select Use the following DNS server addresses, as shown in the following figure. And then
type the DNS server IP address, which should be provided by your ISP. Finally remember to
click OK to save settings.

Note: In most cases, type your local area DNS server IP addresses into it.
The Preferred DNS server is same to default gateway. For Secondary DNS server, you could
leave it blank or type in 8.8.8.8.
Step 5
Click OK to save and apply your settings.

Subnet Mask

An IP address is divided into two parts: network and host parts. For example, an IP class A
address consists of 8 bits identifying the network and 24 bits identifying the host. This is because
the default subnet mask for a class A IP address is 8 bits long. (or, written in dotted decimal
notation, 255.0.0.0). What does it mean? Well, like an IP address, a subnet mask also consists of
32 bits. Computers use it to determine the network part and the host part of an address. The 1s in
the subnet mask represent a network part, the 0s a host part.
Computers works only with bits. The math used to determine a network range is binary AND.
Let’s say that we have the IP address of 10.0.0.1 with the default subnet mask of 8 bits
(255.0.0.0).
First, we need to convert the IP address to binary:
IP address 10.0.0.1= 00001010.00000000.00000000.00000001
Subnet mask 255.0.0.0 = 11111111.00000000.00000000.0000000
Computers then use the AND operation to determine the network number:

The computer can then determine the size of the network. Only IP addresses that begins with 10
will be in the same network. So, in this case, the range of addresses in this network is 10.0.0.0 –
10.255.255.255.

Default Gateway

A default gateway serves as an access point or IP router that a networked computer uses to send
information to a computer in another network or the internet. Default simply means that this
gateway is used by default, unless an application specifies another gateway. The default server
does not even need to be a router; it may be a computer with two network adapters, where one is
connected to the local subnet and the other is connected to an outside network.

A default gateway allows computers on a network to communicate with computers on another


network. Without it, the network is isolated from the outside. Basically, computers send data that
is bound for other networks (one that does not belong to its local IP range) through the default
gateway.
Network administrators configure the computer’s routing capability with an IP range's starting
address as the default gateway and point all clients to that IP address.

Conclusion: - We configured IP of system and studied about subnet mask and default Gateway.
Experiment No. 3

Aim: Installation and introduction to Wireshark.

Theory:

Install Wireshark in Ubuntu:


1. Open terminal by either pressing Ctrl+Alt+T or searching for ‘terminal’ from app launcher. When it
opens, run command:

sudo add-apt-repository ppa:wireshark-dev/stable

2.If you’ve the previous Wireshark 2.4.x installed on your system, remove it first via command:

sudo apt-get remove --autoremove wireshark

3. Finally run following commands one by one in terminal to install Wireshark 2.6:

sudo apt-get update

sudo apt-get install wireshar

Uninstall:
To remove the software, open terminal and run command:

sudo apt-get remove --autoremove wireshark wireshark-*

And remove the PPA by launching Software & Updates -> Other Software tab.
Wireshark:

Wireshark is a network packet analyzer. A network packet analyzer will try to capture network
packets and tries to display that packet data as detailed as possible.

You could think of a network packet analyzer as a measuring device used to examine what’s going
on inside a network cable, just like a voltmeter is used by an electrician to examine what’s going
on inside an electric cable (but at a higher level, of course).

In the past, such tools were either very expensive, proprietary, or both. However, with the advent
of Wireshark, all that has changed.

Wireshark is perhaps one of the best open source packet analyzers available today.

Wireshark is a free and open-source packet analyzer that captures data packets flowing over the
network (wire) and presents them in an understandable form through its GUI. It is used for
network troubleshooting, analysis, software and communications protocol development, and
education. It runs on Linux, OS X, BSD, Solaris, some other Unix-like operating systems, and
Microsoft Windows. There is also a terminal-based (non-GUI) version called TShark. Wireshark,
and the other programs distributed with it such as TShark, are free software, released under the
terms of the GNU General Public License. Wireshark supports a wide range of protocols
likeTCP, UDP, HTTP and even advanced protocols such as AppleTalk. It has several advance
options such as filtering the packets, exporting packets, and name resolution. Wireshark can
capture live data flowing through the network.
Some intended purposes

Here are some examples people use Wireshark for:

• Network administrators use it to troubleshoot network problems


• Network security engineers use it to examine security problems
• QA engineers use it to verify network applications
• Developers use it to debug protocol implementations
• People use it to learn network protocol internals

Beside these examples Wireshark can be helpful in many other situations too.

Features

The following are some of the many features Wireshark provides:

• Available for UNIX and Windows.


• Capture live packet data from a network interface.
• Open files containing packet data captured with tcpdump/WinDump, Wireshark, and a
number of other packet capture programs.
• Import packets from text files containing hex dumps of packet data.
• Display packets with very detailed protocol information.
• Save packet data captured.
• Export some or all packets in a number of capture file formats.
• Filter packets on many criteria.
• Search for packets on many criteria.
• Colorize packet display based on filters.
• Create various statistics.
• …and a lot more!

Working of Wireshark

In computer networking, promiscuous mode or promisc mode is a mode for a wired network
interface controller (NIC) or wireless network interface controller (WNIC) that causes the
controller to pass all traffic it receives to the central processing unit (CPU) rather than passing
only the frames that the controller is intended to receive. This mode is normally used for packet
sniffing that takes place on a router or on a computer connected to a hub (instead of a switch) or
one being part of a WLAN. Interfaces are placed into promiscuous mode by software bridges
often used with hardware virtualization.

The Wireshark network sniffing make use of the promiscuous mode. First, Wireshark transfers
the network interface into promiscuous mode where it can capture raw binary data flowing
through the network. Then the chunks of binary data collected are then converted into a readable
form. The packets are also re-assembled based on their sequence. Finally the captured and re-
assembled data is analyzed. The initial analysis involves identifying the protocol type, the
communication channel, port numbers, and so on. At an advanced level, the different protocol
headers can also be analyzed for a deeper understanding.

Start capturing data in your local machine

You can start capturing by either clicking on interface list, selecting your network card and
clicking start there, or by selecting your network card under the start and clicking on start.

You can list the available capture interfaces, show the capture options, start a new live capture,
stop the running live capture and also restart the running live capture using the icons available on
top (towards left) under menu options. You can also save the capture using the save icon or by
going to File > Save.

Figure 1: Wireshark Network Analyzer


Figure1: Wireshark captures packets and lets you examine their contents.
You can analyze the saved capture files using wireshark utilizing its features such as filtering.
For instance, if you need your http request/response details, search for http in the filter.

There are also icons on top (towards right) for zoomin in and out, resize all columns, edit capture
filter, edit/apply display filter, edit coloring rules, edit preferences etc. Edit capture filter will
only capture as per settings whereas display filter will capture everything and show you as per
your filter.

Applying Filters to captured packets

Filters – There are display filters and capture filters. Display filters can be used on already
captured packets. Specify any one of the following items in the display filter and press “Apply”.

a. TCP:

Conclusion: We studied how to install wireshark and wireshark as network analyzer.


Experiment No. 04

Aim: Wireshark Lab: Ethernet and ARP

Theory:What is the 48-bit Ethernet address of your computer?


My 48-bit Ethernet address is 00:11:11:1e:94:3a

2. What is the 48-bit destination address in the Ethernet frame? Is this the Ethernet
address of gaia.cs.umass.edu? (Hint: the answer is no). What device has this as its
Ethernet address? [Note: this is an important question, and one that students
sometimes get wrong. Re-read pages 468-469 in the text and make sure you
understand the answer here.]

The 48-bit destination address in the Ethernet frame is 00:11:50:53:95:77.


This is not the Ethernet address of gaia.cs.umass.edu. It is the mac address for my router or
internet gateway address.

3. Give the hexadecimal value for the two-byte Frame type field. What do the bit(s)
whose value is 1 mean within the flag field?

Type: IP 0x0800

4. How many bytes from the very start of the Ethernet frame does the ASCII “G” in
“GET” appear in the Ethernet frame?

After 432 bits or 54 bytes the G in get appears.

5. What is the hexadecimal value of the CRC field in this Ethernet frame?

There is no hexadecimal value for crc in the Ethernet frame


6. What is the value of the Ethernet source address? Is this the address of your
computer, or of gaia.cs.umass.edu (Hint: the answer is no). What device has this
as its Ethernet address?

The Source address is 00:11:50:53:95:77. This address is the address of my belkins


router/internet gateway address.

7. What is the destination address in the Ethernet frame? Is this the Ethernet address
of your computer?

The Destination address is 00:11:11:1e:94:3a. This is the Ethernet address of my computer.


8. Give the hexadecimal value for the two-byte Frame type field. What do the bit(s)
whose value is 1 mean within the flag field?

The two-byte frame type field is 0x0800. The bit that is valued to 1 says to not fragment the set.

9. How many bytes from the very start of the Ethernet frame does the ASCII “O” in
“OK” (i.e., the HTTP response code) appear in the Ethernet frame?
The o in the ok starts after 104 bits or 13 bytes.

10. What is the hexadecimal value of the CRC field in this Ethernet frame.

There is no crc field in this Ethernet frame.

11. Write down the contents of your computer’s ARP cache. What is the meaning of
each column value?

The first column is the internet address of the computer then its physical address and finally what
type it is and it is
dynamic.
12. What are the hexadecimal values for the source and destination addresses in the
Ethernet frame containing the ARP request message?

The source address is (00:11:50:53:95:77)


The Destination address is (00:11:11:1e:94:3a)

13. Give the hexadecimal value for the two-byte Ethernet Frame type field. What do
the bit(s) whose value is 1 mean within the flag field?

The hexadecimal value is Type: ARP (0x0806)


14. Download the ARP specification from ftp:https://ftp.rfc-editor.org/innotes/std/std37.txt. A
readable, detailed discussion of ARP is also at

https://www.erg.abdn.ac.uk/users/gorry/course/inet-pages/arp.html.
a) How many bytes from the very beginning of the Ethernet frame does the
ARP opcode field begin?

It begins 42 bytes from the beginning of the Ethernet frame

b) What is the value of the opcode field within the ARP-payload part of the
Ethernet frame in which an ARP request is made?

The value of the opcode field within the ARP-payload is 0x0001

c) Does the ARP message contain the IP address of the sender?


Yes

d) Where in the ARP request does the “question” appear – the Ethernet
address of the machine whose corresponding IP address is being queried?

The question appears in the mac destination address.

15. Now find the ARP reply that was sent in response to the ARP request.
a) How many bytes from the very beginning of the Ethernet frame does the
ARP opcode field begin?

It is 10 bytes from the beginning

b) What is the value of the opcode field within the ARP-payload part of the
Ethernet frame in which an ARP response is made?
It is 2

c) Where in the ARP message does the “answer” to the earlier ARP request
appear – the IP address of the machine having the Ethernet address whose
corresponding IP address is being queried?

Sender MAC address: Intel_1e:94:3a (00:11:11:1e:94:3a)


16. What are the hexadecimal values for the source and destination addresses in the
Ethernet frame containing the ARP reply message?

Source: Intel_1e:94:3a (00:11:11:1e:94:3a)


Destination: Belkin_53:95:77 (00:11:50:53:95:77)

Conclusion: Traced and studied ARP and Ethernet details in Wireshark.


Experiment No. 5

Aim: To find out shortest path from source to destination using Dijkstras Algorithm.

Objective: Student should be able to understand and implement the program shortest path
algorithm.

Theory:

Dijkstra’s algorithm is very similar to Prim’s algorithm for minimum spanning tree. Like Prim’s
MST, we generate a SPT (shortest path tree) with given source as root. We maintain two sets,
one set contains vertices included in shortest path tree, other set includes vertices not yet
included in shortest path tree. At every step of the algorithm, we find a vertex which is in the
other set (set of not yet included) and has minimum distance from source.

Below are the detailed steps used in Dijkstra’s algorithm to find the shortest path from a single
source vertex to all other vertices in the given graph. Algorithm 1) Create a set sptSet (shortest
path tree set) that keeps track of vertices included in shortest path tree, i.e., whose minimum
distance from source is calculated and finalized. Initially, this set is empty. 2) Assign a distance
value to all vertices in the input graph. Initialize all distance values as INFINITE. Assign
distance value as 0 for the source vertex so that it is picked first. 3) While sptSet doesn’t include
all vertices ….a) Pick a vertex u which is not there in sptSetand has minimum distance value.
….b) Include u to sptSet. ….c) Update distance value of all adjacent vertices of u. To update the
distance values, iterate through all adjacent vertices. For every adjacent vertex v, if sum of
distance value of u (from source) and weight of edge u-v, is less than the distance value of v,
then update the distance value of v.
The set sptSetis initially empty and distances assigned to vertices are {0, INF, INF, INF, INF,
INF, INF, INF} where INF indicates infinite. Now pick the vertex with minimum distance value.
The vertex 0 is picked, include it in sptSet. So sptSet becomes {0}. After including 0 to sptSet,
update distance values of its adjacent vertices. Adjacent vertices of 0 are 1 and 7. The distance
values of 1 and 7 are updated as 4 and 8. Following subgraph shows vertices and their distance
values, only the vertices with finite distance values are shown. The vertices included in SPT are
shown in green color.

Pick the vertex with minimum distance value and not already included in SPT (not in sptSET).
The vertex 1 is picked and added to sptSet. So sptSet now becomes {0, 1}. Update the distance
values of adjacent vertices of 1. The distance value of vertex 2 becomes 12.

Pick the vertex with minimum distance value and not already included in SPT (not in sptSET).
The vertex 1 is picked and added to sptSet. So sptSet now becomes {0, 1}. Update the distance
values of adjacent vertices of 1. The distance value of vertex 2 becomes 12.
Pick the vertex with minimum distance value and not already included in SPT (not in sptSET).
Vertex 6 is picked. So sptSet now becomes {0, 1, 7, 6}. Update the distance values of adjacent
vertices of 6. The distance value of vertex 5 and 8 are updated.

Pick the vertex with minimum distance value and not already included in SPT (not in sptSET).
Vertex 7 is picked. So sptSet now becomes {0, 1, 7}. Update the distance values of adjacent
vertices of 7. The distance value of vertex 6 and 8 becomes finite (15 and 9 respectively).

We repeat the above steps until sptSet doesn’t include all vertices of given graph. Finally, we get
the following Shortest Path Tree (SPT).
Algorithm:

// A C / C++ program for Dijkstra's single source shortest path algorithm.


// The program is for adjacency matrix representation of the graph
#include <stdio.h>
#include <limits.h>
// Number of vertices in the graph
#define V 9
// A utility function to find the vertex with minimum distance value, from
// the set of vertices not yet included in shortest path tree
int minDistance(int dist[], bool sptSet[])
{
// Initialize min value
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
// A utility function to print the constructed distance array
int printSolution(int dist[], int n)
{
printf("Vertex Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t\t %d\n", i, dist[i]);
}

Program:

#include<stdio.h>
#include<conio.h>
#define INFINITY 9999
#define MAX 10

void dijkstra(int G[MAX][MAX],int n,int startnode);


int main()
{
int G[MAX][MAX],i,j,n,u;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");

for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);

printf("\nEnter the starting node:");


scanf("%d",&u);
dijkstra(G,n,u);

return 0;
}

void dijkstra(int G[MAX][MAX],int n,int startnode)


{

int cost[MAX][MAX],distance[MAX],pred[MAX];
int visited[MAX],count,mindistance,nextnode,i,j;

//pred[] stores the predecessor of each node


//count gives the number of nodes seen so far
//create the cost matrix
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(G[i][j]==0)
cost[i][j]=INFINITY;
else
cost[i][j]=G[i][j];

//initialize pred[],distance[] and visited[]


for(i=0;i<n;i++)
{
distance[i]=cost[startnode][i];
pred[i]=startnode;
visited[i]=0;
}

distance[startnode]=0;
visited[startnode]=1;
count=1;
while(count<n-1)
{
mindistance=INFINITY;

//nextnode gives the node at minimum distance


for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i])
{
mindistance=distance[i];
nextnode=i;
}

//check if a better path exists through nextnode


visited[nextnode]=1;
for(i=0;i<n;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i])
{
distance[i]=mindistance+cost[nextnode][i];
pred[i]=nextnode;
}
count++;
}

//print the path and distance of each node


for(i=0;i<n;i++)
if(i!=startnode)
{
printf("\nDistance of node%d=%d",i,distance[i]);
printf("\nPath=%d",i);

j=i;
do
{
j=pred[j];
printf("<-%d",j);
}while(j!=startnode);
}
}

Conclusion: Hence we studied and implement to shortest path between any node.
Experiment No. 6

Aim: To Establish A Straight Over And A Cross Over Cable In LAN.


Theory:

Common Ethernet network cable are straight and crossover cable. This Ethernet network
cable is made of 4 pair high performance cable that consists twisted pair conductors that used for
data transmission. Both end of cable is called RJ45 connector.

The cable can be categorized as Cat 5, Cat 5e, Cat 6 UTP cable. Cat 5 UTP cable can
support 10/100 Mbps Ethernet network, whereas Cat 5e and Cat 6 UTP cable can support
Ethernet network running at 10/100/1000 Mbps. You might heard about Cat 3 UTP cable, it's not
popular anymore since it can only support 10 Mbps Ethernet network.

Straight and crossover cable can be Cat3, Cat 5, Cat 5e or Cat 6 UTP cable, the only
difference is each type will have different wire arrangement in the cable for serving different
purposes.

Straight Cable

You usually use straight cable to connect different type of devices. This type of cable will be
used most of the time and can be used to:
1) Connect a computer to a switch/hub's normal port.
2) Connect a computer to a cable/DSL modem's LAN port.
3) Connect a router's WAN port to a cable/DSL modem's LAN port.
4) Connect a router's LAN port to a switch/hub's uplink port.(normally used for expanding
network)
5) Connect 2 switches/hubs with one of the switch/hub using an uplink port and the other one
using normal port.

If you need to check how straight cable looks like, it's easy. Both side (side A and side B) of
cable have wire arrangement with same color. Check out different types of straight cable that
are available in the market here.

Crossover Cable

Sometimes you will use crossover cable, it's usually used to connect same type of devices. A
crossover cable can be used to:
1) Connect 2 computers directly.
2) Connect a router's LAN port to a switch/hub's normal port. (normally used for expanding
network)
3) Connect 2 switches/hubs by using normal port in both switches/hubs.

In you need to check how crossover cable looks like, both side (side A and side B) of cable
have wire arrangement with following different color .

Step 1:

Cut the shielding off the cable, which will expose the 4 pairs of wires. Blue, Green, Orange and
Brown. When it comes to creating a straight through cable the color combination does not
matter. What ever the color of the first end is, make the second end the same.
When it comes to RJ45 Standards its different. The standard rj45 colors are:

White Orange
Orange
White Green
Blue
White Blue
Green
White Brown
Brown

Step 2:

Line the wires according to the image below. This is the rj45 Straight through standard colors.
This will be the same color on both ends of the cable.

Cut the excess wire off, i usually leave half inch. This usually fits in the head perfect.
Above is the final cut. The White Orange is Pin 1 and Brown is Pin 8.

Pin Outs ( tab facing down and pins away from you )

Step 3:

RJ45 Head, When placing the wires into the head try to line it up length wise. Similar to what is
shown couple images above.
In the image above you can see how the wires are inserted into the rj45 head.

Make sure the wires reach the copper / gold pins. This is important because its what connect the
wires to whatever you plug the cable into.

Now, use the crimper can crimp the wires and you are finished.

Conclusion: In this experiment we have learned how to create LAN cable.


Experiment No. 7

Aim: Implementation of Congestion Control Algorithm (Leaky Bucket Algorithm.)

Objective: Student should be able to understand and implement the program leaky bucket
algorithm.

Theory:

Theory The congesting control algorithms are basically divided into two groups: open loop and
closed loop. Open loop solutions attempt to solve the problem by good design, in essence, to
make sure it does not occur in the first place. Once the system is up and running, midcourse
corrections are not made. Open loop algorithms are further divided into ones that act at source
versus ones that act at the destination.

In contrast, closed loop solutions are based on the concept of a feedback loop if there is any
congestion. Closed loop algorithms are also divided into two sub categories: explicit feedback
and implicit feedback. In explicit feedback algorithms, packets are sent back from the point of
congestion to warn the source. In implicit algorithm, the source deduces the existence of
congestion by making local observation, such as the time needed for acknowledgment to come
back.

The presence of congestion means that the load is (temporarily) greater than the resources (in
part of the system) can handle. For subnets that use virtual circuits internally, these methods can
be used at the network layer.

Another open loop method to help manage congestion is forcing the packet to be transmitted at a
more predictable rate. This approach to congestion management is widely used in ATM
networks and is called traffic shaping.

The other method is the leaky bucket algorithm. Each host is connected to the network by an
interface containing a leaky bucket, that is, a finite internal queue. If a packet arrives at the queue
when it is full, the packet is discarded. In other words, if one or more process are already queued,
the new packet is unceremoniously discarded. This arrangement can be built into the hardware
interface or simulate d by the host operating system. In fact it is nothing other than a single
server queuing system with constant service time.
The host is allowed to put one packet per clock tick onto the network. This mechanism turns an
uneven flow of packet from the user process inside the host into an even flow of packet onto the
network, smoothing out bursts and greatly reducing the chances of congestion.

Program:

#include<iostream.h>

#include<dos.h>

#include<stdlib.h>

#define bucketSize 512

void bktInput(int a,int b)

if(a>bucketSize) cout<<"\n\t\tBucket overflow";

else

{ delay(500);

while(a>b)

{
cout<<"\n\t\t"<<b<<" bytes outputted.";

a-=b;

delay(500);

if (a>0) cout<<"\n\t\tLast "<<a<<" bytes sent\t";

cout<<"\n\t\tBucket output successful"; } }

void main()

int op, pktSize;

randomize();

cout<<"Enter output rate : ";

cin>>op;

for(int i=1;i<=5;i++)

delay(random(1000));

pktSize=random(1000);

cout<<"\nPacket no "<<i<<"\tPacket size = "<<pktSize;

bktInput(pktSize,op); } }

Output:

Enter output rate : 100

Packet no 0 Packet size = 3

Bucket output successful

Last 3 bytes sent

Packet no 1 Packet size = 33


Bucket output successful

Last 33 bytes sent

Packet no 2 Packet size = 117

Bucket output successful

100 bytes outputted.

Last 17 bytes sent

Packet no 3 Packet size = 95

Bucket output successful

Last 95 bytes sent

Packet no 4 Packet size = 949

Bucket overflow

Conclusion: Hence we studied and implement program for leaky bucket algorithm.
Experiment No. 8

Aim: Creating workgroup of computers and resource sharing (file & printer) (Ubuntu OS)

Theory:

1. Install Samba and the graphical configuration tool:


Press Ctrl+Alt+T on keyboard to open the terminal. When it opens, paste the command
below and hit run:

sudo apt-get install samba samba-common system-config-samba python-glade2 gksu

2. Open Unity Dash, search for and open the samba configuration tool:

3. When the tool opens, go to Preferences -> Server Settings.

Under Basic tab:

• Workgroup. Same to your Windows Workgroup name (case-sensitive). In Windows 7,


right-click Computer icon and go to Properties, there you’ll see Windows Workgroup
name.
• Description.This is the name of your computer as seen by Windows Users.
As it is not advisable to allow ‘Guests’ there should be no reason to change the ‘security’
settings tab unless you wish to do so.
Finally click the OK button to save it.

(Optional) 4. Create a special user for network file sharing

Go to System Settings -> User Accounts -> Click unlock -> Click + (plus) icon ->
Choose Standard account and type in names.

Remember to set a password to enable the new account.


5. Next go to Preferences -> Samba Users. Click Add User:

• Unix Username: Select a user on this Ubuntu machine. You’ll access the shares from
Windows machine with this user privilege. You can create a special user for file sharing
by step 4
• Windows Username: When accessing from Windows machine, you’ll be asked to type
this username and the password below.
• Samba password: When accessing from Windows machine, you’ll be asked to type the
username above and this password.
• Confirm Samba password.

Finally, restart Samba service and done!

sudo restart smbd && sudo restart nmbd

To share a folder, click the green + (plus) button in Samba Server Configuration tool and you
can then easily set the directory, name, read/write permissions and access users.

Conclusion: By installing SAMBA and creating workgroup of systems we shared files.


Experiment No. 9

Aim: Installation of Cisco Packet Tracer and demonstration of simple network topology
using Cisco Packet Tracer.

Theory:

Installation of Cisco Packet Tracer:


Downloading Packet Tracer:

You can download and use Cisco Packet Tracer for free. You need a Cisco Network Academy
account in order to download and use Cisco Packet Tracer. You can create a Cisco Network
Academy account for free.
To create a Cisco Network Academy account, visit https://www.netacad.com/courses/packet-
tracerfrom any web browser of your choice and you should see the following page. Now click
on Enroll to download Packet Tracer as marked in the screenshot below.
You should see the following page. Now click on Sign up today! as marked in the screenshot
below.

Now click on English.


A sign up page should open. Fill in the details and click on Create Account as marked in the
screenshot below.

Once you’ve signed up and verified your account, go to https://www.netacad.com/ and you
should see the following page. Click on Log In as marked in the screenshot below.
Now type in your email and password and click on Log In.

Once you’re logged in, click on Resource > Download Packet Tracer as marked in the
screenshot below.
Now navigate to the Download section. At the time of this writing, Packet Tracer 7.2 is the latest
version. From the Linux Desktop Version 7.2 English section, click on 64 Bit Download link
as marked in the screenshot below.

Your browser should prompt you to download Packet Tracer. Click on Save File and click
on OK.
Your download should start.

Installing Packet Tracer on Ubuntu 18.04 LTS:Now that Packet Tracer is downloaded. It’s time
to install it.First, navigate to the ~/Downloads directory of your Ubuntu 18.04 LTS machine with
the following command:

$ cd ~/Downloads
As you can see, Packet Tracer archive is available
here.

Now make a new directory (Let’s call it PT72Installer) to extract the installer from the Packer
Tracer archive you just downloaded.
$ mkdir PT72Installer

Now extract the Packet Tracer archive with the following command:

$ sudo tar xvzf 'Packet Tracer 7.2 for Linux 64 bit.tar.gz' -C PT72Installer

All the files are extracted to PT72Installer


directory.
Now navigate to the PT72Installer/ directory with the following command:
$ cd PT72Installer

Now start the installer with the following command:

$ ./install

Now press <Enter>.

Press <Enter> a few more times.


At the end of the License agreement, press y and then press <Enter>.

Leave the default and press <Enter>.

Press y and then press <Enter>.


Press y and then press <Enter> to continue.

Packet Tracer 7.2 should be installed.

Now restart your computer with the following command:

$ sudo reboot

Once your computer starts, navigate to the Packet Tracker directory /opt/pt/bin with the
following command:
$ cd /opt/pt/bin
Now if you try to start Packet Tracer, you should see the following error. It
means, libpng12.so.0library file is not available in your computer. The library file is not
available in the Ubuntu 18.04 LTS package repository as well. But you can download and install
the library package from Debian Jessie package repository. It should solve our problem.

First, navigate to the /tmp directory with the following command:


$ cd /tmp

To download the libpng12-0 library package from Debian Jessie package repository, run the
following command:
$ wget https://ftp.us.debian.org/debian/pool/main/libp/libpng/libpng12-0_1.2.50-2+
deb8u3_amd64.deb

libpng12-0 should be downloaded.

Now, install libpng12-0 with the following command:


$ sudo dpkg -i libpng12-0_1.2.50-2+deb8u3_amd64.deb
libpng12-0 should be installed.

Now go back to the Packet Tracer directory (/opt/pt/bin) with the following command:
$ cd /opt/pt/bin

If you try to run Packet Tracer, you may still get some errors! The required Qt libraries are not
installed.

To install all the required Qt libraries, run the following command:

$ sudo apt update && sudo apt install libqt5webkit5 libqt5multimediawidgets5


libqt5svg5 libqt5script5 libqt5scripttools5 libqt5sql5

Now press y and then press <Enter>.


The Qt libraries should be installed.

Now try to run Packet Tracer again.

$ ./PacketTracer7

We got a prompt! Click on OK.

Now you should see the following window. Login to your Cisco Network Academy account.
Packet Tracer 7.2 should start.

You can also start Packet Tracer 7.2 with the following command:

$ packettracer
Using Packet Tracer 7.2:
In this section, I will design a simple network topology and show you how Packet Tracer
works.First, start Packet Tracer 7.2. Now click on Network Devices icon and then click
on Switches icon as marked in the screenshot below.

Now click and drag one of the switches to the project window.
Now click on the End Devices icon. As you can see, a lot of end devices such as PC, Laptop,
Server etc are listed.

Now drag and drop 2 PCs to the project window.


Now click on the Cable icon.

Then click on a PC and then on the Switch in your project window. They should be connected.

Connect the other PC to the switch the same way.


Now double click on any of the PC and you should see the following window. Go to
the Desktoptab.

Now click on Configuration.


Now, fill in the IPv4 details as follows in one of the PCs and click on the X button once you’re
done.
The same way, fill in the IPv4 details as follows in the other PC:

Now click on the Command Prompt icon on one of the PCs.

The command prompt should start. Now try to ping one PC from the other.

$ ping 192.168.111.10

As you can see, the ping is working.


As you can see, the ping is working both ways. I can connect to one PC from the other.
You can also login to the IOS console of your CISCO Switch. Just double click on the Switch in
your project window and go to the CLI tab.

Conclusion: We installed Cisco Packet Tracer a Network Simulator and developed a simple
network topology.
Experiment No. 10

Aim: Socket programming for TCP and UDP.


Theory:

Socket Programming in C/C++

What is Socket Programming?

Socket programming is a way of connecting two nodes on a network to communicate with


each other. One socket(node) listens on a particular port at an IP, while other socket reaches
out to the other to form a connection. Server forms the listener socket while client reaches
out to the server.

Figure1: State diagram for server and client model

Stages for server

• Socket creation:

int sockfd = socket(domain, type, protocol)

sockfd: socket descriptor, an integer (like a file-handle)


domain: integer, communication domain e.g., AF_INET (IPv4 protocol) , AF_INET6 (IPv6
protocol)
type: communication type
SOCK_STREAM: TCP(reliable, connection oriented)
SOCK_DGRAM: UDP(unreliable, connectionless)
protocol: Protocol value for Internet Protocol(IP), which is 0. This is the same number which
appears on protocol field in the IP header of a packet.(man protocols for more details)

• Setsockopt:

• int setsockopt(int sockfd, int level, int optname,

const void *optval, socklen_t optlen);

This helps in manipulating options for the socket referred by the file descriptor sockfd. This
is completely optional, but it helps in reuse of address and port. Prevents error such as:
“address already in use”.

• Bind:

• int bind(int sockfd, const struct sockaddr *addr,

socklen_t addrlen);

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.

• Listen:

int listen(int sockfd, int backlog);

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.

• Accept:

int new_socket= accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);

It extracts the first connection request on the queue of pending connections for the listening
socket, sockfd, creates a new connected socket, and returns a new file descriptor referring to
that socket. At this point, connection is established between client and server, and they are
ready to transfer data.

Stages for Client

• Socket connection: Exactly same as that of server’s socket creation


• Connect:

• int connect(int sockfd, const struct sockaddr *addr,

socklen_t addrlen);

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.

Implementation
Here we are exchanging one hello message between server and client to demonstrate the
client/server model.

Server.c

// Server side C/C++ program to demonstrate Socket programming


#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#define PORT 8080
int main(int argc, char const *argv[])
{
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
char *hello = "Hello from server";

// Creating socket file descriptor


if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}

// Forcefully attaching socket to the port 8080


if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
&opt, sizeof(opt)))
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );

// Forcefully attaching socket to the port 8080


if (bind(server_fd, (struct sockaddr *)&address,
sizeof(address))<0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
if ((new_socket = accept(server_fd, (struct sockaddr *)&address,
(socklen_t*)&addrlen))<0)
{
perror("accept");
exit(EXIT_FAILURE);
}
valread = read( new_socket , buffer, 1024);
printf("%s\n",buffer );
send(new_socket , hello , strlen(hello) , 0 );
printf("Hello message sent\n");
return 0;
}

Client.c

// Client side C/C++ program to demonstrate Socket programming


#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#define PORT 8080

int main(int argc, char const *argv[])


{
struct sockaddr_in address;
int sock = 0, valread;
struct sockaddr_in serv_addr;
char *hello = "Hello from client";
char buffer[1024] = {0};
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Socket creation error \n");
return -1;
}

memset(&serv_addr, '0', sizeof(serv_addr));

serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);

// Convert IPv4 and IPv6 addresses from text to binary form


if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0)
{
printf("\nInvalid address/ Address not supported \n");
return -1;
}

if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)


{
printf("\nConnection Failed \n");
return -1;
}
send(sock , hello , strlen(hello) , 0 );
printf("Hello message sent\n");
valread = read( sock , buffer, 1024);
printf("%s\n",buffer );
return 0;
}

Compiling:
gcc client.c -o client
gcc server.c -o server

Output:
Client:Hello message sent
Hello from server
Server:Hello from client
Hello message sent

UDP Server-Client implementation

In UDP, the client does not form a connection with the server like in TCP and instead just sends
a datagram. Similarly, the server need not accept a connection and just waits for datagrams to
arrive. Datagrams upon arrival contain the address of sender which the server uses to send data
to the correct client.
Figure: State digram for client server model in UDP

The entire process can be broken down into following steps :


UDP Server :

1. Create UDP socket.

2. Bind the socket to server address.

3. Wait until datagram packet arrives from client.

4. Process the datagram packet and send a reply to client.

5. Go back to Step 3.

UDP Client :

1. Create UDP socket.

2. Send message to server.

3. Wait until response from server is recieved.

4. Process reply and go back to step 2, if necessary.

5. Close socket descriptor and exit


Necessary Functions :

int socket(int domain, int type, int protocol)

Creates an unbound socket in the specified domain.

Returns socket file descriptor.

Arguments:
domain – Specifies the communication
domain ( AF_INET for IPv4/ AF_INET6 for IPv6 )
type – Type of socket to be created
( SOCK_STREAM for TCP / SOCK_DGRAM for UDP )
protocol – Protocol to be used by socket.
0 means use default protocol for the address family.

int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen)


Assigns address to the unbound socket.

Arguments :
sockfd – File descriptor of socket to be binded
addr – Structure in which address to be binded to is specified
addrlen – Size of addr structure

ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,
const struct sockaddr *dest_addr, socklen_t addrlen)
Send a message on the socket

Arguments :
sockfd – File descriptor of socket
buf – Application buffer containing the data to be sent
len – Size of buf application buffer
flags – Bitwise OR of flags to modify socket behaviour
dest_addr – Structure containing address of destination
addrlen – Size of dest_addr structure

ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,


struct sockaddr *src_addr, socklen_t *addrlen)
Receive a message from the socket.
Arguments :
sockfd – File descriptor of socket
buf – Application buffer in which to receive data
len – Size of buf application buffer
flags – Bitwise OR of flags to modify socket behaviour
src_addr – Structure containing source address is returned
addrlen – Variable in which size of src_addr structure is returned

int close(int fd)


Close a file descriptor

Arguments:
fd – File descriptor

UDPServer.c

// Server side implementation of UDP client-server model


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#define PORT 8080


#define MAXLINE 1024

// Driver code
int main() {
int sockfd;
char buffer[MAXLINE];
char *hello = "Hello from server";
struct sockaddr_in servaddr, cliaddr;

// Creating socket file descriptor


if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}

memset(&servaddr, 0, sizeof(servaddr));
memset(&cliaddr, 0, sizeof(cliaddr));

// Filling server information


servaddr.sin_family = AF_INET; // IPv4
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(PORT);
// Bind the socket with the server address
if ( bind(sockfd, (const struct sockaddr *)&servaddr,
sizeof(servaddr)) < 0 )
{
perror("bind failed");
exit(EXIT_FAILURE);
}

int len, n;
n = recvfrom(sockfd, (char *)buffer, MAXLINE,
MSG_WAITALL, ( struct sockaddr *) &cliaddr,
&len);
buffer[n] = '\0';
printf("Client : %s\n", buffer);
sendto(sockfd, (const char *)hello, strlen(hello),
MSG_CONFIRM, (const struct sockaddr *) &cliaddr,
len);
printf("Hello message sent.\n");

return 0;
}

UDPClient.c

// Client side implementation of UDP client-server model


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#define PORT 8080


#define MAXLINE 1024

// Driver code
int main() {
int sockfd;
char buffer[MAXLINE];
char *hello = "Hello from client";
struct sockaddr_in servaddr;

// Creating socket file descriptor


if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}

memset(&servaddr, 0, sizeof(servaddr));

// Filling server information


servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
servaddr.sin_addr.s_addr = INADDR_ANY;

int n, len;

sendto(sockfd, (const char *)hello, strlen(hello),


MSG_CONFIRM, (const struct sockaddr *) &servaddr,
sizeof(servaddr));
printf("Hello message sent.\n");

n = recvfrom(sockfd, (char *)buffer, MAXLINE,


MSG_WAITALL, (struct sockaddr *) &servaddr,
&len);
buffer[n] = '\0';
printf("Server : %s\n", buffer);

close(sockfd);
return 0;
}

Output:

$ ./server
Client : Hello from client
Hello message sent.

$ ./client
Hello message sent.
Server : Hello from server

Conclusion: We implemented a Socket Server and Client program for TCP.

You might also like