Sunteți pe pagina 1din 64

Mody University of Science & Technology

College of Engineering & Technology

Computer Network Lab


CS 333
Mody University

Submitted By
Ms. Aratrika Guin

Ajay Kumar Singh


Asst. Prof. CSE

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

Experiment-1
AIM : To configure a computer with the college network to access internet.
Steps to be followed are-

DISABLE : a) Right click on Unidentified Network.

b) Click on Open Network and Sharing Center.


c) Go to Change Adapter Settings.

d) Right click on Local Area Connection and click Disable.

e) Right click on Local Area Connection and go to Properties.


f) Click on Internet Protocol Version 4(TCP/IPv4).
g) Select- (i)Obtain an IP address automatically.
(ii)Obtain DNS server address automatically.

ENABLE : a) Right click on Unidentified Network.

Mody University

b) Click on Open Network and Sharing Center.


c) Go to Change Adapter Settings.

d) Right click on Local Area Connection and click Enable.

e) Right click on Local Area Connection and go to Properties.


f) Click on Internet Protocol Version 4(TCP/IPv4).

g) Select Use of the following IP Address and enter the IP Address, subnet
mask, default gateway, preferred DNS Server, Alternate DNS Server.

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

Experiment-2
AIM: To have a study on network devices.
Some of the commonly used network devices are-

HUB : A hub is a hardware device used to connect several computers together. Basically,
hubs are multi slot concentrators into which a number of multiport cards can be plugged
to provide additional access.

Active Hubs They electrically amplify the signal as it moves from one connected
device to another.
Passive Hubs They allow the signal to pass from one computer to another
without any change.

Function Hubs interconnect groups of users. They forward any data packet
including e-mail, word processing documents, spreadsheets- they receive over one port
from one workstation to all the remaining ports. All users connected to a single hub are
in the same segment, sharing the hubs bandwidth or data-carrying capacity.

SWITCH : A switch is a device that is used to segment networks into different sub

Mody University

networks called subnets or LAN segments. Segmenting the network into smaller subnets
prevents traffic overloading in a network.
A switch is responsible for filtering, i.e. transforming data in a specific way and
for forwarding packets between LAN segments.

Function To insulate the transmission from the other ports, the switch establishes a
temporary connection between source and destination, and then terminates the
connection once the conversion is done.

ROUTER : A router is a network device that is used to separate different segments in a


network to improve performance and reliability. A router works like a bridge but can
handle different protocols.

Function - Routers use a more complete packet address to determine which router or
workstation should receive each packet next. Based on a network road map called the
routing table, routers can help ensure that packets are travelling the most efficient paths
to their destinations. If a link between 2 routers fails, the sending router can determine
an alternate route to keep traffic moving.

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

GATEWAY : A gateway is a network device that connects dissimilar networks . It


establishes an intelligent connection between a local network and external networks with
completely different structures.

Function : A gateway is actually a node on a network that serves as an entrance to


another network. In enterprises, the gateway is the computer that routes the traffic from
a workstation to the outside network that is serving the web pages. In homes, the
gateway is the ISP that connects the user to the Internet.
In enterprises, the gateway node often acts as proxy server and a firewall is
designed to prevent unauthorized access.

BRIDGE : A bridge is a network device that establishes an intelligent connection between


two local networks with the same standard but different types of cables.

Function : Bridges know which computers are on which side of the bridge, so they
allow only those messages that need to go to the other side to cross the bridge. As a
packet arrives at the bridge, it examines the physical destination address of packet. The
bridge then decides whether or not to let the packet across.

Mody University

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

Experiment-3
AIM : Write a C program to input an IP Address from user, identify the address
and display the class of IP Address.

PROGRAM#include<stdio.h>
#include<conio.h>
void main()
{
int i,arr[4];
clrscr();
printf("Enter the 4 octet values of IP Address : ");
for(i=0;i<4;i++)

Mody University
scanf("%d",&arr[i]);

i=0;

if(arr[i]>=0 && arr[i]<=127)


printf("\nIP Address lies in Class A..");
else if(arr[i]>=128 && arr[i]<=191)
printf("\nIP Address lies in Class B..");
else if(arr[i]>=192 && arr[i]<=223)
printf("\nIP Address lies in Class C..");
else if(arr[i]>=224 && arr[i]<=239)
printf("\nIP Address lies in Class D..");
else if(arr[i]>=240 && arr[i]<=255)
printf("\nIP Address lies in Class E..");
getch();
}
4

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

OUTPUT-

Mody University

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

Experiment-4
AIM : Write a C program to enter a stream of 7 bits and check whether it is even or odd
parity. Now insert the 8th bit depending on whether the user wants to make the
stream even parity or odd parity.

PROGRAM#include<stdio.h>
#include<conio.h>
void main()
{
char arr[7];
int i,ctr=0,ch;

Mody University

clrscr();

printf("\nEnter 7 bits(0 or 1) : ");


for(i=0;i<7;i++)
scanf("%c",&arr[i]);
for(i=0;i<7;i++)
{
if(arr[i]=='1')
ctr++;
}
if(ctr%2==0)
printf("\nEven Parity..");
else
printf("\nOdd Parity..");

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

printf("\n1.EVEN PARITY..");
printf("\n2.ODD PARITY..");
printf("\nEnter your choice(1-2) : ");
scanf("%d",&ch);
switch(ch)
{
case 1 : if(ctr%2==0)
arr[7]='0';
else
arr[7]='1';
for(i=0;i<8;i++)
printf("%c",arr[i]);
break;

Mody University
case 2 : if(ctr%2==1)

arr[7]='0';

else
arr[7]='1';
for(i=0;i<8;i++)
printf("%c",arr[i]);
break;
}
getch();
}

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

