You are on page 1of 52

NETWORK LAB MANUAL

Network Lab CS2305

List of Experiments (as per syllabus):

9
10
10
11
12

12

15

18

21

3
3

24
27

30

33

36

39

42

45

k/

e.t

ub

et

cs

Cumulative No.
Of periods

://

No. of
Periods

tp

Name of the Experiment


CYCLE I
Basic unix commands and introduction to
vi editor.
Introduction to socket programming.
Socket Creation & Binding the socket
Develop a server using socket with listen,
accept and send/receive system calls
Develop a Client that contacts a given
DNS Server to resolve a given host name.
Develop a Client Server application for
chat.
Write a Client to download a file from a
HTTP Server.
Study of Network Simulators like
NS2/Glomosim / OPNET.
Introduction to Ns2
Simple programs using NS2
Model Exam I
CYCLE II
Simulation of protocols such as
ARP/RARP
Write a program that takes a binary file as
input and performs bit stuffing and CRC
Computation.
Develop an application for transferring
files over RS232.
Simulation of Sliding-Window protocol.
Simulation of BGP / OSPF routing
protocol.
Model Exam II

ht

Expt.
No

Contemporary Experiments (beyond syllabus):


Expt.
No

Name of the Experiment

No. of
Periods

Cumulative
No.
Of periods

Study of LAN switch (CISCO 2950)

49

Study of Routers (CISCO 2600)

53

Study of crypt tools (Crypt tool, Ethereal)

57

Study of Wireless LAN devices

60

http://csetube.tk/

Network Lab CS2305


Mini Projects:

Simulation of congestion control in TCP using NS-2


Simulation of Traffic Engineering using NS-2
Simulation of Policy based networks using NS-2

ht

tp

://

cs

et

ub

e.t

k/

Reference web sites:


http://www.linuxhq.org
http://www1.us.elsevierhealth.com
www.ipv6.org
www.dbaseiv.net/socketsfaq.html
www.dbaseiv.net/sockets/beej/net/
www.protocols.com/pbook/tcpip.html
http://www.ecst.csuchico.edu/~chafey/prog/sockets/sinfo1.html
http://www.uwo.ca/its/doc/courses/notes/socket/
http://www.tldp.org/guides.html
http://www.linuxgazette.com/issue47/bueno.html
ftp://gaia.cs.umass.edu/cs653_1996/sock.ps
http://www-net.cs.umass.edu/ntu_socket/
http://www.geocities.com/kollurihari/hari/harilinks.html
http://www.fortunecity.com/skyscraper/arpanet/6/cc.htm
http://www.cs.buffalo.edu/~milun/unix.programming.html
http://www.coding-zone.co.uk/cpp/articles/140101networkprogrammingc.shtml
http://beej.us/guide/bgnet/
http://orca.st.usm.edu/~seyfarth/network_pgm/homework1.html
http://www.cs.rpi.edu/courses/netprog/

http://csetube.tk/

Network Lab CS2305

1. Introduction to VI Editor
The VI editor is a screen-based editor used by many Unix users. The VI editor has powerful
features to aid programmers, but many beginning users avoid using VI because the different
features overwhelm them. This tutorial is written to help beginning users get accustomed to using
the VI editor, but also contains sections relevant to regular users of VI as well. Examples are
provided, and the best way to learn is to try these examples, and think of your own examples as
well... There's no better way than to experience things yourself.
1.1 Starting the VI Editor
The VI editor lets a user create new files or edit existing files. The command to start the VI editor
is vi, followed by the filename. For example to edit a file called temporary, you would type vi
temporary and then return. You can start VI without a filename, but when you want to save your
work, you will have to tell VI which filename to save it into later.
When you start VI for the first time, you will see a screen filled with tildes (A tilde looks like this:
~) on the left side of the screen. Any blank lines beyond the end of the file are shown this way. At
the bottom of your screen, the filename should be shown, if you specified an existing file, and the
size of the file will be shown as well, like this:

tp

://

cs

et

ub

e.t

k/

"filename" 21 lines, 385 characters


If the file you specified does not exist, then it will tell you that it is a new file, like this:
"newfile" [New file]
If you started VI without a filename, the bottom line of the screen will just be blank when VI starts.
If the screen does not show you these expected results, your terminal type may be set wrong. Just
type : q and return to get out of VI.

ht

1.2 The Two Modes of VI


