CS 1305 - Network Lab Manual
CS 1305 - Network Lab Manual
SYLLABUS:
2. Write a program that takes a binary file as input and performs bit stuffing and
CRC Computation.
7. Develop a Client that contacts a given DNS Server to resolve a given host
name.
COURSE PLAN
Prerequisite:
Objectives:
To provide a good understanding of the salient features of network Programming. Students are
expected to understand the network concept in detail and to program using C programming
language.
Method of Assessment:
Algorithm - 15
Coding - 30
Program Execution - 20
Result Verification - 5
Viva Voce - 10
Department of Computer Science and Engineering
Network Lab CS1305
Cumulative
Expt. No. of
No.
No Name of the Experiment Periods
Of periods
1 Study of LAN switch (CISCO 2950) 4 49
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.
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:
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.
The command mode commands are normally in this format: (Optional arguments are given in the
brackets)
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:
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
Department of Computer Science and Engineering
Network Lab CS1305
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
k or Cursor up.
j or Cursor down.
b Cursor left one word.
w 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.
G Cursor to last line.
Get out of current mode.
i Start insert mode.
Insert a blank line below the current line and then start insert
o
mode.
Insert a blank line above the current line and then start insert
O
mode.
a Append (start insert mode after the current character).
R Replace (start insert mode with overwrite).
:wq Save (write) and quit.
:q Quit.
:q! Quit forced (without checking whether a save is required).
x Delete (delete under cursor and copy to register).
X 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).
u Undo.
Ctrl-R Redo.
de Delete to word end (and copy to register).
db Delete to word start (and copy to register).
Department of Computer Science and Engineering
Network Lab CS1305
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.
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.
A socket can be created with the socket()system call by specifying the desired address family,
socket type, and protocol.
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 */
char sa_data[14]; /* up to 14 bytes of direct address */
}
Department of Computer Science and Engineering
Network Lab CS1305
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.
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.
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.
struct in_addr {
union {
struct { u_char s_b1,s_b2,s_b3,s_b4; } S_un_b;
Department of Computer Science and Engineering
Network Lab CS1305
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.
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 low-
order 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 3-
byte 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
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
Department of Computer Science and Engineering
Network Lab CS1305
bind(), the local host address will be automatically supplied. Another reason for using
INADDR_ANY is thata 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.
8. Protocols
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.
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.
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.
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 */
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.
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:
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:
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
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(e0rueqireir90r7937ufkjdkf’sd-0ds9r037298y32jefke)
Department of Computer Science and Engineering
Network Lab CS1305
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;
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.
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
Department of Computer Science and Engineering
Network Lab CS1305
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>.
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.)
getpeername() : The function getpeername() gives the other end of a connected stream socket.
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.
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.
Department of Computer Science and Engineering
Network Lab CS1305
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():
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.
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.
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.
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
}
Department of Computer Science and Engineering
Network Lab CS1305
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]
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.
Department of Computer Science and Engineering
Network Lab CS1305
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
Department of Computer Science and Engineering
Network Lab CS1305
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"'.
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]
Marking flows
Add the following two lines to your CBR agent definitions.
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.
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.
Start ns again and you will see a picture similar to the one below after a few moments.
Department of Computer Science and Engineering
Network Lab CS1305
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
Header Files
When programming sockets you will need to #include the following header files:
Appendix B
if(sockfd2==-1)
{
printf("socket2 creation error");
}
else
{
printf("Socket2 created and \t socket2 descriptor value is %d\n",sockfd2);
}
Department of Computer Science and Engineering
Network Lab CS1305
}
}
Department of Computer Science and Engineering
Network Lab CS1305
main()
{
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 */
main()
{
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 */
main()
{
int fd, fd2; /* file descriptors */
int sin_size;
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 */
while(1){
Department of Computer Science and Engineering
Network Lab CS1305
sin_size=sizeof(struct sockaddr_in);
if ((fd2 = accept(fd,(struct sockaddr *)&client,&sin_size))==-1) /* calls accept() */
{
printf("accept() error\n");
exit(-1);
}
}
/*End of TCP server program */
Department of Computer Science and Engineering
Network Lab CS1305
#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 */
struct hostent *he; /* structure that will get information about remote host */
struct sockaddr_in server; /* server's address information */
if (argc !=2) { /* this is used because our program will need one
argument (IP) */
printf("Usage: %s <IP Address>\n",argv[0]);
exit(-1);
}
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);
Department of Computer Science and Engineering
Network Lab CS1305
}
buf[numbytes]='\0';
printf("Server Message: %s\n",buf); /* it prints server's welcome message =) */
close(fd); /* close fd =) */
}
/* End of the tcp client program */
Department of Computer Science and Engineering
Network Lab CS1305
{
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;
}
Department of Computer Science and Engineering
Network Lab CS1305
#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; // connector’s 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;
}
Department of Computer Science and Engineering
Network Lab CS1305
SIMULATION OF ARP/RARP
DATE: EX.NO: 1
AIM:
To perform Address Resolution Protocol or Reverse Address Resolution protocol using c.
ALGORITHM:
Server File:
Client File:
The APR table is
A1.B2.C3.D4.E5.F6
A2.B3.C4.D5.E6.F7
A3.B4.C5.D6.E7.F8
1.ARP
2.RARP
3.EXIT
5.6.7.8
A2:B3:C4:D5:E6:f7
Result:
Thus the program was executed successfully.
Department of Computer Science and Engineering
Network Lab CS1305
BITSTUFFING
DATE: EX.NO: 2
AIM:
To write a C program to perform bit stuffing operation.
ALGORITHM:
Input:
Enter the i/p string:
10101111110101111110
Output:
Result:
Thus the program was executed successfully.
Department of Computer Science and Engineering
Network Lab CS1305
DATE: EX.NO: 3
AIM:
To write a C program to perform CRC.
ALGORITHM:
error message.
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
Department of Computer Science and Engineering
Network Lab CS1305
Result:
Thus the program was executed successfully.
Department of Computer Science and Engineering
Network Lab CS1305
DATE: EX.NO: 4
AIM:
ALGORITHM:
Input:
Sample.txt
Hi this is sample program
Result:
Thus the program was executed successfully.
Department of Computer Science and Engineering
Network Lab CS1305
DATE: EX.NO: 5
AIM:
ALGORITHM:
Input:
Output:
Result:
DATE: EX.NO: 6
AIM:
To write a C program for simple chat application.
ALGORITHM:
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.
Department of Computer Science and Engineering
Network Lab CS1305
DATE: EX.NO: 7
AIM:
To write a C program to develop a DNS client server to resolve the given hostname.
ALGORITHM:
1. Create a new file. Enter the domain name and address in that file.
2. To establish the connection between client and server.
3. Compile and execute the program.
4. Enter the domain name as input.
5. The IP address corresponding to the domain name is display on the screen
6. Enter the IP address on the screen.
7. The domain name corresponding to the IP address is display on the screen.
8. Stop the program.
Input:
[root@localhost root]# ./a.out 172.16.6.187
Output:
Hostname: 172.16.6.187
Ip address:172.16.6.187
Result:
Thus the program was executed successfully
Department of Computer Science and Engineering
Network Lab CS1305
HTTP SERVER
DATE: EX.NO: 8
AIM:
ALGORITHM:
<html>
<title>sample</title>
<body>
<h1>welcome to my home page</h1>
</body>
</html>
Result:
Thus the program was executed successfully
Department of Computer Science and Engineering
Network Lab CS1305
NETWORK SIMULATOR
DATE: EX.NO: 9
AIM:
ALGORITHM:
Result:
Thus the program was executed successfully