OUTPUT-

Mody University

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

Experiment-5
AIM : Write a C program to identify the class of a given IP Address using string.
PROGRAM#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
char ip[4],c[4];
int i,a;
clrscr();
printf("Enter the IP Address : ");

Mody University
scanf("%s",&ip);

for(i=0;ip[i]!='.';i++)
c[i]=ip[i];
c[i]='\0';
`

a=atoi(c);
if(a>=0 && a<=127)
printf("Class A..");
else if(a>=128 && a<=191)
printf("Class B..");
else if(a>=192 && a<=223)
printf("Class C..");
else if(a>=224 && a<=239)
9

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

printf("Class D..");
else if(a>=240 && a<=255)
printf("Class E..");
else
printf("Invalid Address!!");
getch();
}

OUTPUT-

Mody University

10

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

Experiment-6
AIM : Write a C program to evaluate the IP header checksum.
PROGRAM#include<stdio.h>
#include<conio.h>
void main()
{
unsigned int arr[16];
long int checksum,sum=0,carry;
int i;
printf("Enter the IP Address in hexadecimal form : ");
for(i=0;i<16;i++)
{

Mody University
scanf("%x",&arr[i]);
sum=sum+arr[i];

}
printf("\nThe sum is = %x",sum);
carry=sum>>16;
printf("\nThe carry is = %x",carry);
sum=sum+carry;
checksum=~sum;
printf("\nThe checksum is = %x",checksum);
getch();
}
11

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

OUTPUT-

Mody University

12

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

Experiment-7
AIM : Write a C program to evaluate Longitudinal Redundancy Check(LRC).
PROGRAM//program to evaluate longitudinal redundancy check
#include<stdio.h>
#include<conio.h>
void main()
{
char a[9],b[9],c[9]={"000000000"};
int i;
printf("Enter the 1st string : ");
scanf("%s",&a);

Mody University

printf("Enter the 2nd string : ");


scanf("%s",&b);
for(i=0;i<8;i++)
{
if(a[i]==b[i])
c[i]='0';
else
c[i]='1';
}
printf("\n");

13

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

for(i=0;i<8;i++)
{
printf("%c",c[i]);
getch();
}
}

OUTPUT-

Mody University

14

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

Experiment-8
AIM : Introduction to Network Protocol Analyzer with the help of wire shark.
THEORY

: The basic tool for observing the messages exchanged between executing

protocol entities is called a packet sniffer. As the name suggests, a packet sniffer captures
(sniffs) messages being sent/received from/by your computer; it will also typically store
and/or display the contents of the various protocol fields in these captured messages. A
packet sniffer itself is passive. It observes messages being sent and received by
applications and protocols running on your computer, but never sends packets itself.
Similarly, received packets are never explicitly addressed to the packet sniffer. Instead, a
packet sniffer receives a copy of packets that are sent/received from/by application and
protocols executing on your machine.
Fig:1 shows the structure of a packet sniffer. At the right of Fig:1 are the
protocols (in this case, Internet protocols) and applications (such as a web browser or ftp
client) that normally run on your computer. The packet sniffer, shown within the dashed
rectangle in Fig:1 is an addition to the usual software in your computer, and consists of
two parts. The packet capture library receives a copy of every link-layer frame that is
sent from or received by your computer. The messages exchanged by higher layer
protocols such as HTTP, FTP, TCP, UDP, DNS, or IP all are eventually encapsulated in
link-layer frames that are transmitted over physical media such as an Ethernet cable. In
Fig:1, the assumed physical media is an Ethernet, and so all upper layer protocols are
eventually encapsulated within an Ethernet frame. Capturing all link-layer frames thus
gives you all messages sent/received from/by all protocols and applications executing in
your computer.

Mody University

FIG 1:
Packet
Sniffer
Structure

15

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

The second component of a packet sniffer is the packet analyzer, which displays
the contents of all fields within a protocol message. In order to do so, the packet
analyzer must understand the structure of all messages exchanged by protocols. For
example, suppose we are interested in displaying the various fields in messages
exchanged by the HTTP protocol in Fig:1. The packet analyzer understands the format of
Ethernet frames, and so can identify the IP datagram within an Ethernet frame. It also
understands the IP datagram format, so that it can extract the TCP segment within the IP
datagram. Finally, it understands the TCP segment structure, so it can extract the HTTP
message contained in the TCP segment. Finally, it understands the HTTP protocol and
so, for example, knows that the first bytes of an HTTP message will contain the string
GET, POST, or HEAD.
Wireshark is a packet analyzer that uses a packet capture library in our
computer. Wireshark is a free network protocol analyzer that runs on Windows,
Linux/Unix, and Mac computers. Its an ideal packet analyzer for our labs it is stable,
has a large user base and well-documented support that includes a user-guide and a
detailed FAQ, rich functionality that includes the capability to analyze hundreds of
protocols, and a well-designed user interface. It operates in computers using Ethernet,
Token-Ring, FDDI, serial (PPP and SLIP), 802.11 wireless LANs, and ATM connections.

Mody University

The Wireshark interface has five major components :

COMMAND MENU : The command menus are standard pulldown menus


located at the top of the window. The Capture menu allows you to begin packet
capture.

PACKET-LISTING WINDOW : The packet-listing window displays a one-line


summary for each packet captured, including the packet number, the time at
which the packet was captured, the packets source and destination addresses, the
protocol type, and protocol-specific information contained in the packet.
PACKET-HEADER DETAILS : The packet-header details window provides details
about the packet selected in the packet listing window. These details include
information about the Ethernet frame and IP datagram that contains this packet.

PACKET-CONTENTS WINDOW : The packet-contents window displays the entire


contents of the captured frame, in both ASCII and hexadecimal format.
PACKET DISPLAY FILTER FIELD : Towards the top of the Wireshark graphical
user interface, is the packet display filter field, into which a protocol name or
other information can be entered in order to filter the information displayed in
the packet-listing window.

16

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

FEATURES OF WIRESHARKThe following are some of the features that wireshark provides Available for UNIX and Windows.
Capture line 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.
Plug-ins can be created for dissecting new protocols.
Raw USB traffic can be captured.
VoIP calls in the captured traffic can be detected. If encoded in a compatible
encoding, the media flow can even be played.
Various settings, timers, and filters can be set that ensure only triggered traffic
appear.
Wireless connections can also be filtered as long as they transverse the monitored
Ethernet.

Mody University

17

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

HTTP
Q1) Is your browser running HTTP version 1.0 or 1.1? What version of HTTP is the
server running?
Ans) HTTP/1.1
Q2) What languages (if any) does your browser indicate that it can accept to the server?
Ans) English(US)
Q3) What is the IP address of your computer?
Ans) 10.20.111.11
Q4) What is the status code returned from the server to your browser?
Ans) Status code : 200
Q5) When was the HTML file that you are retrieving last modified at the server?
Ans) 0.000115000 seconds

Mody University

Q6) How many bytes of content are being returned to your browser?
Ans) Captured length : 1400 bytes

Q7) By inspecting the raw data in the packet content window, do you see any headers
within the data that are not displayed in the packet-listing window? If so, name
one.
Ans) Yes, there exists a header in the packet content window.
Header length : 20 bytes

18

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

Experiment-9
OBJECTIVE : To study DOS commands used in computer networking.
The commands used in computer networking are as follows-

Ipconfig(Internet Protocol Configuring)

Description : It displays all current TCP/IP network configuration values and


refreshes Dynamic Host Configuration Protocol(DHCP) and Domain Name
System(DNS) settings. Used without parameters, ipconfig displays the ip address,
subnet mask and default gateway for all adapters.

Syntax : ipconfig

Mody University

19

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

Ping
Description : Ping works by sending an Internet Control Message Protocol(ICMP)
Echo Request to a specified interface on the network and waiting for a reply. Ping
can be used for troubleshooting to test connectivity and determine response time.

Syntax : ping IP_Address

eg ping 10.20.111.10

Mody University

20

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

Netstat
Description : In computing, netstat(network statistics) is a command-line tool
that displays network connections for the Transmission Control Protocol (both
incoming and outgoing), routing tables, and a number of network interface
(network interface controller or software-defined network interface and network
protocol statistics).

Syntax : netstat

Mody University

21

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

Nslookup
Description : nslookup is a network administration command-line tool available
for many computer operating systems for querying the Domain Name
System(DNS) to obtain domain name or IP address mapping or for any other
specific DNS record.

Syntax : nslookup

Mody University

22

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

Tracert
Description : The tracert command is a Command Prompt command that is used
to show several details about the path that a packet takes from the computer or
device were on to whatever destination we specify.

Syntax : tracert IP_Address


eg : tracert 192.168.1.64

Mody University

23

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

Getmac
Description : getmac returns the media access control (MAC) address and list of
network protocols associated with each address for all network cards in each
computer, either locally or across a network.

Syntax : getmac

Mody University

24

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

Arp (Address Resolution Protocol)


Description : This command displays and modifies address resolution, including
ATM (Asynchronous Transfer Mode) interfaces.

Syntax : arp s

arp d
arp a

Mody University

25

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

Experiment-10
AIM : To study the color coding of RJ-45.
INTRODUCTIONRJ stands for registered jack. RJ-45 is a standard type of connector (UTP) for
network cables. RJ-45 connectors are most commonly seen with Ethernet cables and
networks. RJ-45 connectors feature eight pins to which the wire strands of a cable
interface electrically. It is a keyed connector, meaning the connector can be inserted in
only one way. Standard RJ-45 pin outs define the arrangement of the individual wires
needed when attaching connectors to a cable. RJ-45 interface is typically used for data
transmission, the most common applications for network interface cards. There are two
RJ-45 connector line : straight line, cross line.

Mody University
APPLICATIONSThese are used in telephone and data jack wiring registered with FCC. RJ-11 is a 6position, 4-conductor jack used in Ethernet wiring and RJ-45 is an 8-position, 8conductor jack used in Ethernet wiring i.e. used in Ethernet Networking.
RJ-45 conductor data cable contains 4 pairs of wires each consists of a solid colored
wire and a strip of the same color. There are 2 wiring standards for RJ-45 wiring : T568A and T-568B. Although there are 4 pairs of wires, Ethernet uses only 2 pairs :
Orange and Green. The other two colors (blue and brown) may be used for a second
Ethernet line or for phone connections. The two wiring standards are used to create a
cross-over cable (T-568A on one end, and T-568B on the other end), or a straightthrough cable (T-568B or T-568A on both ends).

26

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

Fig 1:TIA
568-A

Fig 2 : TIA
568-B

Mody University

Fig 3 : RJ-45
Cross-over

27

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

where,

g white/green
G green
o white/orange
O orange
b white/blue
B blue
br white/brown
BR brown

Mody University

28

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

Experiment-11
AIM : Write a program to identify the ipv4 and ipv6 address.
PROGRAM//program to check whether an ip address is ipv4 or ipv6.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#include<process.h>
void checkipv4(char[],int);
void checkipv6(char[],int);
void main()

Mody University

char ip[40];
int i,dot=0,colon=0;
clrscr();
printf("Enter an IP address : ");
scanf("%s",&ip);
for(i=0;i<(strlen(ip)-1);i++)
{
if(ip[i]=='.')
dot++;
else if(ip[i]==':')
colon++;
}
29

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

if(dot==3)
checkipv4(ip,dot);
else if(colon==7)
checkipv6(ip,colon);
else
printf("\nNot a valid IP address!!");
getch();
}
void checkipv4(char ip[],int dot)
{
char c[5];
int flag=0,i=0,j,k,val;
while(dot>=0)
{

Mody University
for(j=0;(ip[i]!='.' && i<=strlen(ip));j++,i++)
c[j]=ip[i];
c[j]='\0';
val=atoi(c);
if(val>=0 && val<=255)
flag++;
for(j=0;j<strlen(c);j++)
{
k=toascii(c[j]);
if(k>=48 && k<=57);

30

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

else
{
printf("\nNot an ipv4 address!!");
getch();
exit(0);
}
}
dot--;
i++;
}
if(flag==4)
printf("\nThis is an ipv4 address..");
else

Mody University
printf("\nThis is not an ipv4 address..");

getch();
}

void checkipv6(char ip[],int colon)


{
char c[5];
int i=0,j,k,val;
while(colon>=0)
{
for(j=0;ip[i]!='.' && i<=strlen(ip);j++,i++)
c[j]=ip[i];
c[j]='\0';
if(strlen(c)>4)

31

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

{
printf("\nNot an ipv6 address!!");
getch();
exit(0);
}
for(j=0;j<strlen(c);j++)
{
k=toascii(c[j]);
if(k>=48 && k<=57||k>=65 && k<=70||k>=97 && k<=102);
else
{
printf("\nNot an ipv6 address!!");
getch();

Mody University
exit(0);

}
colon--;
i++;
}
printf("\nThis is an ipv6 address..");
getch();
}

32

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

OUTPUT-

Mody University

33

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

Experiment-12
AIM : Write a C program to evaluate Cyclic Redundancy Check.

PROGRAM#include<stdio.h>
#include<conio.h>
#include<string.h>
#define N strlen(g)
void xor();
void crc();
char t[20],cs[20],g[10]="1011",e,a,c;
void main()
{

Mody University

clrscr();

printf("Enter the data : ");


scanf("%s",t);
printf("\nGenerator polynomial is %s",g);
a=strlen(t);
for(e=a;e<a+N-1;e++)
t[e]='0';
printf("\nModified data is %s",t);
crc();
for(e=a;e<a+N-1;e++)
t[e]=cs[e-a];
printf("\nFinal code is %s",t);

34

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

getch();
}
void xor()
{
for(c=1;c<N;c++)
{
if(cs[c]==g[c])
cs[c]='0';
else
cs[c]='1';
}
}
void crc()

Mody University

for(e=0;e<N;e++)
cs[e]=t[e];
do
{

if(cs[0]=='1')
xor();
for(c=0;c<N-1;c++)
cs[c]=cs[c+1];
cs[c]=t[e++];
}while(e<=a+N-1);
}

35

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

OUTPUT-

Mody University

36

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

PROGRAM-13
AIM : Introduction to socket programming.
SOCKET : A socket is an endpoint of an inter process communication flow across a
computer
network. Communication between computers is based on the internet
protocol(IP), therefore most network socket are internet socket.

Concatenation of ip address and porto Connection oriented : phone number and receiver.
o Connection less : address and receiver
A socket pair (local IP address, local port, foreign ip port, foreign port)
uniquely identifies a communication.
The socket 161.25.19.8.1625 refers to port 1625 on host 161.25.19.8

SOCKET ADDRESS : A socket address is the combination of an ip address and a port


number, much like one end of a telephone connection is the combination of a phone
number and a particular extension based on this address, internet socket deliver incoming
data packets to the appropriate application process or thread:Example : 161.25.19.8.1625
Here ip address is : 161.25.19.8
Here port address is : 1625
It is the combination of ip address and ip port.

Mody University
SOCKET ARCHITECTURE-

37

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

int s = socket(domain, type, protocol);


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

Various header files used1. <stdlib.h> :-

Full fro of stdli .h : standard library definitions.


Dis riptio : stdlib.h is the header of the general purpose standard library of C
programming language which includes functions involving memory allocation,
process control, conversions.
2. <stdio.h> :-

Full for of stdio.h : standard buffered input/output.


Dis riptio : It provides general file operation support and supplies functions
with narrow input/output capabilities.

Mody University

3. <errno.h> :-

Full fro of err o.h : system error numbers


Dis riptio : It is having macro reporting error conditions. It points out the errors
in line.
4. <string.h> :-

Full fro of stri g.h : standard library function


Dis riptio : This header file defines several functions to manipulate C strings and
arrays.
5. <sys/socket.h> :-

Full for of sys/so ket.h : Internet Protocol family


Dis riptio : It defines the macro with distinct integer values for us as the valid
values.

38

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

6. <sys/types.h> :-

Full fro of sys/types.h : data types


Dis riptio : Contains data definition. It is usually included before other socket
related header file.
7. <netinet/in.h>

Full for of eti et/i .h :


Discription : Contain constants and structure defined by intent system. It also
defines prototypes, macro, variables and sock_adder in structure to use with
internal domain socket.
8. <unistd.h>

Full for of u istd.h : standard symbolic constants and types


Dis riptio : It defines miscellaneous symbolic constants and type and declare
miscellaneous function.

Mody University

9. <arpa/inet.h>

Full for of arpa/i et.h : definitions for internet operations.


Dis riptio : It has functions for manipulating numeric ip address. It defines
prototype for those network library routines that convert internet address and
dotted-decimal notation.

Memset
It fills memory with constant bytes. It fills the first n bytes of the memory area.
Example:#include<stdio.h>
#include<string.h>
void main()
{
char ste[]=it s my work;
memset(ste,*,2);
puts(ste);
}
Output:** s my work
39

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

PREDEFINED FUNCTIONS1. htons():Converts the unsigned short int host short from host byte order to network
byte order.

2. bind():Used on the server side and associates a socket with a socket address structure.

3. socket():Creates a new socket of a certain socket type, identified by an integer number.

4. listen():Used on the server side and causes a bound TCP socket to enter listing state.

5. connect():Used on the client side and assigns a free local port number to a socket.
6. accept():Used on the server side. It accepts an incoming receiver. This function is used
to create a new TCP connection from the remote client and create a new
socket associated with the socket address pair of this connection.

Mody University

7. recvfrom():Used for receiving data from remote socket.

8. sendto():Used for sending data to a remote socket.

9. sizeof():Used to calculate the size of any data type. It gives result as the number of
bytes.

VARIOUS EDITORS USED IN SOCKET PROGRAMMINGThere are three types of editors-

1. vi editor:It is a screen oriented text editor generally created for the UNIX operating
system. It is the most widely used text editor after gedit. Language supported
within these program is described by single UNIX specification

40

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

$viclient_filename.c and then press enter.


Press insert key and then write code
To save a file after typing press Esc and press :wq and then press enter.

2. gedit:It is the default text editor of the gnome desktop environment and part of
the gnome core application. It is free and open source software which is
designed as a general purpose text editor. It includes tools for editing source
code structured text such as markup language.
$gedit filename.c and then press enter
Press insert key and then write code
To save a file after typing press Esc and press :wq and then press enter.

3. Pico editor:Pine composer is a text editor for UNIX and UNIX based computer system.
It does not support working with various files simultaneously and cannot
perform a find and replace across multiple files. It also cannot copy text from
one file to another file.
$pico filename.c and then press enter
Press insert key and then write code
To save a file after typing press Esc and press :wq and then press enter.

Mody University

41

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

Experiment 14
AIM : A simple demonstration of sending a UDP packet containing the string Hello
World to address 127.0.0.1, port 8500.

STEP 1 : Open the terminal.


STEP 2 : Type vi clientaratrika.c and then press the Enter key.
STEP 3 : Now a screen will appear. It will be in non-editable mode unless we press
the Insert key.
STEP 4 : Type the code of the client.
Client#include<stdlib.h>
#include<stdio.h>
#include<errno.h>

Mody University

#include<string.h>

#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<unistd.h>
#include<arpa/inet.h>
int main()
{
struct sockaddr_in sa;
int bytes_sent;
char buffer[200]= Hello World ;
int sock=socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
42

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

if(-1==sock)
printf(Error Creating Socket.);
memset(&sa,0,sizeof(sa));
sa.sin_family=AF_INET;
sa.sin_addr.s_addr=inet_addr=inet_addr(127.0.0.1);
sa.sin_port=htons(8500);
bytes_sent=sendto(sock,buffer,strlen(buffer),0,(structsockaddr *)&sa,sizeof(sa));
if(bytes_sent<0)
printf(Error sending packet : \n);
close(sock);
return(0);
}

Mody University

STEP 5 : Press Escape key from the keyboard and type :wq . Then press the Enter key.
STEP 6 : Type vi serveraratrika.c and press the Enter key.
STEP 7 : Now, a new screen will appear. It is in non-editable mode until and unless
we press the Enter key.
STEP 8 : Type the code of the server.
Server#include<stdlib.h>
#include<stdio.h>
#include<errno.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>

43

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

#include<netinet/in.h>
#include<unistd.h>
#include<arpa/inet.h>
int main()
{
struct sockaddr_in sa;
char buffer[1024];
ssize_t recsize;
socklen_t fromlen;
int sock=socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
memset(&sa,0,sizeof(sa));
sa.sin_family=AF_INET;

Mody University

sa.sin_addr.s_addr=inet_addr=INADDR_ANY;
sa.sin_port=htons(8500);
fromlen=sizeof(sa);

if(-1==bind(sock,(structsockaddr *)&sa,sizeof(sa)));
printf(Error bind failed);
for(;;)
{
printf(Recv test.\n);
recsize=recvfrom(sock,(void *)buffer,sizeof(buffer),0,(structsockaddr
*)&sa,&fromlen);
if(recsize<0)
printf(strderr);

44

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

}
printf(Recsize : %d\n,recsize);
sleep(1);
printf(Datagram : %s\n,buffer);
}
STEP 9 : Press Escape key from the keyboard and type :wq. Then press the Enter key.
STEP 10 : In the terminal write down gcc o clientaratrika.c.

STEP 11 : In the terminal write down gcc o serveraratrika.c.


STEP 12 : If the above two statements return shell prompt, then it means there is no
error. Otherwise first resolve the error.
STEP 13 : Close all the windows.
STEP 14 : On the 1st terminal, type ./serveraratrika and press the Enter key.

Mody University

STEP 15 : On the 2nd terminal, type ./clientaratrika and press the Enter key.
STEP 16 : The output is shown below-

45

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

PROGRAM-15
AIM : A simple demonstration of sending a UDP packet containing a number to address
127.0.0.1, port 8500 and receiving a square of it.
STEP 1 : Open the terminal.
STEP 2 : Type vi bclient2.c and then press the Enter key.
STEP 3 : Now a screen will appear. It will be in non-editable mode unless we press the
Insert key.
STEP 4 : Type the code of the client.
Client#include<stdlib.h>
#include<stdio.h>
#include<errno.h>

Mody University

#include<string.h>

#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<unistd.h>
#include<arpa/inet.h>
int main()
{
struct sockaddr_in sa;
int bytes_sent;
char buffer[200],newbuffer[1024];
46

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

ssize_t recsize;
socklen_t fromlen;
int sock=socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
if(-1==sock)
printf("Error creating socket..");
memset(&sa,0,sizeof(sa));
sa.sin_family=AF_INET;
sa.sin_addr.s_addr=inet_addr("127.0.0.1");
sa.sin_port=htons(8500);
fromlen=sizeof(sa);
printf("Enter the number : ");

Mody University

gets(buffer);

bytes_sent=sendto(sock,buffer,strlen(buffer),0,(struct sockaddr *)&sa,sizeof(sa));


if(bytes_sent<0)
printf("Error sending packet..:\n");
recsize=recvfrom(sock,(void *)newbuffer,sizeof(newbuffer),0,(struct sockaddr
*)&sa,&fromlen);
printf("%s",newbuffer);
close(sock);
return(0);
}

47

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

STEP 5 : Press Escape key from the keyboard and type :wq. Then press the Enter key.
STEP 6 : Type vi bserver2.c and press the Enter key.
STEP 7 : Now, a new screen will appear. It is in non-editable mode until and unless we
press the Enter key.
STEP 8 : Type the code of the server.

Server#include<stdlib.h>
#include<stdio.h>
#include<errno.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>

Mody University

#include<netinet/in.h>
#include<unistd.h>
#include<arpa/inet.h>
int main(void)
{

struct sockaddr_in sa;


char buffer[1024],newbuffer[1024];
int n,square,bytes_sent;
ssize_t recsize;
socklen_t fromlen;
int sock=socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
48

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

memset(&sa,0,sizeof(sa));
sa.sin_family=AF_INET;
sa.sin_addr.s_addr=INADDR_ANY;
sa.sin_port=htons(8500);
fromlen=sizeof(sa);
if(-1==bind(sock,(struct sockaddr *)&sa,sizeof(sa)));
printf("Error bind failed..");
for(;;)
{
printf("Recv test....\n");
recsize=recvfrom(sock,(void *)buffer,sizeof(buffer),0,(struct sockaddr

Mody University
*)&sa,&fromlen);

if(recsize<0)

printf("stderr");
}
printf("Recsize : %d\n",recsize);
sleep(1);
printf("Datagram : %s\n",buffer);
n=atoi(buffer);
square=n*n;
sprintf(newbuffer,"%d",square);
printf("%s",newbuffer);

49

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

bytes_sent=sendto(sock,newbuffer,strlen(newbuffer),0,(struct sockaddr
*)&sa,sizeof(sa));
}

STEP 9 : Press Escape key from the keyboard and type :wq. Then press the Enter key.
STEP 10 : In the terminal write down gcc o bcient2.c.

STEP 11 : In the terminal write down gcc o bserver2.c.


STEP 12 : If the above two statements return shell prompt, then it means there is no
error. Otherwise, first resolve the error.
STEP 13 : Close all the windows.
STEP 14 : On the 1st terminal, type ./bandana1 and press the Enter key.
STEP 15 : On the 2nd terminal, type ./bandana and press the Enter key.
STEP 16 : The output is shown below-

Mody University

50

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

PROGRAM-16
AIM : A simple demonstration of sending a TCP packet containing a string in lower case
to address 127.0.0.1, port 7891 and receiving the same string with the characters in
uppercase.
STEP 1 : Open the terminal.
STEP 2 : Type vi client.c and then press the Enter key.
STEP 3 : Now a screen will appear. It will be in non-editable mode unless we press the
Insert key.
STEP 4 : Type the code of the client.
Client#include<stdio.h>
#include<sys/socket.h>

Mody University

#include<netinet/in.h>
#include<string.h>
int main()
{

int clientSocket,portNum,nBytes;
char buffer[1024];
struct sockaddr_in serverAddr;
socklen_t addr_size;
clientSocket=socket(PF_INET,SOCK_STREAM,0);
portNum=7891;
serverAddr.sin_family=AF_INET;
serverAddr.sin_port=htons(portNum);
serverAddr.sin_addr.s_addr=inet_addr("127.0.0.1");
memset(serverAddr.sin_zero,'\0',sizeof serverAddr.sin_zero);

51

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

addr_size=sizeof serverAddr;
connect(clientSocket,(struct sockaddr *)&serverAddr,addr_size);
while(1)
{
printf("Type a sentence to send to server : \n");
fgets(buffer,1024,stdin);
printf("You typed : %s",buffer);
nBytes=strlen(buffer)+1;
send(clientSocket,buffer,nBytes,0);
recv(clientSocket,buffer,1024,0);
printf("\nReceived from serner : %s\n\n",buffer);
}
return 0;
}

Mody University

STEP 5 : Press Escape key from the keyboard and type :wq. Then press the Enter key.
STEP 6 : Type vi server.c and press the Enter key.
STEP 7 : Now, a new screen will appear. It is in non-editable mode until and unless we
press the Enter key.
STEP 8 : Type the code of the server.

Server#include<stdio.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>
#include<stdlib.h>
int main()
{
52

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

int welcomeSocket,newSocket,portNum,clientLen,nBytes;
char buffer[1024];
struct sockaddr_in serverAddr;
struct sockaddr_storage serverStorage;
socklen_t addr_size;
int i;
welcomeSocket=socket(PF_INET,SOCK_STREAM,0);
portNum=7891;
serverAddr.sin_family=AF_INET;
serverAddr.sin_port=htons(portNum);
serverAddr.sin_addr.s_addr=inet_addr("127.0.0.1");
memset(serverAddr.sin_zero,'\0',sizeof serverAddr.sin_zero);
bind(welcomeSocket,(struct sockaddr *)&serverAddr,sizeof(serverAddr));
if(listen(welcomeSocket,5)==0)

Mody University
printf("Listening..\n");

else

printf("Error!!\n");
addr_size=sizeof serverStorage;
while(1)
{
newSocket=accept(welcomeSocket,(struct sockaddr *)&serverStorage
,&addr_size);
if(!fork())
{
nBytes=-1;
while(nBytes!=0)
{
nBytes=recv(newSocket,buffer,1024,0);
for(i=0;i<nBytes-1;i++)
53

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

buffer[i]=toupper(buffer[i]);
send(newSocket,buffer,nBytes,0);
}
close(newSocket);
exit(0);
}
else
close(newSocket);
}
return(0);
}
STEP 9 : Press Escape key from the keyboard and type :wq. Then press the Enter key.
STEP 10 : In the terminal write down gcc o cclient client.c.

STEP 11 : In the terminal write down gcc o sserver server.c.

Mody University

STEP 12 : If the above two statements return shell prompt, then it means there is no
error. Otherwise, first resolve the error.
STEP 13 : Close all the windows.
STEP 14 : On the 1st terminal, type ./cclient and press the Enter key.
STEP 15 : On the 2nd terminal, type ./sserver and press the Enter key.
STEP 16 : The output is shown below-

54

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

PROGRAM-17
AIM : A simple demonstration of a chat application using TCP.
STEP 1 : Open the terminal.
STEP 2 : Type vi client.c and then press the Enter key.
STEP 3 : Now a screen will appear. It will be in non-editable mode unless we press the
Insert key.
STEP 4 : Type the code of the client.
Client#include<stdio.h>
#include<string.h>
#include<sys/socket.h>
#include<arpa/inet.h>
int main(int argc, char *argv[])

Mody University

int sock;
struct sockaddr_in server;
char message[1000],server_reply[2000];

sock = socket(AF_INET,SOCK_STREAM,0);
if(sock == -1)
printf("could not create socket");
puts("Socket created");
server.sin_addr.s_addr = inet_addr("127.0.01");
server.sin_family = AF_INET;
server.sin_port = htons(8888);
if(connect(sock ,(struct sockaddr *)&server , sizeof(server))<0)
{
55

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

perror("connect failed.Error");
return 1;
}
puts("connected\n");
while(1)
{
printf("Enter message: ");
scanf("%s",message);
if(send(sock, message, strlen(message),0)<0)
{
puts("Send failed");
return 1;
}
if(recv(sock ,server_reply, 2000,0)<0)

Mody University
{

puts("recv failed");
break;

}
puts("Server reply : ");
puts(server_reply);
}
close(sock);
return 0;
}
STEP 5 : Press Escape key from the keyboard and type :wq. Then press the Enter key.
STEP 6 : Type vi server.c and press the Enter key.
STEP 7 : Now, a new screen will appear. It is in non-editable mode until and unless we
press the Enter key.
56

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

STEP 8 : Type the code of the server.

Server#include<stdio.h>
#include<string.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<unistd.h>
int main(int argc, char *argv[])
{
int socket_desc,client_sock,c,read_size;
struct sockaddr_in server , client;
char client_message[2000];
socket_desc= socket(AF_INET, SOCK_STREAM,0);
if(socket_desc == -1)

Mody University
printf("Could not create socket");

puts("Socket Created");
server.sin_family= AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(8888);
if(bind(socket_desc,(struct sockaddr *)&server , sizeof(server))<0)
{
perror("bind failed.Error");
return 1;
}
puts("bind done");
listen(socket_desc,3);
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
57

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

client_sock = accept(socket_desc,(struct sockaddr*)&client,(socklen_t*)&c);


if(client_sock<0)
{
perror("accept failed");
return 1;
}
puts("Connection accepted");
while((read_size = recv(client_sock,client_message,2000,0))>0)
write(client_sock,client_message,strlen(client_message));
if(read_size == 0)
{
puts("Client disconnected");
fflush(stdout);
}

Mody University

else if(read_size == -1)

perror("recv failed");

return 0;
}
STEP 9 : Press Escape key from the keyboard and type :wq. Then press the Enter key.
STEP 10 : In the terminal write down gcc o cli client.c.

STEP 11 : In the terminal write down gcc o serv server.c.


STEP 12 : If the above two statements return shell prompt, then it means there is no
error. Otherwise, first resolve the error.
STEP 13 : Close all the windows.
STEP 14 : On the 1st terminal, type ./cli and press the Enter key.
STEP 15 : On the 2nd terminal, type ./serv and press the Enter key.
STEP 16 : The output is shown below58

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

Mody University

59

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

PROGRAM-18
AIM : A simple demonstration of client-server application for date and time using TCP
protocol in which a client application initiates a request to a server application for
current date and time. The server gives response with the correct date and time to
the client.
STEP 1 : Open the terminal.
STEP 2 : Type vi clientara.c and then press the Enter key.
STEP 3 : Now a screen will appear. It will be in non-editable mode unless we press the
Insert key.
STEP 4 : Type the code of the client.
Client#include<netinet/in.h>

Mody University

#include<sys/socket.h>
#include<stdio.h>

#include<stdlib.h>
#include<string.h>
main()
{
struct sockaddr_in sa,cli;
int n,sockfd;
int len;
char buff[100];
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd<0)
{
printf("Error in socket!!");

60

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

exit(0);
}
else
printf("\nSocket is opened..");
bzero(&sa,sizeof(sa));
sa.sin_family=AF_INET;
sa.sin_port=htons(5600);
if(connect(sockfd,(struct sockaddr*)&sa,sizeof(sa))<0)
{
printf("\nError in connection failed!!");
exit(0);
}
else
printf("\nConnected successfully..");

Mody University

if(n=read(sockfd,buff,sizeof(buff))<0)
{
printf("\nError in reading!!");
exit(0);
}
else

printf("\nMessage read %s",buff);


}
STEP 5 : Press Escape key from the keyboard and type :wq. Then press the Enter key.
STEP 6 : Type vi serverara.c and press the Enter key.
STEP 7 : Now, a new screen will appear. It is in non-editable mode until and unless we
press the Enter key.
STEP 8 : Type the code of the server.
61

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

Server#include<netinet/in.h>
#include<sys/socket.h>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
struct sockaddr_in sa;
struct sockaddr_in cli;
int sockfd,conntfd;
int len,ch;
char str[100];

Mody University

time_t tick;

sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd<0)
{
printf("Error in socket!!");
exit(0);
}
else
printf("\nSocket opened..");
bzero(&sa,sizeof(sa));
sa.sin_port=htons(5600);
sa.sin_addr.s_addr=htons(0);
if(bind(sockfd,(struct sockaddr*)&sa,sizeof(sa))<0)
printf("\nError in binding!!");
62

Aratrika

130125

CSE(IIIrd Year)

1-08-2015

else
printf("\nBinded successfully..");
listen(sockfd,50);
for(;;)
{
len=sizeof(ch);
conntfd=accept(sockfd,(struct sockaddr*)&cli,&len);
printf("\nAccepted..");
tick=time(NULL);
snprintf(str,sizeof(str),"%s",ctime(&tick));
printf("%s",str);
write(conntfd,str,100);
}
}

Mody University

STEP 9 : Press Escape key from the keyboard and type :wq. Then press the Enter key.
STEP 10 : In the terminal write down gcc o clie clientara.c.

STEP 11 : In the terminal write down gcc o serv serverara.c.


STEP 12 : If the above two statements return shell prompt, then it means there is no
error. Otherwise, first resolve the error.
STEP 13 : Close all the windows.
STEP 14 : On the 1st terminal, type ./cli and press the Enter key.
STEP 15 : On the 2nd terminal, type ./serv and press the Enter key.
STEP 16 : The output is shown below-

63

S-ar putea să vă placă și