The first thing most users learn about the VI editor is that it has two modes: command and insert.
The command mode allows the entry of commands to manipulate text. These commands are
usually one or two characters long, and can be entered with few keystrokes. The insert mode puts
anything typed on the keyboard into the current file.
VI starts out in command mode. There are several commands that put the VI editor into insert
mode. The most commonly used commands to get into insert mode are a and i. These two
commands are described below. Once you are in insert mode, you get out of it by hitting the
escape key. If your terminal does not have an escape key, ^[ should work (control-[). You can hit
escape two times in a row and VI would definitely be in command mode. Hitting escape while you
are already in command mode doesn't take the editor out of command mode. It may beep to tell you
that you are already in that mode.
2. How to Type Commands in Command Mode
The command mode commands are normally in this format: (Optional arguments are given in the
brackets)
[count] command [where]

Most commands are one character long, including those which use control characters. The
commands described in this section are those which are used most commonly the VI editor.

http://csetube.tk/

Network Lab CS2305


The count is entered as a number beginning with any character from 1 to 9. For example, the x
command deletes a character under the cursor. If you type 23x while in command mode, it will
delete 23 characters. Some commands use an optional where parameter, where you can specify
how many lines or how much of the document the command affects, the where parameter can also
be any command that moves the cursor.
3. Word and Character Searching
The VI editor has two kinds of searches: string and character. For a string search, the / and ?
commands are used. When you start these commands, the command just typed will be shown on
the bottom line, where you type the particular string to look for. These two commands differ only
in the direction where the search takes place. The / command searches forwards (downwards) in
the file, while the? command searches backwards (upwards) in the file. The n and N commands
repeat the previous search command in the same or opposite direction, respectively. Some
characters have special meanings to VI, so they must be preceded by a backslash (\) to be included
as part of the search expression.
Special characters:

ub

e.t

k/

Beginning of the line. (At the beginning of a search expression.)


Matches a single character.
Matches zero or more of the previous character.
End of the line (At the end of the search expression.)
Starts a set of matching, or non-matching expressions.
For example: /f[iae]t matches either of these: fit fat fet In this form, it matches anything
except these: /a[^bcd] will not match any of these, but anything with an a and another letter:
ab ac ad
Put in an expression escaped with the backslash to find the ending or beginning of a word.
For example: /\<the\> should find only word the, but not words like these: there and other.
The character search searches within one line to find a character entered after the
command. The f and F commands search for a character on the current line only. f searches
forwards and F searches backwards and the cursor moves to the position of the found
character.

>

tp

ht

<

://

cs

et

^
.
*
$
[

The t and T commands search for a character on the current line only, but for t, the cursor moves
to the position before the character, and T searches the line backwards to the position after the
character.
These two sets of commands can be repeated using the ; or , command, where ; repeats the last
character search command in the same direction, while , repeats the command in the reverse
direction.
4. Recovering Your Work When Something Goes Wrong with Your Terminal
The VI editor edits a temporary copy of your file, and after the editing is complete, or when you
tell it to save, it puts the contents of the temporary copy into the original file. If something goes
wrong while you are editing your file, the VI editor will attempt to save whatever work you had in
progress, and store it for later recovery. (Note: If VI dies while you were working on any file, it
sends you an email message on how to recover it. The -r option stands for recovery. If you were
editing the file vital info, and you accidentally got logged out, then the -r option of the 'vi' editor

http://csetube.tk/

Network Lab CS2305


should help. The command would look somewhat like this: vi -r vital info After using the -r
option once, though, you MUST save what you have recovered to the actual file... The -r option
only works once per failed VI session.
5. Basic Functions
Key combination

Function

or

or <Backspace> Cursor left

or

or <Spacebar>

or

Cursor up.

or

Cursor down.

Cursor right.

Cursor left one word.

Cursor right one word.

Cursor up one paragraph.

Cursor down one paragraph.


Cursor to line starts.

Cursor to line end.

gg

Cursor to first line.

Cursor to last line.

cs

et

ub

e.t

k/

Start insert mode.

ht

tp

://

Get out of current mode.

Insert a blank line below the current line and then start insert
mode.

Insert a blank line above the current line and then start insert
mode.

Append (start insert mode after the current character).

Replace (start insert mode with overwrite).

:wq

Save (write) and quit.

:q

Quit.

:q!

Quit forced (without checking whether a save is required).

Delete (delete under cursor and copy to register).

Backspace (delete left of cursor and copy to register).

dd

Delete line (and copy to register).

:j!

Join line (remove newline at end of current line).

Undo.

Ctrl-R

Redo.

de

Delete to word end (and copy to register).

http://csetube.tk/

Network Lab CS2305


db

Delete to word start (and copy to register).

d$

Delete to line end (and copy to register).

d^

Delete to line beginning (and copy to register).

dd

Delete current line (and copy to register).

2dd

Delete two lines (and copy to register).

Paste clipboard (insert register).

Ctrl-G

Show cursor position.

5G

Cursor to line five.

Cursor to last line.

/search-string

Search forwards for search-string.

:-1,$s/search-string /replacestring /gc

Search and replace with confirmation starting at current line.

:,$s/\<search-string
\>/replace-string /gc

Search and replace whole words.

Search backwards for search-string.

:5,20w

filename

:5,$w!

filename

:r

filename

k/

cs

://

filename

Save to file filename.


Save lines 5 through 20 to file filename (use Ctrl-G to get line
numbers if needed).

ht

:w

Search and replace whole file without confirmation.

tp

:%s/search-string /replacestring /g

Search and replace in lines 8 through 22 without confirmation.

et

:8,22s/search-string /replacestring /g

Search and replace with confirmation starting at line below


cursor.

e.t

:,$s/search-string /replacestring /gc

ub

?search-string

Force save lines 5 through to last line to file filename.


Insert file filename.

Visual mode (start highlighting).

Copy highlighted text to register.

Delete highlighted text (and copy to register).

Paste clipboard (insert register).

Press v, then move cursor

Search and replace within

down a few lines, then,

highlighted text.

:help

Reference manual (open new window with help screen inside-probably the most important command here!).

:new

Open new blank window.

:split

filename

Open new window with filename.

:q

Close current window.

:qa

Close all windows.

Ctrl-W j

Move cursor to window below.

http://csetube.tk/

Network Lab CS2305


Ctrl-W k

Move cursor to window above.

Ctrl-W -

Make window smaller.

Ctrl-W +

Make window larger.

Introduction to Socket Programming


6.1 Socket Creation
A socket is an endpoint for communication. Two processes can communicate by creating sockets
and sending messages between them. There are a variety of different types of sockets, differing in
the way the address space of the sockets is defined and the kind of communication that is allowed
between sockets.

e.t

k/

A socket type is uniquely determined by a <domain, type, protocol> triple. In order for a remote
socket to be reached, it must be possible to assign a name to it. The form that this name assumes is
determined by the communication domain or address family to which the socket belongs. There is
also an abstract type or style of communication associated with each socket. This gives the
semantics of communication for that socket. Finally, there is a specific protocol that is used with
the socket.

et

ub

A socket can be created with the socket()system call by specifying the desired address family,
socket type, and protocol.

tp

://

cs

socket_descriptor = socket (domain, type, protocol)


int socket_descriptor, domain, type, protocol;

ht

This call returns a small positive integer called a socket descriptor that can be used as a parameter
to reference the socket in subsequent system calls. Socket descriptors are similar to file descriptors
returned by the open() system call. Each open() or socket() call will return the smallest
unused integer. Thus a given number denotes either an open file, a socket, or neither (but never
both). Socket and file descriptors may be used interchangeably in many system calls. For example,
the close() system call is used to destroy sockets.

6.2 Domains
The communication domain or address family to which a socket belongs specifies a certain address
format. All later operations on a socket will interpret the supplied address according to this
specified format. The various address formats are defined as manifest constants in the file
<sys/socket.h>. Examples are AF_UNIX (UNIX path names), AF_INET (DARPA Internet
addresses), and AF_OSI (as specified by the international standards for Open Systems
Interconnection). AF_UNIX and AF_INET are the most important address families. The general
form of an address is represented by the sockaddr structure defined in <sys/socket.h>.
struct sockaddr {
short sa_family; /* address family */

http://csetube.tk/

Network Lab CS2305

char sa_data[14]; /* up to 14 bytes of direct address */

Note: You must include <sys/types.h> before <sys/socket.h>.


When a socket is created, it does not initially have an address associated with it. However, since it
is impossible for a remote host or process to find a socket unless it has an address, it is important to
bind an address to the socket. A socket does not have a name until an address is explicitly assigned
to it with the bind() system call.
status = bind(sock, address, addrlen)
int status; /* status returns 0 for success, -1 otherwise */
int sock; /* descriptor returned by socket() */
struct sockaddr *address;
int addrlen; /* size of address (in bytes) */
This call fails if the address is already in use, the address is not in the correct format for the address
family specified, or the socket already has an address bound to it.

ht

tp

://

cs

et

ub

e.t

k/

6.2.1 UNIX domain


In the UNIX domain, a socket is addressed by a UNIX path name that may be up to 108 characters
long. The binding of a path name to a socket results in the allocation of an inode and an entry of
the path name into the file system. This necessitates removing the path name from the file system
(using unlink() system call) when the socket is closed. The created file is only used to provide a
name for the socket and does not play a role in the actual transfer of data. When using sockets in
the UNIX domain, it is advisable to only use path names for directories (/tmp) directly mounted on
the local disk. The UNIX domain only allows interprocess communication for processes working
on the same machine. The structure sockaddr_un used to define the UNIX address format can be
found in <sys/un.h>.
struct sockaddr_un {
short sun_family; /* AF_UNIX */
char sun_path[108-4]; /* path name */
}
Note:When specifying the length of UNIX domain addresses for system calls, use sizeof(struct
sockaddr_un). Using the size of sockaddr will cause the call to fail.
6.2.2 Internet domain
In the DARPA Internet domain, addresses consist of two parts. First part is a host address
(consisting of a network number and a host number) and the later is a port number (also known as
a transport suffix). This host address allows processes on different machines to communicate. The
port number is like a mail box that allows multiple addresses on the same host. The structure
sockaddr_in describing an address in the Internet domain is defined in the file <netinet/in.h>.
struct sockaddr_in {
short sin_family; /* AF_INET */
u_short sin_port; /* port number */
struct in_addr sin_addr; /* see struct below */
char sin_zero[8]; /* not used */
}

http://csetube.tk/

Network Lab CS2305


struct in_addr {
union {
struct { u_char s_b1,s_b2,s_b3,s_b4; } S_un_b;
struct { u_short s_w1,s_w2; } S_un_w;
u_long S_addr;
} S_un;
#define s_addr S_un.S_addr /* can be used for most tcp& ip code */
}
It is often useful to bind a specific service to a "well-known" port, enabling remote processes to
locate the required server easily. Examples of well-known ports are 79 for the "finger" service and
513 for remote login. The kernel reserves the first 1024 port numbers for its own use. There is a
network services database in /etc/services that can be queried by using the system calls
getservbyname() and getservbyport().Each of these routines returns a pointer to the structure
servent defined in <netdb.h>. If the port field in the address parameter to bind is specified as zero,
the system will assign an unused port number. The assigned port number can be discovered by
calling getsockname(). In the Internet domain, UDP and TCP can use the same port numbers.
There is no confusion in naming because ports bound to sockets with different protocols cannot
communicate. Ports numbered less than 1024 are "reserved"--only processes running as superuser
may bind to them.

ht

tp

://

cs

et

ub

e.t

k/

Internet host addresses are specified in four bytes (32 bits). They are typically represented by a
standard `.' notation, a.b.c.d. The bytes of the address are represented by decimal integers,
separated by periods, and ordered from high order to low order. This ordering is called network
order and is the order in which addresses are transmitted over the network. For example, the
Internet address for the host garfield.cs.wisc.edu is 128.105.1.3 which corresponds to the unsigned
integer 80690103 in hex, or 2154365187 in decimal. Some hosts (such as the VAX), however,
have a host order for these integer values that reverses the order of the bytes. When a word is
transmitted from such a host (or when a C program treats a word as a sequence of bytes), the loworder byte is transmitted first (has the lowest address). Thus, it is necessary to reverse the bytes of
an address, stored in an integer, before transmitting it. The system routines htonl() and ntohl()
are provided to convert long (32-bit) integers from host to network order and vice versa. Similarly,
htos() and ntohs() swap the bytes of short (16-bit) integers, such as port numbers. System calls
that return or demand Internet addresses and port numbers (such as gethostbyname() or bind(),
which is described above), deal entirely in network order, so you normally don't have to worry
about all this. However, if you want to print out one of these values or read it in, you will have to
convert from/to host order.
An Internet host address can be decomposed into two parts, a network number and a local address.
There are three formats for Internet addresses (see inet(3N)), each of which partitions the 32 bits
differently. "Class A" addresses have a one-byte network number (the high order byte), and a 3byte host number. "Class B" addresses have two bytes each of network and host number, and "class
C" networks have three bytes of network number and one byte of host number. (Thus a class C
network can have at most 256 hosts). The high-order bits of an address determine its class:
Addresses starting with a zero are class A addresses, addresses starting with 10 are class B, and
addresses starting with 110 are class C. Thus there can be at most 128 class A networks and at
most 214 = 16,384 class B networks.
The system calls gethostbyaddr() and gethostbyname() can be used to look up the host address
(see gethostent(3N) and host(5)). Each of these calls returns a pointer to the structure hostent

http://csetube.tk/

Network Lab CS2305


defined in <netdb.h>. Host addresses are returned in network order, the proper format for a call to
bind(). The system routine memcpy() can be used to copy the host address into the sockaddr_in
structure. If a zero host address is given (the wildcard value INADDR_ANY can be used) in the call to
bind(), the local host address will be automatically supplied. Another reason for using
INADDR_ANY is that a host may have multiple Internet addresses; addresses specified this way will
match any incoming messages with a valid Internet address.
7. Styles of Communication
The type field of the socket() call specifies the abstract "style of communication" to be used with
that socket. These types are defined as manifest constants in <sys/socket.h>. The following
types are currently defined: SOCK_STREAM (stream), SOCK_DGRAM (datagram), SOCK_RAW (raw
protocol interface), SOCK_RDM (reliable datagrams), and SOCK_SEQPACKET (sequenced packet
stream). Each of these abstractions is supported by different protocols. We will be primarily
concerned with the SOCK_STREAM and SOCK_DGRAM abstractions.

ht

tp

://

cs

et

ub

e.t

k/

7.1 Datagram Sockets


The SOCK_DGRAM type provides a datagram model of communication. A datagram service is
connectionless and unreliable. Independent (and usually small) messages called datagrams are
accepted by the transport protocol and sent to the address specified. These messages may be lost,
duplicated, or received out of order. An important characteristic of datagrams is that message
boundaries are maintained. This means that individual datagrams (i.e., messages sent with separate
calls) will be kept separate when they are received at the other end. A revcfrom() call on a
datagram socket will only return the next datagram available. The SOCK_DGRAM type can be used in
the UNIX or Internet domain. When used in the Internet domain, it is supported by the Internet
transport protocol UDP. The call
sock = socket(AF_INET, SOCK_DGRAM, 0)
returns a UDP datagram socket.

7.2 Stream Sockets


The STREAM_SOCK type provides a stream model of communication. This service is reliable and
connection-oriented. Data is transmitted on a full-duplex, flow-controlled byte stream. The
transport protocol supporting this socket type must ensure that data is delivered in order without
loss, error, or duplication. Otherwise, it must abort the connection and report an error to the user.
Message boundaries are not preserved on a stream socket. Before data can be sent or received on a
stream socket, the socket must be made the active or passive end of a connection using the system
calls listen(), accept(), and connect() discussed in Section 2. Again, the SOCK_STREAM
abstraction can be used in both the UNIX and Internet domains. In the Internet domain, it is
supported by the Internet transport protocol TCP. The call
sock = socket(AF_INET, SOCK_STREAM, 0)
returns a TCP stream socket.
8. Protocols
A protocol is a set of communication conventions for regulating the exchange of information
between two parties. Transport protocols that support the styles of communication described above
are implemented as code in the UNIX kernel. These concrete protocols actually realize the
semantics defined by the socket type. User Datagram Protocol (UDP), Transmission Control

http://csetube.tk/

Network Lab CS2305


Protocol (TCP), and Internet Protocol (IP) all belong to the Internet family of protocols. Each
member of this protocol family supports a different abstract type. UDP supports datagram sockets,
TCP supports stream sockets, and the SOCK_RAW type of socket provides a raw interface to IP. TP,
the ISO connection-based transport protocol, conceptually supports the SOCK_SEQPACKET
abstraction, although it is not currently implemented in Berkeley Unix. There is currently only one
protocol supporting a given socket abstraction in a particular domain. Nothing, however, prevents
future protocols from being implemented that support the same abstract type in the same domain as
an existing protocol. The protocol to be used is specified in the protocol field of the socket call.
There are three ways to specify the protocol. First, if a zero is supplied, the system provides the
default protocol for that address family and socket type; this is the most common method. Second,
manifest constants describing protocols, such as IPPROTO_UDP, can be found in <netinet/in.h>.
Third, the network protocol database /etc/protocols can be consulted by calling
getprotobyname() and getprotobynumber() (see getprotoent(3N) and protocols(5)).
9. Associate the socket with a port
If a socket is created then we might have to associate that socket with a port on your local machine.
(This is commonly done if you're going to listen() for incoming connections on a specific port.The
port number is used by the kernel to match an incoming packet to a certain process's socket
descriptor.

ht

tp

://

cs

et

ub

e.t

k/

Here is the synopsis for the bind() system call:


int bind(int sockfd, struct sockaddr *my_addr, int addrlen);
sockfd is the socket file descriptor returned by socket(). my_addr is a pointer to a struct sockaddr
that contains information about your address, namely, port and IP address. addrlen can be set to
sizeof(struct sockaddr).

10. Connection Establishment

Stream sockets must establish a connection before data can be transferred. A stream socket is either
"active" or "passive". A socket is initially active and only becomes passive after a listen call. Only
active sockets can be mentioned in a connect call and only passive sockets can be mentioned in
accept. These connection establishment calls are intended for use with stream sockets, but
datagram sockets can call connect to permanently fix the destination for future send calls.
10.1 Active End
An active socket establishes a connection to a named passive socket by using the connect()
system call.
status = connect(sock, name, namelen)
int sock; /* socket descriptor */
struct sockaddr *name;
int namelen;
The name parameter is the address of the remote socket interpreted according to the
communication domain in which the socket exists. If the domain is AF_UNIX, this should be a
sockaddr_un structure; if the domain is AF_INET, it should be a sockaddr_in structure.
10.2 Passive End

http://csetube.tk/

Network Lab CS2305


A socket becomes the passive end of a connection by first doing a listen() and then an
accept().
status = listen(sock, queuelen)
int sock, queuelen;
Listen initializes a queue for waiting connection requests. The parameter queuelen specifies the
maximum number of queued connections that will be allowed. The maximum queue length is
currently limited by the system to 5. The manifest constant SOMAXCONN from <sys/socket.h>
defines this maximum. A connection can then be established using the system call accept().
new_socket = accept(old_sock, name, namelen)
int new_socket, old_sock; /* socket descriptors */
struct sockaddr *name; /* name of peer socket on new connection */
int *namelen; /* length of name in bytes */

cs

et

ub

e.t

k/

Accept takes the first pending connection request off the queue and returns a socket descriptor for a
new, connected socket. This socket has the same properties as the old socket. The address of the
socket at the active end is returned in name. Namelen is a value/result parameter that should be
initialized to the size of the address structure being passed; upon return it will be set to the actual
length of the address returned. The old socket remains unaffected and can be used to accept more
connections. If there are no pending connection requests, accept blocks. If necessary, a select can
be done first to see if there are any connection requests. A socket with pending connections will
show up as being ready for reading.

ht

tp

://

10.3 Byte Ordering


Basically, a computer has to have a way of storing things in memory. Depending on the system,
some systems will store things in memory starting with the less significant byte, while others
would do it the other way, starting with the most significant byte. For example, consider the
following:
10110001 10000000 01000000 00000000
That is a 32-bit string in a binary form. It could be just some number or a word. Now, some
systems would store this string starting with least significant byte like so:
[00000000] [01000000] [10000000] [10110001]
Now, as you can see, the least significant byte goes first, and more significant ones follow. That
way of storing is called a small endian. While other systems would store it the other way, like so:
[10110001] [10000000] [01000000] [00000000]
From the above example you can see that the string is being stored starting with the most
significant byte. This is called a big endian.
Imagine two different systems are communicating with each other. Say, you have an iMac and a
UNIX based system. Say iMac is our client, while UNIX is the server. The iMac requests a file,
and UNIX sends the file... guess what happens then? If those two systems have different byte
ordering, say UNIX uses a big endian and iMac uses a small endian, things will break in a horrible

http://csetube.tk/

Network Lab CS2305


manner and in the case of Windows, the crash will most likely take OS for the ride, too. There are
ways to avoid that. Always convert data received from the network into the native byte order!
@E$DSDSAFSADIJF*HER(e0rueqireir90r7937ufkjdkfsd-0ds9r037298y32jefke)

cs

et

ub

count = recv(sock, buf, buflen, flags)


int count, sock, buflen, flags; char *buf;

e.t

k/

10.4 Data Transfer


The system call pairs (read(), write()), (recv(), send()), (recvfrom(), sendto()),
(recvmsg(), sendmsg()), and (readv(), writev()) can all be used to transfer data on sockets.
The most appropriate call depends on the exact functionality required. send() and recv() are
typically used with connected stream sockets. They can also be used with datagram sockets if the
sender has previously done a connect() or the receiver does not care who the sender is. sendto()
and recvfrom() are used with datagram sockets. sendto() allows one to specify the destination
of the datagram, while revcfrom() returns the name of the remote socket sending the message.
read() and write() can be used with any connected socket. These two calls may be chosen for
efficiency considerations. The remaining data transfer calls can be used for more specialized
purposes. writev() and readv() make it possible to scatter and gather data to/from separate
buffers. sendmsg() and recvmsg() allow scatter/gather capability as well as the ability to
exchange access rights. The calls read(), write(), readv(), and writev() take either a socket
descriptor or a file descriptor as their first argument; all the rest of the calls require a socket
descriptor.
count = send(sock, buf, buflen, flags)
int count, sock, buflen, flags; char *buf;

ht

tp

://

count = sendto(sock, buf, buflen, flags, to, tolen)


int count, sock, buflen, flags, tolen;
char *buf;
struct sockaddr *to;
count = recvfrom(sock, buf, buflen, flags, from, fromlen)
int count, sock, buflen, flags, *fromlen;
char *buf;
struct sockaddr *from;
For the send calls, count returns the number of bytes accepted by the transport layer, or -1 if some
error is detected locally. A positive return count is no indication of the success of the data transfer.
Note: If made non blocking, send may accept some but not all of the bytes in the data buffer.The
return value should be checked so that the remaining bytes can be sent if necessary. For receive
calls, count returns the number of bytes actually received, or -1 if some error is detected.
The first parameter for each call is a valid socket descriptor. The parameter buf is a pointer to the
caller's data buffer. In the send() calls, buflen is the number of bytes being sent; in the receive()
calls, it indicates the size of the data area and the maximum number of bytes the caller is willing to
receive. The parameter to in the sendto() call specifies the destination address (conforming to a
particular address family) and tolen specifies its length. The parameter from in the recvfrom() call
specifies the source address of the message. fromlen is a value/result parameter that initially gives
the size of the structure pointed to by from and then is modified on return to indicate the actual
length of the address.

http://csetube.tk/

Network Lab CS2305


The flags parameter, which is usually given zero as an argument, allows several special operations
on stream sockets. It is possible to send out-of-band data or "peek" at the incoming message
without actually reading it. The flags MSG_OOB and MSG_PEEK are defined in <sys/sockets.h>.
Out-of-band data is high priority data (such as an interrupt character) that a user might want to
process quickly before all the intervening data on the stream. If out-of-band data were present, a
SIGURG signal could be delivered to the user. The actual semantics of out-of band data is
determined by the relevant protocol. ISO protocols treat it as expedited data, while Internet
protocols treat it as urgent data.
If any of these system calls is interrupted by a signal, such as SIGALRM, the call will return -1 and
the variable errno will be set to EINTR. The system call will be automatically restarted. It may be
advisable to reset errno to zero.
Note: Error numbers are defined in the file <errno.h>.
close() and shutdown()
After send()ing and recv()ing data ,close the connection on the socket descriptor.Use close()
function:
close(sockfd);

ht

tp

://

cs

et

ub

e.t

k/

This will prevent any more reads and writes to the socket. Anyone attempting to read or write the
socket on the remote end will receive an error.
To have more control over how the socket closes, use the shutdown() function. It allows you to cut
off communication in a certain direction, or both ways
int shutdown(int sockfd, int how);
sockfd is the socket file descriptor you want to shutdown, and how is one of the following:
0 -- Further receives are disallowed
1 -- Further sends are disallowed
2 -- Further sends and receives are disallowed (like close())
shutdown() returns 0 on success, and -1 on error (with errno set accordingly.)
11. Getting the destination name
getpeername() : The function getpeername() gives the other end of a connected stream socket.
int getpeername(int sockfd, struct sockaddr *addr, int *addrlen);
sockfd is the descriptor of the connected stream socket, addr is a pointer to a struct sockaddr (or a
struct sockaddr_in) that will hold the information about the other side of the connection, and
addrlen is a pointer to an int, that should be initialized to sizeof(struct sockaddr).
The function returns -1 on error and sets errno accordingly.
12. Getting the source name
gethostname()
It returns the name of the computer that your program is running on. The name can then be used
by gethostbyname(), below, to determine the IP address of your local machine.
int gethostname(char *hostname, size_t size);
hostname is a pointer to an array of chars that will contain the hostname upon the function's return,
and size is the length in bytes of the hostname array.
The function returns 0 on successful completion, and -1 on error, setting errno as usual.

http://csetube.tk/

Network Lab CS2305

13. DNS resolver


DNS stands for "Domain Name Service". In a nutshell, you tell it what the human-readable address
is for a site, and it'll give you the IP address (so you can use it with bind(), connect(), sendto(), or
whatever you need it for.)
Use the function gethostbyname():

ht

tp

://

cs

et

ub

e.t

k/

struct hostent *gethostbyname(const char *name);


It returns a pointer to a struct hostent
struct hostent {
char *h_name;
char **h_aliases;
int h_addrtype;
int h_length;
char **h_addr_list;
};
#define h_addr h_addr_list[0]
And here are the descriptions of the fields in the struct hostent:
h_name -- Official name of the host.
h_aliases -- A NULL-terminated array of alternate names for the host.
h_addrtype -- The type of address being returned; usually AF_INET.
h_length -- The length of the address in bytes.
h_addr_list -- A zero-terminated array of network addresses for the host. Host addresses are in
Network Byte Order.
h_addr -- The first address in h_addr_list.
gethostbyname() returns a pointer to the filled struct hostent, or NULL on error. (But errno is not
set--h_errno is set instead. See herror(), below.)
14. Client-Server architecture
Normally network deals with client processes talking to server processes and vice-versa. Take
telnet, for instance. When you connect to a remote host on port 23 with telnet (the client), a
program on that host (called telnetd, the server) springs to life. It handles the incoming telnet
connection, sets you up with a login prompt, etc.
Client-Server Interaction.

The exchange of information between client and server is summarized


Note that the client-server pair can speak SOCK_STREAM, SOCK_DGRAM, or anything else (as
long as they're speaking the same thing.) Some good examples of client-server pairs are

http://csetube.tk/

Network Lab CS2305


telnet/telnetd, ftp/ftpd, or bootp/bootpd. Every time you use ftp, there's a remote program, ftpd,
that serves you.
Often, there will only be one server on a machine, and that server will handle multiple clients using
fork(). The basic routine is: server will wait for a connection, accept() it, and fork() a child process
to handle it.
14.1 Understanding Clients and Servers
The Clients are known as Active and Server is known as Passive, or Outgoing and
Incomming.There is no defacto standard to be sure for describing the two parts... but Client Server
is used allot.
Client = Active = Outgoing
Server = Passive = Incomming
Heres is a basic run down on the application level and network level, of the different socket
connections.
14.2 Client Communications
Network PC level
socket is called by the program. This will set up a data
structure for the operating system to use, to read and write,
and control the socket.
With active ( client ) sockets you do not always need to call
bind, but if you would like to designate a particular IP port to
be used with the UDP socket you will need to fill in the struct
sockaddr_in, and make a call to bind();, bind is used to set
the address and port number associated with a given socket
With UDP sockets you do not always need to call connect
before sending, With TCP this connect call will make the OS
preform what is known as "the TCP three part
handshake". This consists of the Client computer ( the
computer that called connect ) sending a SYN packet, to the
Server computer. If all goes well the server computer will
respond with an SYN,ACK packet, and then finally the Client
computer sends a final ACK packet. If all this works well
connect( ) returns a posetive integer, and you will have a
connected socket .
UDP can use send( ), recv( ), sendto( ), recvfrom( ), read( ),
and write( ) for passing data. If you have used bind to bind a
ipaddress and port, you will most likely want to just use recv
for reading, and send for sending. If you have not used bind
on the UDP socket it may be nessary to use sendto, and recv,
or recvfrom. When using TCP it is more common for
applications to use send, and recv, allthough sendto, recvfrom,
and read and write do work.
These functions will close the socket and deallocate any
resources from the OS.

tp

ht

connect( );

://

cs

et

ub

*bind( );

e.t

k/

Application level
socket( );

send( );, and


or recv( );, sendto( );,
recvfrom( );

close( );, shutdown( );

http://csetube.tk/

Network Lab CS2305


14.3 Server Communications
Application level
socket( );
is called by the program
*bind( );

*listen( );

k/

*accept( );

Network PC level
This will set up a data structure for the
operating system to use, to read and write,
and control the socket
Bind is used to realte a local port number to
a socket, therefore if you wanted to create a
server that ran on a specific port, such as
telnet, FTP, and HTTP, you will need to
use bind in your sever application.
The call to listen( ) is only needed in TCP
applications, this will allow you to specify
how many clients can connect to any given
TCP port at one time.
The call to accept( ) again , is only needed
in TCP applications, this will allow you to
preform the server side of the three way
handshake when a client connects. If
accept is successfull it will return a new
socket to you for reading and writting.
UDP can use send( ), recv( ), sendto( ),
recvfrom( ), read( ), and write( ) for passing
data. If you have used bind to bind a
ipaddress and port, you will most likely
want to just use recv for reading, and send
for sending. If you have not used bind on
the UDP socket it may be nessary to use
sendto, and recv, or recvfrom.
These functions will close the socket and
deallocate any resources from the OS.

close( );, shutdown( );

ht

tp

://

cs

et

ub

e.t

send( );, and


or recv( );, sendto( );, recvfrom( );

http://csetube.tk/

Network Lab CS2305


Introduction to NS-2 Simulator
NS is a discrete event simulator for networking research. It provides substantial support for
simulation of TCP, routing, and multicast protocols over wired and wireless (local and satellite)
networks.
15.1 Downloading/Installing ns
NS should configure and build on Unix systems. To install NS-2 in your own system, you can
download the package from http://www.isi.edu/nsnam/ns/ns-build.html (To install NS in windows
systems, please also refer this page). There are two ways to build ns: from the various packages or
all-in-one package. For simplicity, it is recommended to start with the all-in-one package.
Build NS:
Entering NS2 directory and execute:
./gunzip ns-allinone-***.tar.gz
/* *** is the version number */
/* unzip the file */
./tar xvf ns-allinone-***.tar
/* untar the file */
./install
./validate
Please refer http://www.isi.edu/nsnam/ns/ns-problems.html for any installation problems.

ht

tp

://

cs

et

ub

e.t

k/

15.2 Starting ns
You start ns with the command 'ns <tclscript>' (assuming that you are in the directory with the ns
executable, or that your path points to that directory), where '<tclscript>' is the name of a Tcl script
file which defines the simulation scenario (i.e. the topology and the events). You could also just
start ns without any arguments and enter the Tcl commands in the Tcl shell, but that is definitely
less comfortable. For information on how to write your own Tcl scripts for ns.Everything else
depends on the Tcl script. The script might create some output on stdout, it might write a trace file
or it might start nam to visualize the simulation. Or all of the above. These possibilities will all be
discussed in later sections.
15.3 Starting nam
You can either start nam with the command 'nam <nam-file>' where '<nam-file>' is the name of a
nam trace file that was generated by ns, or you can execute it directly out of the Tcl simulation
script for the simulation which you want to visualize. Below you can see a screenshot of a nam
window where the most important functions are being explained.

http://csetube.tk/

ub

e.t

k/

Network Lab CS2305

ht

tp

://

cs

et

15.4 How to start


Now we are going to write a 'template' that you can use for all of the first Tcl scripts. You can
write your Tcl scripts in any text editor like joe or emacs. I suggest that you call this first example
'example1.tcl'.
First of all, you need to create a simulator object. This is done with the command
set ns [new Simulator]
Now we open a file for writing that is going to be used for the nam trace data.
set nf [open out.nam w]
$ns namtrace-all $nf
The first line opens the file 'out.nam' for writing and gives it the file handle 'nf'. In the second line
we tell the simulator object that we created above to write all simulation data that is going to be
relevant for nam into this file.The next step is to add a 'finish' procedure that closes the trace file
and starts nam.
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam out.nam &
exit 0
}

http://csetube.tk/

Network Lab CS2305


You don't really have to understand all of the above code yet. It will get clearer to you once you
see what the code does. The next line tells the simulator object to execute the 'finish' procedure
after 5.0 seconds of simulation time.
$ns at 5.0 "finish"
You probably understand what this line does just by looking at it. ns provides you with a very
simple way to schedule events with the 'at' command. The last line finally starts the simulation.
$ns run
You can actually save the file now and try to run it with 'ns example1.tcl'. You are going to get an
error message like 'nam: empty trace file out.nam' though, because until now we haven't defined
any objects (nodes, links, etc.) or events. You will have to use the code from this section as starting
point in the other sections. #Create a simulator object
set ns [new Simulator]

e.t

cs

et

ub

#Define a 'finish' procedure


proc finish {} {
global ns nf
$ns flush-trace
#Close the trace file
close $nf
#Execute nam on the trace file
exec nam out.nam &
exit 0
}

k/

#Open the nam trace file


set nf [open out.nam w]
$ns namtrace-all $nf

ht

tp

://

# Insert your own code for topology creation


# and agent definitions, etc. here
#Call the finish procedure after 5 seconds simulation time
$ns at 5.0 "finish"
#Run the simulation
$ns run

15.5 Two nodes, one link


In this section we are going to define a very simple topology with two nodes that are connected by
a link. The following two lines define the two nodes. (Note: You have to insert the code in this
section before the line '$ns run', or even better, before the line '$ns at 5.0 "finish"').
set n0 [$ns node]
set n1 [$ns node]
A new node object is created with the command '$ns node'. The above code creates two nodes and
assigns them to the handles 'n0' and 'n1'. The next line connects the two nodes.
$ns duplex-link $n0 $n1 1Mb 10ms DropTail
This line tells the simulator object to connect the nodes n0 and n1 with a duplex link with the
bandwidth 1Megabit, a delay of 10ms and a DropTail queue.
Now you can save your file and start the script with 'ns example1.tcl'. nam will be started
automatically and you should see an output that resembles the picture below.

http://csetube.tk/

Network Lab CS2305

#Create a simulator object


set ns [new Simulator]

e.t

ub

#Define a 'finish' procedure


proc finish {} {
global ns nf
$ns flush-trace
#Close the trace file
close $nf
#Execute nam on the trace file
exec nam out.nam &
exit 0
}

k/

#Open the nam trace file


set nf [open out.nam w]
$ns namtrace-all $nf

://

cs

et

#Create two nodes


set n0 [$ns node]
set n1 [$ns node]

ht

tp

#Create a duplex link between the nodes


$ns duplex-link $n0 $n1 1Mb 10ms DropTail
#Call the finish procedure after 5 seconds of simulation time
$ns at 5.0 "finish"
#Run the simulation
$ns run

15.5.1 Sending data


The next step is to send some data from node n0 to node n1. In ns, data is always being sent from
one 'agent' to another. So the next step is to create an agent object that sends data from node n0,
and another agent object that receives the data on node n1.
#Create a UDP agent and attach it to node n0
set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0
# Create a CBR traffic source and attach it to udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
These lines create a UDP agent and attach it to the node n0, then attach a CBR traffic generator to
the UDP agent. CBR stands for 'constant bit rate'. Line 7 and 8 should be self-explaining. The

http://csetube.tk/

Network Lab CS2305


packet Size is being set to 500 bytes and a packet will be sent every 0.005 seconds (i.e. 200 packets
per second). The next lines create a Null agent which acts as traffic sink and attach it to node n1.
set null0 [new Agent/Null]
$ns attach-agent $n1 $null0
Now the two agents have to be connected with each other.
$ns connect $udp0 $null0
And now we have to tell the CBR agent when to send data and when to stop sending. Note: It's
probably best to put the following lines just before the line '$ns at 5.0 "finish"'.

et

ub

e.t

k/

$ns at 0.5 "$cbr0 start"


$ns at 4.5 "$cbr0 stop"
This code should be self-explaining again. Now you can save the file and start the simulation
again. When you click on the 'play' button in the nam window, you will see that after 0.5
simulation seconds, node 0 starts sending data packets to node 1. You might want to slow nam
down then with the 'Step' slider.

ht

tp

://

cs

Now you start some experiments with nam and the Tcl script. You can click on any packet in the
nam window to monitor it, and you can also click directly on the link to get some graphs with
statistics.Try to change the 'packetsize_' and 'interval_' parameters in the Tcl script to see what
happens.
#Create a simulator object
set ns [new Simulator]
#Open the nam trace file
set nf [open out.nam w]
$ns namtrace-all $nf
#Define a 'finish' procedure
proc finish {} {
global ns nf
$ns flush-trace
#Close the trace file
close $nf
#Execute nam on the trace file
exec nam out.nam &
exit 0
}
#Create two nodes
set n0 [$ns node]
set n1 [$ns node]
#Create a duplex link between the nodes
$ns duplex-link $n0 $n1 1Mb 10ms DropTail
#Create a UDP agent and attach it to node n0

http://csetube.tk/

Network Lab CS2305


set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0
# Create a CBR traffic source and attach it to udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
#Create a Null agent (a traffic sink) and attach it to node n1
set null0 [new Agent/Null]
$ns attach-agent $n1 $null0
#Connect the traffic source with the traffic sink
$ns connect $udp0 $null0
#Schedule events for the CBR agent
$ns at 0.5 "$cbr0 start"
$ns at 4.5 "$cbr0 stop"
#Call the finish procedure after 5 seconds of simulation time
$ns at 5.0 "finish"
#Run the simulation
$ns run

ht

tp

://

cs

et

ub

e.t

k/

15.6 The topology


You will always have to create a simulator object, you will always have to start the simulation with
the same command, and if you want to run nam automatically, you will always have to open a trace
file, initialize it, and define a procedure which closes it and starts nam.
Now insert the following lines into the code to create four nodes.
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
The following piece of Tcl code creates three duplex links between the nodes.
$ns duplex-link $n0 $n2 1Mb 10ms DropTail
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n3 $n2 1Mb 10ms DropTail
You can save and start the script now. You might notice that the topology looks a bit awkward in
nam. You can hit the 're-layout' button to make it look better, but it would be nice to have some
more control over the layout. Add the next three lines to your Tcl script and start it again.
$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n2 $n3 orient right
You will probably understand what this code does when you look at the topology in the nam
window now. It should look like the picture below.

http://csetube.tk/

Network Lab CS2305

15.7 The events


Now we create two UDP agents with CBR traffic sources and attach them to the nodes n0 and n1.
Then we create a Null agent and attach it to node n3.
#Create a UDP agent and attach it to node n0
set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0

ub

e.t

k/

# Create a CBR traffic source and attach it to udp0


set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0

tp

://

cs

et

#Create a UDP agent and attach it to node n1


set udp1 [new Agent/UDP]
$ns attach-agent $n1 $udp1

ht

# Create a CBR traffic source and attach it to udp1


set cbr1 [new Application/Traffic/CBR]
$cbr1 set packetSize_ 500
$cbr1 set interval_ 0.005
$cbr1 attach-agent $udp1
set null0 [new Agent/Null]
$ns attach-agent $n3 $null0
The two CBR agents have to be connected to the Null agent.
$ns connect $udp0 $null0
$ns connect $udp1 $null0
We want the first CBR agent to start sending at 0.5 seconds and to stop at 4.5 seconds while the
second CBR agent starts at 1.0 seconds and stops at 4.0 seconds.
$ns at 0.5 "$cbr0 start"
$ns at 1.0 "$cbr1 start"
$ns at 4.0 "$cbr1 stop"
$ns at 4.5 "$cbr0 stop"
When you start the script now with 'ns example2.tcl', you will notice that there is more traffic on
the links from n0 to n2 and n1 to n2 than the link from n2 to n3 can carry. A simple calculation
confirms this: We are sending 200 packets per second on each of the first two links and the packet
size is 500 bytes. This results in a bandwidth of 0.8 megabits per second for the links from n0 to n2
and from n1 to n2. That's a total bandwidth of 1.6Mb/s, but the link between n2 and n3 only has a
capacity of 1Mb/s, so obviously some packets are being discarded. But which ones? Both flows are

http://csetube.tk/

Network Lab CS2305


black, so the only way to find out what is happening to the packets is to monitor them in nam by
clicking on them. In the next two sections I'm going to show you how to distinguish between
different flows and how to see what is actually going on in the queue at the link from n2 to n3.
Marking flows
Add the following two lines to your CBR agent definitions.
$udp0 set class_ 1
$udp1 set class_ 2
The parameter 'fid_' stands for 'flow id'.
Now add the following piece of code to your Tcl script, preferably at the beginning after the
simulator object has been created, since this is a part of the simulator setup.
$ns color 1 Blue
$ns color 2 Red

ht

tp

://

cs

et

ub

e.t

k/

This code allows you to set different colors for each flow id.

Now you can start the script again and one flow should be blue, while the other one is red. Watch
the link from node n2 to n3 for a while, and you will notice that after some time the distribution
between blue and red packets isn't too fair anymore (at least that's the way it is on my system). In
the next section I'll show you how you can look inside this link's queue to find out what is going on
there.
Monitoring a queue
You only have to add the following line to your code to monitor the queue for the link from n2 to
n3.
$ns duplex-link-op $n2 $n3 queuePos 0.5
Start ns again and you will see a picture similar to the one below after a few moments.

http://csetube.tk/

Network Lab CS2305

k/

You can see the packets in the queue now, and after a while you can even see how the packets are
being dropped, though (at least on my system, I guess it might be different in later or earlier
releases) only blue packets are being dropped. But you can't really expect too much 'fairness' from
a simple Drop Tail queue. So let's try to improve the queuing by using a SFQ (stochastic fair
queuing) queue for the link from n2 to n3. Change the link definition for the link between n2 and
n3 to the following line.
$ns duplex-link $n3 $n2 1Mb 10ms SFQ
The queuing should be 'fair' now. The same amount of blue and red packets should be dropped.
Appendix A

tp

://

cs

et

/* basic system data types */


/* basic socket definitions */
/* timeval{} for select() */
/* timespec{} for pselect() */
/* sockaddr_in{} and other Internet defns */
/* inet(3) functions */

ht

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
*/
#include <netdb.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/un.h>
#include <stdarg.h>
Usefull Defines

ub

e.t

Header Files
When programming sockets you will need to #include the following header files:

/* for nonblocking, on windows don't use fnctl(), use ioctlsocket()

/* for S_xxx file mode constants */


/* this file is typically only for Linux *nix OS's */
/* for Unix domain sockets */
/* for sdprintf */

/* Define bzero( ) as a macro if it's not in standard C library. */


#ifndef HAVE_BZERO
#define bzero( ptr, n ) memset( ptr, 0, n )
#endif

http://csetube.tk/

Network Lab CS2305

/* Following shortens all the type casts of pointer arguments */


#define SA
struct sockaddr
#define SA_in struct sockaddr_in
#define min( a , b ) ( ( a ) < ( b ) ? ( a ) : ( b ) )
#define max( a , b ) ( ( a ) > ( b ) ? ( a ) : ( b ) )

k/

Appendix B

ht

tp

://

cs

et

ub

e.t

Program to create a socket


/* Ex-1
Program To Create a Socket */
#include <stdio.h>
/* NEEDED HEADER FILES */
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
int main()
{
int sockfd1,sockfd2;
/* sokcet file descriptors */
sockfd1=socket(AF_INET,SOCK_STREAM,0); /* socket system call */
sockfd2=socket(PF_INET,SOCK_DGRAM,0);
if(sockfd1==-1)
/* error checking */
{
printf("Socket1 not Created\n");
}
else
{
printf("Socket1 Created and \t Socket1 File Descriptor value is %d \n",sockfd1);
if(sockfd2==-1)
{
printf("socket2 creation error");
}
else
{
printf("Socket2 created and \t socket2 descriptor value is %d\n",sockfd2);
}

http://csetube.tk/

Network Lab CS2305

ht

tp

://

cs

et

ub

e.t

k/

}
}

http://csetube.tk/

Network Lab CS2305

Program to Bind a socket


/* Ex-2 Program to Bind a Socket */
#include<stdio.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#define PORTNO 2000
/* Type definition of a Port number */
int main()
{
int sockfd,i=PORTNO;
struct sockaddr_in myaddr;
/* Builtin structure for internet address */
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{printf("Socket Creation Error\n");}

e.t

k/

myaddr.sin_family=AF_INET;
/* Structure variable definition */
myaddr.sin_port=htons(PORTNO);
myaddr.sin_addr.s_addr=INADDR_ANY;
memset(&(myaddr.sin_zero),'\0',8); /* fills with constant byte to remaining space */

ht

tp

://

cs

et

ub

/* socket Binding process and error checking */


if(bind(sockfd,(struct sockaddr *)&myaddr,sizeof(struct sockaddr))!=-1)
{
printf(" Socket is Binded at port %d\n",i);
}
else
{
printf("Binding Error\n");
}
}

http://csetube.tk/

Network Lab CS2305

Program to implement listen() system call


/* Ex-3 Program to implement LISTEN system call */
#include <stdio.h>
/* These are the usual header files */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 3550 /*Assigning Port number */
#define BACKLOG 12 /* Number of allowed connections */
main()
{
/* file descriptors */

struct sockaddr_in server;


struct sockaddr_in client;

/* server's address information */


/* client's address information */

ub

e.t

k/

int fd;

ht

tp

://

cs

et

int sin_size;
int x;
if ((fd=socket(AF_INET, SOCK_STREAM, 0)) == -1 ){ /* calls socket() */
printf("socket() error\n");
exit(-1);
}
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
/* Remember htons() from "Conversions" section? =) */
server.sin_addr.s_addr = INADDR_ANY; /* INADDR_ANY puts your IP address automatically */
bzero(&(server.sin_zero),8);
/* zero the rest of the structure */
if(bind(fd,(struct sockaddr*)&server,sizeof(struct sockaddr))==-1) /* calls bind() */
{
printf("bind() error\n");
exit(-1);
}
x=listen(fd,BACKLOG) ;
/* calls listen() */
if(x==-1)
{
printf("listen() error\n");
exit(-1);
}
else
{
printf(Server is in listening mode \n );

http://csetube.tk/

Network Lab CS2305

tp

://

cs

et

ub

e.t

k/

/* close fd */

ht

}
close(fd);

http://csetube.tk/

Network Lab CS2305

Program for accept() system call


/* Ex-3 Program to implement ACCEPT system calls */
#include <stdio.h>
/* These are the usual header files */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 3550 /* Assigning Port numbers */
#define BACKLOG 2 /* Number of allowed connections */
main()
{
/* file descriptors */

struct sockaddr_in server;


struct sockaddr_in client;

/* server's address information */


/* client's address information */

ub

e.t

k/

int fd, fd2;

ht

tp

://

cs

et

int sin_size;
if ((fd=socket(AF_INET, SOCK_STREAM, 0)) == -1 ) /* calls socket() */
{
printf("socket() error\n");
exit(-1);
}
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
/* Remember htons() from "Conversions" section */
server.sin_addr.s_addr = INADDR_ANY; /* INADDR_ANY puts your IP address automatically */
bzero(&(server.sin_zero),8);
/* zero the rest of the structure */
if(bind(fd,(struct sockaddr*)&server,sizeof(struct sockaddr))==-1){ /* calls bind() */
printf("bind() error\n");
exit(-1);
}
{

if(listen(fd,BACKLOG) == -1)

/* calls listen() */

printf("listen() error\n");
exit(-1);

}
printf("server is in accept mode \n ");

http://csetube.tk/

Network Lab CS2305


while(1)
{
sin_size=sizeof(struct sockaddr_in);
if ((fd2 = accept(fd,(struct sockaddr *)&client,&sin_size))==-1){ /* calls accept() */
printf("accept() error\n");
exit(-1);
}
else
printf(" Server is in accept mode ");
printf("You got a connection from %s\n",inet_ntoa(client.sin_addr) ); /* prints client's IP */

k/
e.t
ub
et
cs
://
tp
ht

}
}

close(fd2); /* close fd2 */

http://csetube.tk/

Network Lab CS2305

Program to implement Client/Server architecture using TCP


/* Ex-4 Program to implement client/server architecture using TCP/IP */
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

/* These are the usual header files */

#define PORT 3550


#define BACKLOG 2

/* Assigning Port number */


/* Number of allowed connections */

main()
{
int fd, fd2;

/* file descriptors */
/* server's address information */
/* client's address information */

k/

struct sockaddr_in server;


struct sockaddr_in client;

ub

e.t

int sin_size;

ht

tp

://

cs

et

if ((fd=socket(AF_INET, SOCK_STREAM, 0)) == -1 ) /* calls socket() */


{
printf("socket() error\n");
exit(-1);
}
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
/* Remember htons() from "Conversions" section*/
server.sin_addr.s_addr = INADDR_ANY; /* INADDR_ANY puts your IP address automatically */
bzero(&(server.sin_zero),8);
/* zero the rest of the structure */
if(bind(fd,(struct sockaddr*)&server,sizeof(struct sockaddr))==-1) /* calls bind() */
{
printf("bind() error\n");
exit(-1);
}
{

if(listen(fd,BACKLOG) == -1)

/* calls listen() */

printf("listen() error\n");
exit(-1);

while(1){

http://csetube.tk/

Network Lab CS2305


sin_size=sizeof(struct sockaddr_in);
if ((fd2 = accept(fd,(struct sockaddr *)&client,&sin_size))==-1) /* calls accept() */
{
printf("accept() error\n");
exit(-1);
}
printf("You got a connection from %s\n",inet_ntoa(client.sin_addr) ); /* prints client's IP */
send(fd2,"Welcome to my server.\n",22,0); /* send to the client welcome message */

://

cs

et

ub

e.t

k/

/*End of TCP server program */

tp

/* close fd2 */

ht

close(fd2);

http://csetube.tk/

Network Lab CS2305

Program to implement TCP client


#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

/* netdb.h is needed for struct hostent */

#define PORT 3550


#define MAXDATASIZE 100

/* Open Port on Remote Host */


/* Max number of bytes of data */

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


{
int fd, numbytes;
char buf[MAXDATASIZE];

/* files descriptors */
/* buf will store received text */
/* structure that will get information about remote host */
/* server's address information */

k/

struct hostent *he;


struct sockaddr_in server;

/* this is used because our program will need one


argument (IP) */
printf("Usage: %s <IP Address>\n",argv[0]);
exit(-1);

cs

et

ub

e.t

if (argc !=2) {

ht

tp

://

}
if ((he=gethostbyname(argv[1]))==NULL){
/* calls gethostbyname() */
printf("gethostbyname() error\n");
exit(-1);
}
if ((fd=socket(AF_INET, SOCK_STREAM, 0))==-1){ /* calls socket() */
printf("socket() error\n");
exit(-1);
}
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
/* htons() is needed again */
server.sin_addr = *((struct in_addr *)he->h_addr); /*he->h_addr passes "*he"'s info to
"h_addr" */
bzero(&(server.sin_zero),8);
if(connect(fd, (struct sockaddr *)&server,sizeof(struct sockaddr))==-1)

printf("connect() error\n");
exit(-1);
}
if ((numbytes=recv(fd,buf,MAXDATASIZE,0)) == -1)

/* calls recv() */

printf("recv() error\n");
exit(-1);

http://csetube.tk/

Network Lab CS2305


}

tp

://

cs

et

ub

e.t

k/

/* End of the tcp client program */

ht

buf[numbytes]='\0';
printf("Server Message: %s\n",buf); /* it prints server's welcome message =) */
close(fd); /* close fd =) */

http://csetube.tk/

Network Lab CS2305

Program to get the Host name


/* Program to get the hostname */
#include<stdio.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<netdb.h>
#include<errno.h>

/* These are the usual header files */

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


{
struct hostent *h;
if(argc != 2)

ht

tp

://

cs

et

ub

e.t

k/

{
fprintf(stderr , "usage : getip address \n ");
exit(1);
}
if((h=gethostbyname(argv[1])) == NULL) /* Get the Local host name */
{
herror("gethostbyname ");
exit(1);
}
printf(" Host name : %s \n ",h->h_name);
printf("IP address : %s \n ", inet_ntoa(*((struct in_addr *)h->h_addr)));
return 0;
}

http://csetube.tk/

Network Lab CS2305

Program to implement Client /Server architecture using UDP

ht

tp

://

cs

et

ub

e.t

k/

/*Program to implement Datagram server*/


#include <stdio.h>
/*Usual header Files */
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define MYPORT 4950
/* the port users will be connecting */
#define MAXBUFLEN 100
int main(void)
{
int sockfd;
struct sockaddr_in my_addr;
/* my address information*/
struct sockaddr_in their_addr;
/* connectors address information*/
int addr_len, numbytes;
char buf[MAXBUFLEN];
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
perror("socket");
exit(1);
}
my_addr.sin_family = AF_INET;
/* host byte order*/
my_addr.sin_port = htons(MYPORT);
// short, network byte order
my_addr.sin_addr.s_addr = INADDR_ANY;
// automatically fill with my IP
memset(&(my_addr.sin_zero), \0, 8);
// zero the rest of the struct
if (bind(sockfd, (struct sockaddr *)&my_addr,
sizeof(struct sockaddr)) == -1) {
perror("bind");
exit(1);
}
addr_len = sizeof(struct sockaddr);
if ((numbytes=recvfrom(sockfd,buf, MAXBUFLEN-1, 0,
(struct sockaddr *)&their_addr, &addr_len)) == -1) {
perror("recvfrom");
exit(1);
}
printf("got packet from %s\n",inet_ntoa(their_addr.sin_addr));
printf("packet is %d bytes long\n",numbytes);
buf[numbytes] = \0;
printf("packet contains \"%s\"\n",buf);
close(sockfd);
return 0; }

http://csetube.tk/

Network Lab CS2305

Program to implement Datagram Client

ht

tp

://

cs

et

ub

e.t

k/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#define MYPORT 4950
// the port users will be connecting to
int main(int argc, char *argv[])
{
int sockfd;
struct sockaddr_in their_addr;
// connectors address information
struct hostent *he;
int numbytes;
if (argc != 3) {
fprintf(stderr,"usage: talker hostname message\n");
exit(1);
}
if ((he=gethostbyname(argv[1])) == NULL) {
// get the host info
perror("gethostbyname");
exit(1);
}
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
perror("socket");
exit(1);
}
their_addr.sin_family = AF_INET;
// host byte order
their_addr.sin_port = htons(MYPORT);
// short, network byte order
their_addr.sin_addr = *((struct in_addr *)he->h_addr);
memset(&(their_addr.sin_zero), \0, 8);
// zero the rest of the struct
if ((numbytes=sendto(sockfd, argv[2], strlen(argv[2]), 0,
(struct sockaddr *)&their_addr, sizeof(struct sockaddr))) == -1) {
perror("sendto");
exit(1);
}
printf("sent %d bytes to %s\n", numbytes,
inet_ntoa(their_addr.sin_addr));
close(sockfd);
return 0;
}

http://csetube.tk/

Network Lab CS2305

Procedure to run the program in LINUX

ht

tp

://

cs

et

ub

e.t

k/

1.Open VI editor (read the manual topic 1)


2.Type the program.
3.to save :wq
4.To compile cc programname with extn
5.to run ./a.out
6.To get host name program ./a.out ipaddress of the system

http://csetube.tk/

Network Lab CS2305

SIMULATION OF ARP/RARP
DATE:
AIM:

EX.NO: 1

To perform Address Resolution Protocol or Reverse Address Resolution protocol using c.

ALGORITHM:
1. Start the program with required header files.
2. To define file descriptor with characters, variables and character pointer.
3. The MAC address and IP address are obtained from the user.

k/

4. To make The MAC and IP address is displayed as a table.

e.t

5. Get the IP address from the user.

MAC

et

ub

6. ARP is used to Map the IP address and MAC Address and its display the
address on the screen.

://

cs

7. Get the MAC address from the user.

ht

screen.

tp

8. RARP used to Map the MAC address and IP address and its display the IP address on the
9. Stop.

Sample Input: & Sample Output :


Server File:

Enter the MAC address


A1:B2:C3:D4:E5:F6

Enter the IP address


1.2.3.4

http://csetube.tk/

Network Lab CS2305

Enter the MAC address


A2.B3.C4.D5.E6.F7

Enter the IP address


5.6.7.8

Enter the MAC address


A3.B4.C5.D6.E7.F8

Enter the IP address


9.10.11.12

ub

e.t

k/

Client File:
The APR table is
A1.B2.C3.D4.E5.F6
A2.B3.C4.D5.E6.F7
A3.B4.C5.D6.E7.F8

ht

Enter your choice: 1

tp

://

cs

et

1.ARP
2.RARP
3.EXIT

Enter the IP address:


5.6.7.8
A2:B3:C4:D5:E6:f7

Enter your choice 2


Enter MAC address
A3:B4:C5:D6:E7:F8
9.10.11.12

Result:

Thus the program was executed successfully.

http://csetube.tk/

Network Lab CS2305

BITSTUFFING
DATE:
AIM:

EX.NO: 2

To write a C program to perform bit stuffing operation.

ALGORITHM:
1. Start the program with required header files.
2. Get the input string from the user and find out the length of the string.
3. Covert the given input string into ASCII character.
4. Calculate the binary equivalent of each character.
5. Check the number of ones present in the binary value.

e.t

k/

6. If there are five consecutive ones in the binary value then insert the parity bit in sixth

ub

position.

et

7. Repeat the same procedure for entire string.

ht

tp

://

cs

8. Stop.

Input:
Enter the i/p string:
10101111110101111110
Output:
The bit stuffed string is 1010111110101011111010

Result:

Thus the program was executed successfully.

http://csetube.tk/

Network Lab CS2305

CYCLIC REDUNDANCY CHECK (CRC)


DATE:
AIM:

EX.NO: 3

To write a C program to perform CRC.

ALGORITHM:
1. CRC is one of the powerful redundancies checking technique.
2. Get the input form the user.
3. Calculate the key value. Key k= number of bits present in the input 1.
4. The key using binary division technique divides the input string.
5. The reminder is the required CRC it replaces the 0s in the input string then transmits your

e.t

k/

input.

ub

6. At the receiving end the key using binary division divides the received message.

://
ht

tp

error message.

cs

et

7. If reminder is 0 then your received message is correct otherwise it display the

Input & Output:


1.find crc
2.check crc
3. exit
Enter the choice 1
Enter the input string
100100
Enter the key
1101
The transmitted message is 100100001
1.find crc
2. check crc
3.exit

http://csetube.tk/

Network Lab CS2305

ht

tp

://

cs

et

ub

e.t

k/

Enter the choice 2


Enter the input string
100100
Enter the key
1101
There is no error in the message

Result:

Thus the program was executed successfully.

http://csetube.tk/

Network Lab CS2305

TRANSFERING FILES OVER RS232


DATE:

EX.NO: 4

AIM:
To write a c program to develop an application for transferring files over RS232
ALGORITHM:

tp
ht

Input:

://

cs

et

ub

e.t

k/

1. Start the program by including all the necessary header files.


2. Define the serial port base address.
3. Turn off the interrupt using the output function.
4. Set DLAB ON and band rates using the output function.
5. Compile and execute the program.
6. Enter your file name.
7. Open the file in write mode else open the file in read mode.
8. Stop.

Enter the file name: Sample.txt


Hi this is sample program
Output:
Sample.txt
Hi this is sample program

Result:

Thus the program was executed successfully.

http://csetube.tk/

Network Lab CS2305

SLIDING WINDOW PROTOCOL


DATE:

EX.NO: 5

AIM:
To write a C program to perform sliding window.
ALGORITHM:
Start the program.
Get the frame size from the user
To create the frame based on the user request.
To send frames to server from the client side.
If your frames reach the server it will send ACK signal to client otherwise it will send NACK
signal to client.
6. Stop the program

et

ub

e.t

k/

1.
2.
3.
4.
5.

tp

ht

Enter the frame size: 13


Enter the number of frame: 2

://

cs

Input:

Output:
ACK signal from server.
NACK signal from server.

Result:
Thus the program was executed successfully.

http://csetube.tk/

Network Lab CS2305

CLIENT SERVER APPLICATION FOR CHAT


DATE:

AIM:

EX.NO: 6

To write a C program for simple chat application.

ALGORITHM:

tp
ht

Input & Output:

://

cs

et

ub

e.t

k/

1. Start the program with the header files.


2. To establish the connection between client and server by using socket and
function.
3. Bind the IP address and port number using bind function.
4. To send data from client to server.
5. The server provides the response to the client.
6. Close the connection using close function.
7. Stop.

Server:
[admin@root cse03]$./.a.out 16257
Type the message to client:
Hi how are you
Client: hello how are you.
Fine
Client:
[admin@root cse03]$. /.a.out 192.168.3.33 16257
Enter the message to server
Server: Hi how are you
Hello how are you.
Server: Fine

Result:

Thus the program was executed successfully.

http://csetube.tk/

connect

Network Lab CS2305

DOMAIN NAME SYSTEM


DATE:

AIM:

EX.NO: 7

To write a C program to develop a DNS client server to resolve the given hostname.

ALGORITHM:

ub

e.t

k/

Create a new file. Enter the domain name and address in that file.
To establish the connection between client and server.
Compile and execute the program.
Enter the domain name as input.
The IP address corresponding to the domain name is display on the screen
Enter the IP address on the screen.
The domain name corresponding to the IP address is display on the screen.
Stop the program.

Output:

Result:

ht

Input:

tp

://

cs

et

1.
2.
3.
4.
5.
6.
7.
8.

[root@localhost root]# ./a.out 172.16.6.187


Hostname: 172.16.6.187
Ip address:172.16.6.187

Thus the program was executed successfully

http://csetube.tk/

Network Lab CS2305

HTTP SERVER
DATE:

EX.NO: 8

AIM:
To write a c program to download the file from HTTP server.

ALGORITHM:

tp
ht

Input & Output:

://

cs

et

ub

e.t

k/

1. Start the program by including the entire necessary header files.


2. Initialize a file pointer named stream.
3. Get the name of the HTML file from the user.
4. Open the specified file in read mode.
5. If the file pointer stream is not NULL then get the character from the file and
it.
6. Stop the program.

<html>
<title>sample</title>
<body>
<h1>welcome to my home page</h1>
</body>
</html>

Result:

Thus the program was executed successfully

http://csetube.tk/

print

Network Lab CS2305

NETWORK SIMULATOR
DATE:

EX.NO: 9

AIM:
To write a program to perform network simulator using ping.

ALGORITHM:

e.t

k/

Start the program.


Create the required number of nodes and establish the connection between client and server.
Give various transfer rates to nodes.
Create the agent, which is used to check the connection between the nodes.
Run the procedures and call the appropriate functions.
Run the simulation.
Check the output and stop the program.

ht

tp

://

cs

et

ub

1.
2.
3.
4.
5.
6.
7.

Result:

Thus the program was executed successfully

http://csetube.tk/