You are on page 1of 122

CS2307 - Network Lab

1 of 107

EX NO A

BASIC NETWORKING COMMANDS

Ping ping sends an ICMP ECHO_REQUEST packet to the specified host. If the host responds, we get an ICMP packet back. We can ping an IP address to see if a machine is alive. If there is no response, we know something is wrong. ping, a very useful day-to-day command. It provides a very quick way to see if a machine is up and connected to the network. The basic syntax is: Example: Z:\> ping rmkcse

pathping Provides information about network latency and network loss at intermediate hops between a source and destination. pathping sends multiple Echo Request messages to each router between a source and destination over a period of time and then computes results based on the packets returned from each router. Example:

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab Z:\>pathping www.yahoo.com Tracing route to www-real.wa1.b.yahoo.com [209.131.36.158] over a maximum of 30 hops: 0 RMK0205.rmk.ac.in [10.2.1.205] 1 rmkec.rmk.ac.in [10.1.1.14] 2 121.240.153.1.static-chennai.vsnl.net.in [121.240.153.1] 3 121.240.156.78.static-chennai.vsnl.net.in [121.240.156.78] 4 202.54.65.86 5 59.163.16.130.static.vsnl.net.in [59.163.16.130] 6 if-11-0-2.mcore3.PDI-PaloAlto.as6453.net [64.86.84.129] 7 ix-11-0-1.mcore3.PDI-PaloAlto.as6453.net [64.86.84.146] 8 ae1-p140.msr1.sp1.yahoo.com [216.115.107.53] 9 te-9-1.bas-a1.sp1.yahoo.com [209.131.32.21] 10 f1.www.vip.sp1.yahoo.com [209.131.36.158] Computing statistics for 250 seconds... Source to Here This Node/Link Hop RTT 0 1 0ms 0/ 100 = 0% Lost/Sent = Pct Lost/Sent = Pct Address RMK0205.rmk.ac.in [10.2.1.205]0/ 100 = 0% |

2 of 107

0/ 100 = 0% rmkec.rmk.ac.in [10.1.1.14]0/ 100 = 0% | 0/ 100 = 0% 121.240.153.1.static-chennai.vsnl.net.in

2 0ms 0/ 100 = 0% [121.240.153.1] 0/ 100 = 0% | 3 8ms 0/ 100 = 0% [121.240.156.78] 0/ 100 = 0% | 4 7ms 0/ 100 = 0% 0/ 100 = 0%

0/ 100 = 0% 121.240.156.78.static-chennai.vsnl.net.in

0/ 100 = 0% 202.54.65.86 0/ 100 = 0% | 0/ 100 = 0% 59.163.16.130.static.vsnl.net.in [59.163.16.130]

5 260ms

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab 0/ 100 = 0% | 6 233ms 1/ 100 = 1% [64.86.84.129]

3 of 107

1/ 100 = 1% if-11-0-2.mcore3.PDI-PaloAlto.as6453.net

0/ 100 = 0% | 7 234ms 0/ 100 = 0% [64.86.84.146] 0/ 100 = 0% ix-11-0-1.mcore3.PDI-PaloAlto.as6453.net

0/ 100 = 0% | 8 --100/ 100 =100% [216.115.107.53] 0/ 100 = 0% | 9 234ms 0/ 100 = 0% 0/ 100 = 0% te-9-1.bas-a1.sp1.yahoo.com [209.131.32.21] 100/ 100 =100% ae1-p140.msr1.sp1.yahoo.com

0/ 100 = 0% | 10 234ms 0/ 100 = 0% 0/ 100 = 0% f1.www.vip.sp1.yahoo.com [209.131.36.158]

Trace complete. nslookup

The nslookup command can be used in Windows and Unix to find various details relating to the Domain Name System (DNS) like IP addresses of a particular computer.nslookup comes with a number of subcommands to help us to get more information from the specific dns servers. Example:
server NAME (where NAME is the name or ip address of the dns server we wish to

query). It is not always possible to query a specific dns server as often dns queries are blocked to prevent denial of service attacks. Using subcommands: Z:\>nslookup 204.228.150.3 Server: rmk.ac.in Address: 10.1.1.2 Name: www.computerhope.com

Address: 204.228.150.3

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

4 of 107

The first two lines are information about the server delivering the answer to the nslookup requested by the user. The next two lines tell the user the name and IP address of the machine being looked up. arp When we need an Ethernet (MAC) address we can use arp (address resolution protocol).In other words it shows the physical address of a host. Example: Z:\>arp -a Interface: 10.2.1.205 --- 0x10003 Internet Address 10.1.1.2 10.1.1.4 10.1.1.5 10.2.1.201 Physical Address 00-04-23-dc-dd-d4 00-15-17-53-53-59 00-02-b3-50-69-18 00-16-76-87-01-0d Type dynamic dynamic dynamic dynamic

netstat The netstat command is used to display the TCP/IP network protocol statistics and information (Shows network status).The netstat command symbolically displays the contents of various network-related data structures for active connections. The default display for active sockets shows the following items: Local and remote addresses Send and receive queue sizes (in bytes) Protocol Internal state of the protocol Example: Z:\>netstat Active Connections Proto Local Address Foreign Address State

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab TCP TCP TCP TCP TCP TCP TCP TCP RMK0205:1045 RMK0205:1068 RMK0205:1074 RMK0205:1525 RMK0205:1047 RMK0205:1048 RMK0205:1078 RMK0205:2002 proxy.rmk.ac.in:3128 ESTABLISHED rmk.ac.in:microsoft-ds ESTABLISHED proxy.rmk.ac.in:3128 CLOSE_WAIT rmk.ac.in:microsoft-ds TIME_WAIT localhost:1048 localhost:1047 localhost:2002 localhost:1078 ESTABLISHED ESTABLISHED ESTABLISHED ESTABLISHED

5 of 107

ipconfig ipconfig (internet protocol configuration) is a DOS utility which can be used from MSDOS and a MS-DOS shell to display the network settings currently assigned and given by a network. This command can be utilized to verify a network connection as well as to verify your network settings. Example: Z:\>ipconfig Windows IP Configuration Ethernet adapter Local Area Connection: Connection-specific DNS Suffix . : rmk.ac.in IP Address. . . . . . . . . . . . : 10.2.1.205 Subnet Mask . . . . . . . . . . . : 255.0.0.0 Default Gateway . . . . . . . . . : 10.1.1.4

hostname Tells the user the host name of the computer they are logged into. Note: may be called host.

Example:

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab Z:\>hostname RMK0205 dig(Try using Linux)

6 of 107

The "domain information groper" tool. More advanced then host... If you give a hostname as an argument to output information about that host, including it's IP address, hostname and various other information.To look up information about www.yahoo.com:

Example: [vijay@linux ~]$ dig www.yahoo.com ; <<>> DiG 9.2.4 <<>> www.yahoo.com ;; global options: printcmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 57213 ;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 0 ;; QUESTION SECTION: ;www.yahoo.com. ;; ANSWER SECTION: www.yahoo.com. 133 36 IN IN IN CNAME www.wa1.b.yahoo.com. CNAME www-real.wa1.b.yahoo.com. A 209.131.36.158 IN A

www.wa1.b.yahoo.com.

www-real.wa1.b.yahoo.com. 36 ;; Query time: 4 msec ;; SERVER: 10.1.1.2#53(10.1.1.2)

;; WHEN: Wed Dec 3 10:47:18 2008 ;; MSG SIZE rcvd: 94 tracert traceroute will show the route of a packet. It attempts to list the series of hosts through which your packets travel on their way to a given destination. Example:

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab Z:\>tracert Usage: tracert [-d] [-h maximum_hops] [-j host-list] [-w timeout] target_name Options: -d Do not resolve addresses to hostnames. Maximum number of hops to search for target.

7 of 107

-h maximum_hops -j host-list

Loose source route along host-list.

Z:\>tracert www.yahoo.com Tracing route to www-real.wa1.b.yahoo.com [209.131.36.158] over a maximum of 30 hops: 1 2 3 4 <1 ms <1 ms 6 ms 54 ms <1 ms <1 ms 7 ms 18 ms <1 ms rmkec.rmk.ac.in [10.1.1.14] <1 ms 121.240.153.1.static-chennai.vsnl.net.in [121.240.153.1] 4 ms 121.240.156.78.static-chennai.vsnl.net.in [121.240.156.78] 26 ms 202.54.65.86

5 290 ms 274 ms 249 ms 59.163.16.130.static.vsnl.net.in [59.163.16.130] 6 295 ms 233 ms 269 ms if-11-0-2.mcore3.PDI-PaloAlto.as6453.net [64.86.84.129] 7 298 ms 234 ms 262 ms ix-11-0-1.mcore3.PDI-PaloAlto.as6453.net [64.86.84.146] 8 322 ms 259 ms 250 ms ae0-p150.msr2.sp1.yahoo.com [216.115.107.73] 9 231 ms 238 ms 265 ms te-9-1.bas-a2.sp1.yahoo.com [209.131.32.23] 10 248 ms 243 ms 238 ms f1.www.vip.sp1.yahoo.com [209.131.36.158] Trace complete. finger

Displays information about a user on a specified system running the Finger service. Output varies based on the remote system.

FINGER [-l] [user]@host [...]

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab -l user Displays information in long list format. Specifies the user you want information about. Omit the user parameter to display information about all users on the specifed host. @host Specifies the server on the remote system whose users you

8 of 107

want information about.

df Display filesystem information Most common use: df -h Great way to keep tabs on how much hard disk space you have on each mounted file system.

du Display usage Most common use, under a specific directory: du -a Easily and quickly identify the size of files/programs in certain directories. A word of caution is that you should not run this command from the / directory. It will actually display size for every file on the entire Linux harddisk.

find Find locations of files/directories quickly across entire filesystem Most common use: find / -name appname -type d -xdev ps Lists all existing processes on the server Most common uses: ps and also ps -A |more

top

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab Displays many system statistics and details regarding active processes Most common use: top

9 of 107

traceroute Traces the existing network routing for a remote or local server Most common use: traceroute hostname (replace hostname with the name of your server such as reallylinux.com) w An extension of the who command that displays details of all users currently on the server Most common uses: w

who Tool used to monitor who is on the system and many other server related characteristics Most common uses: who and also who -q and also who -b The plain command just lists the names of users currently on the server. Using the -q option allows you to quickly view just the total number of users on the system. Using the -b option reminds you how long it has been since you rebooted that stable Linux server! One of my servers had a -b of almost three years! Yes, that's really Linux!

EX NO B

INTRODUCTION TO SOCKET PROGRAMMING

Network Programming Network programming involves writing programs that communicate with other programs across a computer N/W. One program is normally called the client, and the other the server.
R.M.K Engineering College Department of CSE

CS2307 - Network Lab

10 of 107

Common examples in the TCP/IP are web clients (browsers) & Web Servers, FTP clients & server and Telnet clients & servers. To facilitate communication between unrelated processes, and to standardize network programming, an API is needed. There are two such APIs: 1. Sockets, sometimes called Berkeley Sockets 2. XTI (X/open transport interface)

Socket In TCP/IP, an addressable point that consists of an IP address and a TCP or UDP port member that provides application with access to TCP/IP protocol is called Socket. A socket is an abstraction that represents an endpoint of communication. The operations that can be performed on a socket include control operations (such as associating a port number with the socket, initiating or accepting a connection on the socket, or destroying the socket), data transfer operations (such as writing data through the socket to some other application, or reading data from some other application through the socket) and status operations (such as finding the IP address associated with the socket). The complete set of operations that can be performed on a socket constitutes the Sockets API (Application Programming Interface).

Structures Structures are used in socket programming to hold information about the address. The generic socket address structure is defined below: struct sockaddr { unsigned short sa_family; char sa_data[14]; }; /* address family */ /* 14 bytes of protocol address*/

IPv4 Socket Address Structure This structure is also called as Internet socket address structure. It is defined by including the <netinet/in.h> header. struct in_addr { in_addr_t s_addr; /* 32-bit IPv4 address, network byte ordered */

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab }; struct sockaddr_in{ unit8_t sa_family_t in_port_t sin_len; sin_family; sin_port; /* length of structure (16 byte) */ /*AF_INET*/ /* 16-bit TCP or UDP port number */ /* network byte ordered */ struct in_addr sin_addr; char }; sin_zero[8];

11 of 107

/*32-bit Ipv4 address, network byte ordered */ /* unused initialize to all zeroes */

Important functions 1.socket() This function is called by both TCP server and client process to create an empty socket. #include <sys/socket.h> int socket (int family, int type, int protocol);

family: specifies the protocol family and is one of the constants below: Family AF_INET AF_INET6 AF_LOCAL AF_ROUTE AF_KEY description IPv4 protocols IPv6 protocols Unix domain protocols Routing sockets Key sockets

type: indicates communications semantics SOCK_STREAM - stream socket SOCK_DGRAM - datagram socket

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab SOCK_RAW - raw socket protocol: set to 0 except for raw sockets.

12 of 107

Returns on success: socket descriptor (a small nonnegative integer), on error: -1

2. bind() The bind function assigns a local protocol address to a socket. The protocol address is the combination of either a 32-bit IPV4 address or a 128-bit IPV6 address, along with a 16-bit TCP or UDP port number. #include <sys/socket.h> int bind(int sockfd, const struct sockaddr *myaddr, socklen_t addrlen);

sockfd: a socket descriptor returned by the socket function. *myaddr: a pointer to a protocol-specific address. addrlen: the size of the socket address structure.

Returns on success: 0, on error: -1 3. connect() The connect function is used by a TCP client to establish a connection with a TCP server. #include <sys/socket.h> int connect(int sockfd, const struct sockaddr *servaddr, socklen_t addrlen);

sockfd: a socket descriptor returned by the socket function *servaddr: a pointer to a socket address structure addrlen: the size of the socket address structure

Returns on success: 0, on error: -1

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab 4. listen()

13 of 107

The listen function is called only by a TCP server to converts an unconnected socket into a passive socket, indicating that kernel should accept incoming connection requests directed to its socket. #include<sys/socket.h> int listen (int sockfd, int backlog);

sockfd: a socket descriptor returned by the socket function. backlog: maximum number of connections that the kernel should queue for this socket.

Returns on success: 0, on error: -1

5. accept() The accept function is called by the TCP server to return the next completed connection from the front of the completed connection queue. #include<sys/socket.h> int accept (int sockfd, struct sockaddr *cliaddr, socklen_t *addrlen);

sockfd: This is the same socket descriptor as in listen call. *cliaddr: used to return the protocol address of the connected peer process *addrlen: length of the address.

Returns on success: a new (connected)socket descriptor, on error:-1

6. close() The close function is used to close a socket and terminate a TCP connection. #include <unistd.h> int close (int sockfd);

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab sockfd: This socket descriptor is no longer useable. Returns on success: 0, on error: -1 7. read() The read function is used to receive data from the specified socket. #include <unistd.h> ssize_t read(int sockfd, const void * buf, size_t nbytes);

14 of 107

sockfd: a socket descriptor returned by the socket function. buf: buffer to store the data. nbytes: size of the buffer

Returns: number of bytes read if OK,0 on EOF, -1 on error

8. write() The write function is used to send the data through the specified socket. #include <unistd.h> ssize_t write(int sockfd, const void * buf, size_t nbytes);

sockfd: a socket descriptor returned by the socket function. buf: buffer to store the data. nbytes: size of the buffer

Returns: number of bytes written if OK,0 on EOF, -1 on error

9. sendto() This function is similar to the write function, but additional arguments are required. #include<sys/socket.h>

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab ssize_t sendto(int sockfd, const void *buff, size_t nbyte, int flag, const struct sockaddr *to, socklen_t addrlen); sockfd socket descriptor *buff pointer to buffer to write from. nbytes number of bytes to write.

15 of 107

to socket address structure containing the protocol address of where the data is to be sent. addrlen size of the socket address structure

Returns: number of bytes read or written if OK,-1 on error

10. recvfrom() This function is similar to the read function, but additional arguments are required. #include<sys/socket.h> ssize_t recvfrom(int sockfd, void *buff, size_t nbyte, int flag, struct sockaddr *from, socklen_t *addrlen);

sockfd socket descriptor *buff pointer to buffer to read. nbytes number of bytes to read. addrlen size of the socket address structure from - socket address structure of who sent the datagram.

Returns: number of bytes read or written if OK,-1 on error

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

16 of 107

Socket functions for connection-oriented communication


TCP Server socket()

bind()

listen()

TCP Client socket() Connection establishment data ( request) write()

accept()

blocks until connection from client

conect()

read()

read()

process request data ( reply) write()

close()

EOF notification

read()

close()

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab Socket functions for connection-less communication

17 of 107

UDP Server socket()

bind() UDP Client socket() recvfrom()

sendto()

Data (request)

Blocks until datagram received from a client Process request sendto()

Data (reply) recvfrom()

close()

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab EX NO 1 Aim To write a program in C to implement TCP Daytime Client Server. Algorithm TCP Daytime client-server

18 of 107

Server 1. A TCP socket is created. 2. An Internet socket address structure is filled in with the wildcard address (INADDR_ANY) and the servers well-known port (PORT). 3. The socket is converted into a listening socket by calling the listen function. 4. The server blocks in the call to accept, waiting for the client connection to complete. 5. The server retrieves the current date and time using the library function time() and it converts the retrieved value to human readable string using the library function ctime(). 6. The server sends the date and time to the client using writen and it closes the connected socket. Client: 1. A TCP socket is created. 2. An Internet socket address structure is filled in with the servers IP address and the same port number. 3. The connect function establishes the connection with the server. 4. The client receives the date and time from the server using readn and it displays it to the standard output. SERVER //tcpd.c -- TCP DAYTIME SERVER

#include<stdio.h> #include<sys/types.h> #include<netinet/in.h> #include<sys/socket.h> #include<string.h> #include<unistd.h> #include<sys/time.h>


R.M.K Engineering College Department of CSE

CS2307 - Network Lab #define PORT 7784

19 of 107

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

time_t seconds; char buffer[30]; int sockfd,a,connfd,len; struct sockaddr_in servaddr,cliaddr;

sockfd=socket(AF_INET,SOCK_STREAM,0); if(sockfd==-1) printf("Error creating Socket\n"); bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family=AF_INET; servaddr.sin_port=htons(PORT); servaddr.sin_addr.s_addr=htonl(INADDR_ANY); bind(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr)); if((a=listen(sockfd,5))<0) printf("Error in Listen Function"); while(1) { len=sizeof(cliaddr); if((connfd=accept(sockfd,(struct sockaddr*)&cliaddr,&len))<0) printf("Error in accept"); seconds=time(NULL); strcpy(buffer,"");

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab sprintf(buffer,"%s\n",ctime(&seconds)); write(connfd,buffer,sizeof(buffer)); close(connfd); } }

20 of 107

CLIENT //tcpdcli.c -- TCP DAYTIME CLIENT

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

int main(int argc,char *argv[]) { int sockfd;

struct sockaddr_in serv; char buff[30];

sockfd=socket(AF_INET,SOCK_STREAM,0); memset(&serv,0,sizeof(serv));

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab serv.sin_family=AF_INET; serv.sin_port=htons(PORT); serv.sin_addr.s_addr=inet_addr(argv[1]); if(connect(sockfd,(struct sockaddr *)&serv,sizeof(serv))<0) printf("Error in Connect"); strcpy(buff,""); read(sockfd,buff,sizeof(buff)); fputs(buff,stdout); close(sockfd); }

21 of 107

OUTPUT:

SERVER

rmk@rmk-desktop:~/NPM$ cc tcpd.c rmk@rmk-desktop:~/NPM$ ./a.out

CLIENT

rmk@rmk-desktop:~/NPM$ cc tcpdcli.c rmk@rmk-desktop:~/NPM$ ./a.out 127.0.0.1 Thu Dec 23 15:33:21 2010 rmk@rmk-desktop:~/NPM$

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

22 of 107

EX NO 2 Aim

TCP echo client-server (Iterative model)

To write a program in C to implement TCP Echo Client Server (Iterative model). Algorithm

Server 7. A TCP socket is created. 8. An Internet socket address structure is filled in with the wildcard address (INADDR_ANY) and the servers well-known port (PORT). 9. The socket is converted into a listening socket by calling the listen function. 10. The server blocks in the call to accept, waiting for the client connection to complete. 11. When the connection is established, the server reads the line from the client using readn and echoes it back to the client using writen. 12. Finally, the server closes the connected socket. Client: 1. A TCP socket is created.

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

23 of 107

2. An Internet socket address structure is filled in with the servers IP address and the same port number. 3. The connect function establishes the connection with the server. 4. The client reads a line of text from the standard input using fgets, writes it to the server using writen, reads back the servers echo of the line using readline and outputs the echoed line to the standard output using fputs.

PROGRAM SERVER //iterserv.c -- Iterative Echo Server #include<stdio.h> #include<sys/types.h> #include<netinet/in.h> #include<sys/socket.h> #include<string.h> #include<unistd.h>

#define PORT 7676

int main(int argc, char *argv[]) { char buffer[20]; int sockfd,connfd,a,len;

struct sockaddr_in servaddr,cliaddr; sockfd=socket(AF_INET,SOCK_STREAM,0);

if(sockfd==-1) printf("ERROR CREATING SOCKET!");


R.M.K Engineering College Department of CSE

CS2307 - Network Lab

24 of 107

bzero(&servaddr,sizeof(servaddr));

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

bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));

if((a=listen(sockfd,5))<0) printf("ERROR IN LISTEN FUNCTION!");

while(1) { len=sizeof(cliaddr); connfd=accept(sockfd,(struct sockaddr*)&cliaddr,&len); strcpy(buffer,""); read(connfd,buffer,10); printf("Message Received and Echoed : %s",buffer); write(connfd,buffer,sizeof(buffer)); } close(sockfd); }

CLIENT //itercli.c -- Echo client #include<stdio.h>

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab #include<sys/types.h> #include<netinet/in.h> #include<sys/socket.h> #include<arpa/inet.h> #include<string.h> #include<unistd.h>

25 of 107

#define PORT 7676

int main(int argc,char *argv[]) { int sockfd; struct sockaddr_in serv; char buff[20];

sockfd=socket(AF_INET,SOCK_STREAM,0);

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

serv.sin_family=AF_INET; serv.sin_port=htons(PORT); serv.sin_addr.s_addr=inet_addr(argv[1]);

if(connect(sockfd,(struct sockaddr *)&serv,sizeof(serv))<0) printf("ERROR IN CONNECT");

printf("ENTER THE STRING TO ECHO :");

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab fgets(buff,sizeof(buff),stdin);

26 of 107

write(sockfd,buff,sizeof(buff)); strcpy(buff," "); read(sockfd,buff,sizeof(buff));

fputs(buff,stdout);

close(sockfd);

return; }

//OUTPUT: //SERVER rmk@rmk-desktop:~/NWLAB/ITERATIVE$ cc iterserv.c rmk@rmk-desktop:~/NWLAB/ITERATIVE$ ./a.out Message Received and Echoed : Good

//CLIENT rmk@rmk-desktop:~/NWLAB/ITERATIVE$ cc itercli.c rmk@rmk-desktop:~/NWLAB/ITERATIVE$ ./a.out 127.0.0.1 ENTER THE STRING TO ECHO :Good Good rmk@rmk-desktop:~/NWLAB/ITERATIVE$

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

27 of 107

EX NO 3 Aim

TCP echo client-server (Concurrent model)

To write a program in C to implement TCP Echo Client Server (Concurrent model).

Algorithm Server 13. A TCP socket is created. 14. An Internet socket address structure is filled in with the wildcard address (INADDR_ANY) and the servers well-known port (PORT). 15. The socket is converted into a listening socket by calling the listen function. 16. The server blocks in the call to accept, waiting for the client connection to complete. 17. For each client, a child is created using fork and the child handles the new client. 18. The child closes the listening socket, reads the line from the client using readn and echoes it back to the client using writen. 19. Finally, the parent closes the connected socket. Client: 1. A TCP socket is created. 2. An Internet socket address structure is filled in with the servers IP address and the same port number. 3. The connect function establishes the connection with the server. 4. The client reads a line of text from the standard input using fgets, writes it to the server using writen, reads back the servers echo of the line using readline and outputs the echoed line to the standard output using fputs.

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

28 of 107

PROGRAM

SERVER //conserv.c -- Concurrent Echo server using fork() #include<stdio.h> #include<sys/types.h> #include<netinet/in.h> #include<sys/socket.h> #include<string.h> #include<unistd.h> #define PORT 7688 int main(int argc, char *argv[]) { char buffer[20]; int sockfd,connfd,a,len; int pid; struct sockaddr_in servaddr,cliaddr; sockfd=socket(AF_INET,SOCK_STREAM,0);

if(sockfd==-1) printf("ERROR CREATING SOCKET!");

bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family=AF_INET; servaddr.sin_port=htons(PORT); servaddr.sin_addr.s_addr=htonl(INADDR_ANY);

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));

29 of 107

if((a=listen(sockfd,5))<0) printf("ERROR IN LISTEN FUNCTION!");

while(1) { len=sizeof(cliaddr);

if((connfd=accept(sockfd,(struct sockaddr*)&cliaddr,&len))<0) printf("ERROR IN ACCEPT"); if((pid=fork())==0) { close(sockfd); strcpy(buffer,""); read(connfd,buffer,10); printf("Message Received and Echoed : %s",buffer); write(connfd,buffer,sizeof(buffer)); exit(0); } close(connfd); } }

CLIENT //concli.c - Echo client #include<stdio.h> #include<sys/types.h>

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab #include<netinet/in.h> #include<sys/socket.h> #include<arpa/inet.h> #include<string.h> #include<unistd.h> #define PORT 7688 int main(int argc,char *argv[]) { int sockfd; struct sockaddr_in serv; char buff[20]; sockfd=socket(AF_INET,SOCK_STREAM,0);

30 of 107

memset(&serv,0,sizeof(serv)); serv.sin_family=AF_INET; serv.sin_port=htons(PORT); serv.sin_addr.s_addr=inet_addr(argv[1]);

if(connect(sockfd,(struct sockaddr *)&serv,sizeof(serv))<0) printf("ERROR IN CONNECT");

printf("ENTER THE STRING TO ECHO :"); fgets(buff,sizeof(buff),stdin); write(sockfd,buff,sizeof(buff)); strcpy(buff," "); read(sockfd,buff,sizeof(buff)); fputs(buff,stdout);

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab close(sockfd); return; } OUTPUT

31 of 107

rmk@rmk-desktop:~/NWLAB/CONCURRENT$ cc conserv.c rmk@rmk-desktop:~/NWLAB/CONCURRENT$ ./a.out Message Received and Echoed : Hello Message Received and Echoed : Bye ^Z [5]+ Stopped ./a.out

rmk@rmk-desktop:~/NWLAB/CONCURRENT$ //client 1 rmk@rmk-desktop:~/NWLAB/CONCURRENT$ cc concli.c rmk@rmk-desktop:~/NWLAB/CONCURRENT$ ./a.out 127.0.0.1 ENTER THE STRING TO ECHO :Hello Hello rmk@rmk-desktop:~/NWLAB/CONCURRENT$ //client 2 rmk@rmk-desktop:~/NWLAB/CONCURRENT$ cc concli.c rmk@rmk-desktop:~/NWLAB/CONCURRENT$ ./a.out 127.0.0.1 ENTER THE STRING TO ECHO :Bye Bye rmk@rmk-desktop:~/NWLAB/CONCURRENT$

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

32 of 107

Ex No : 4 Aim

CHAT APPLICATION USING TCP SOCKETS

To perform the full duplex chat by sending and receiving the message from the client to server and vice versa using TCP sockets.

Algorithm Server 1. A TCP socket is created. 2. An Internet socket address structure is filled in with the wildcard address (INADDR_ANY) and the servers well-known port (PORT). 3. The socket is converted into a listening socket by calling the listen function. 4. The server blocks in the call to accept, waiting for the client connection to complete. 5. When the connection is established, the server reads the line from the client using connected socket and display the message in the standard output using fputs. 6. Then again the server reads a line of text from the standard input and writes it back to the client through the connected socket. 7. The server went through the steps (5) and (6) until it receives 'bye' either from the standard input or client. 8. Finally, the server closes the connected socket. Client: 1. A TCP socket is created. 2. An Internet socket address structure is filled in with the servers IP address and the same port number. 3. The connect function establishes the connection with the server. 4. When the connection is established, the client reads the line from the standard input using fgets and send the message to the server through the socket. 5. Then again the client reads a line of text from the server through the connected socket and writes it back to the standard output using fputs. 6. The client went through the steps (4) and (5) until it receives 'bye' either from the standard input or server. 7. Finally, the client closes the connected socket. PROGRAM

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab SERVER //tcpchatser.c -- TCP CHAT SERVER #include<stdio.h> #include<sys/types.h> #include<netinet/in.h> #include<sys/socket.h> #include<string.h> #include<unistd.h> #include<stdlib.h> #define PORT 4771

33 of 107

int main(int argc,char *argv[]) { char buffer[100]; int sockfd,a,connfd,len,i=0; pid_t pid; struct sockaddr_in servaddr,cliaddr; sockfd=socket(AF_INET,SOCK_STREAM,0); if(sockfd==-1) { printf("Error creating socket\n"); exit(0); } printf("Server Socket Created Successfully.\n"); bzero((struct sockaddr *)&servaddr,sizeof(servaddr)); servaddr.sin_family=AF_INET; servaddr.sin_port=htons(PORT);

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab servaddr.sin_addr.s_addr=htonl(INADDR_ANY);

34 of 107

if(bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr))<0) { printf("Error in BIND function"); exit(0); } printf("Server Socket Binded.\n"); if((a=listen(sockfd,5))==-1) { printf("Error in LISTEN function"); exit(0); } printf("Server Socket Listened...\n"); len=sizeof(cliaddr); if((connfd=accept(sockfd,(struct sockaddr *)&cliaddr,&len))<0) { printf("Error in ACCEPT"); exit(0); } do { strcpy(buffer," "); read(connfd,buffer,100); printf("From client :%s",buffer); if(strcmp(buffer,"bye\n")==0) {

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab printf("from Client: %s",buffer); goto stop; } printf("Server :"); fgets(buffer,sizeof(buffer),stdin); write(connfd,buffer,100); }while(strcmp(buffer,"bye\n")!=0); stop: exit(0); close(connfd); return 0; }

35 of 107

CLIENT //tcpchatcli.c -- TCP CHAT CLIENT #include<stdio.h> #include<sys/types.h> #include<netinet/in.h> #include<sys/socket.h> #include<arpa/inet.h> #include<string.h> #include<unistd.h> #include<stdlib.h> #define PORT 4771

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

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab int sockfd; struct sockaddr_in serv; char buff[100]; sockfd=socket(AF_INET,SOCK_STREAM,0); printf("Client Socket Created Successfully.\n"); memset(&serv,0,sizeof(serv)); serv.sin_family=AF_INET; serv.sin_port=htons(PORT); serv.sin_addr.s_addr=inet_addr(argv[1]); if (connect(sockfd,(struct sockaddr *)&serv, sizeof(serv))<0) { printf("error in connect"); exit(0); } printf("Client Socket with Server Successfully.\n"); do { strcpy(buff," "); printf("Client. :"); fgets(buff,100,stdin); write(sockfd,buff,100); if(strcmp(buff,"bye\n")==0) { printf("Client: %s",buff); goto stop; } strcpy(buff," ");

36 of 107

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab read(sockfd,buff,sizeof(buff)); printf("From Server :%s\n",buff); }while(strcmp(buff,"bye\n")!=0); stop: exit(0); close(sockfd); return 0; } OUTPUT //Server rmk@rmk-desktop:~/NWLAB/ITERATIVE$ cd .. rmk@rmk-desktop:~/NWLAB$ cd TCPCHAT rmk@rmk-desktop:~/NWLAB/TCPCHAT$ cc tcpchatser.c rmk@rmk-desktop:~/NWLAB/TCPCHAT$ ./a.out Server Socket Created Successfully. Server Socket Binded. Server Socket Listened... From client :Hello Server :Hi ..How are you? From client :Fine. How Are You? Server :Fine From client :Bye Server :bye rmk@rmk-desktop:~/NWLAB/TCPCHAT$

37 of 107

//Client rmk@rmk-desktop:~/NWLAB/TCPCHAT$ cc tcpchatcli.c

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab rmk@rmk-desktop:~/NWLAB/TCPCHAT$ ./a.out 127.0.0.1 Client Socket Created Successfully. Client Socket with Server Successfully. Client. :Hello From Server :Hi ..How are you? Client. :Fine. How Are You? From Server :Fine Client. :Bye From Server :bye rmk@rmk-desktop:~/NWLAB/TCPCHAT$

38 of 107

Ex No : 5 Aim

CHAT APPLICATION USING UDP SOCKETS

To perform the full duplex chat by sending and receiving the message from the client to server and vice versa using UDP sockets.

Algorithm Server 1. A UDP socket is created by specifying the second argument to socket as SOCK_DGRAM. The IPv4 address for the bind is specified as INADDR_ANY and the servers wellknown port is the constant SERV_PORT. The server blocks in the call to recvfrom, waiting to receive the datagram from the client. (ie.connection initiation in UDP). The server display the message received from client in the standard output using fputs. Then again the server reads a line of text from the standard input and writes it back to the client using sendto. The server went through the steps (3) and (4) until it receives 'bye' either from the standard input or client. Finally, the server closes the socket.

2. 3. 4. 5. 6.

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab Client: 2. 3. 4. 5. 6.

39 of 107

1. A UDP socket is created. An Internet socket address structure is filled in with the servers IP address and the same port number. The client reads a line of text from the standard input using fgets, writes it to the server using sendto. The client reads a line of text from the server using recvfrom and writes it back to the standard output using fputs. The client went through the steps (3) and (4) until it receives 'bye' either from the standard input or server. Finally, the client closes the connected socket.

PROGRAM SERVER //udpchatser.c --UDP CHAT SERVER #include<stdio.h> #include<sys/types.h> #include<netinet/in.h> #include<sys/socket.h> #include<string.h> #include<unistd.h> #include<stdlib.h> #define PORT 7844 int main(int argc,char *argv[]) { char msg[2000]; int sockfd,len,val; struct sockaddr_in servaddr,cliaddr; sockfd=socket(AF_INET,SOCK_DGRAM,0); printf("UDP Server Socket Created Successfully.\n"); if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0) { printf("Error creating socket\n"); exit(0); } bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family=AF_INET; servaddr.sin_port=htons(PORT); servaddr.sin_addr.s_addr=htonl(INADDR_ANY); if(bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr))<0) {

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab perror("Error binding socket."); exit(0); } printf("UDP Server Socket Binded.\n"); len=sizeof(cliaddr); do { strcpy(msg," "); if((val=recvfrom(sockfd,msg,sizeof(msg),0, (struct sockaddr *)&cliaddr,&len))<0) { perror("ERROR"); exit(0); } printf("From Client : %s",msg); if(strcmp(msg,"bye\n")==0) { goto stop; } printf("Server :"); fgets(msg,sizeof(msg),stdin); if((sendto(sockfd,msg,val,0,(struct sockaddr *)&cliaddr,len))<0) { perror("NOTHING SEND"); exit(0); } }while(strcmp(msg,"bye\n")!=0); stop: exit(0); close(sockfd); return 0; } CLIENT //udpchatcli.c -- UDP CHAT CLIENT #include<stdio.h> #include<sys/types.h> #include<netinet/in.h> #include<sys/socket.h> #include<arpa/inet.h> #include<string.h> #include<unistd.h> #include<stdlib.h> #define PORT 7844

40 of 107

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

41 of 107

int main(int argc,char *argv[]) { int sockfd,len; struct sockaddr_in serv,cliaddr; char msg[2000]; if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0) { perror("ERROR creating socket"); exit(0); } printf("UDP Client Socket Created Successfully.\n"); memset(&serv,0,sizeof(serv)); serv.sin_family=AF_INET; serv.sin_port=htons(PORT); serv.sin_addr.s_addr=inet_addr(argv[1]); do { printf("Client :"); fgets(msg,sizeof(msg),stdin); if((sendto(sockfd,msg,sizeof(msg),0,(struct sockaddr *)&serv,sizeof(serv)))<0) { perror("ERROR IN SENDTO"); goto stop; } if(strcmp(msg,"bye\n")==0) { goto stop; } strcpy(msg," "); if((recvfrom(sockfd,msg,sizeof(msg),0, (struct sockaddr *)&cliaddr,&len))<0) { perror("ERROR IN RECVFROM"); goto stop; } fputs("Server : ",stdout); fputs(msg,stdout); }while(strcmp(msg,"bye\n")!=0); stop: exit(0); close(sockfd); return 0; } OUTPUT //SERVER rmk@rmk-desktop:~/NWLAB/UDPCHAT$ cc udpchatser.c

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab rmk@rmk-desktop:~/NWLAB/UDPCHAT$ rmk@rmk-desktop:~/NWLAB/UDPCHAT$ ./a.out UDP Server Socket Created Successfully. UDP Server Socket Binded. From Client : Good Morning Server :yes. ...good morning From Client : bye //CLIENT rmk@rmk-desktop:~/NWLAB/UDPCHAT$ cc udpchatcli.c rmk@rmk-desktop:~/NWLAB/UDPCHAT$ ./a.out 127.0.0.1 UDP Client Socket Created Successfully. Client :Good Morning Server : yes. ...good morning Client :bye rmk@rmk-desktop:~/NWLAB/UDPCHAT$

42 of 107

EX NO 6 Aim

SIMULATION OF DOMAIN NAME SYSTEM

To write a program in C to simulate the Domain Name System. Algorithm Server 1. A TCP socket is created. 2. An Internet socket address structure is filled in with the wildcard address (INADDR_ANY) and the servers well-known port (PORT). 3. The socket is converted into a listening socket by calling the listen function. 4. The server blocks in the call to accept, waiting for the client connection to complete. 5. When the connection is established, the server reads the domain name from the client using readn. 6. It then finds out the corresponding address using gethostbyname() and sends it back to the client using writen.

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab 7. Finally, the server closes the connected socket.

43 of 107

Client: 1. A TCP socket is created. 2. An Internet socket address structure is filled in with the servers IP address and the same port number. 3. The connect function establishes the connection with the server. 4. The client reads the domain name from the standard input using fgets, writes it to the server using writen. 5. It then reads back the server reply (IP address) using readline and outputs the same to the standard output using fputs. PROGRAM SERVER //DNSServer.c -- DNS SERVER TO RESOLVE IP ADDRESS OF A HOST #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<stdio.h> #include<string.h> #include<stdlib.h> #include<netdb.h> #define SA struct sockaddr #define PORT 7882 int main() { int listenfd,connfd; socklen_t len; struct sockaddr_in servaddr,cliaddr; struct hostent *hp; char host[100],buff[200]; printf("DNS SERVER...\n"); listenfd=socket(AF_INET,SOCK_STREAM,0); printf("DNS Server Started\n"); bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family=AF_INET; servaddr.sin_port=htons(PORT); servaddr.sin_addr.s_addr=htonl(INADDR_ANY); bind(listenfd,(SA *)&servaddr,sizeof(servaddr)); listen(listenfd,10); for(;;) { len=sizeof(cliaddr); connfd=accept(listenfd,(SA *)&cliaddr,&len); read(connfd,host,sizeof(host));

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab printf("%s\n",host); if((hp=gethostbyname(host))==NULL) printf("Cannot get address\n"); inet_ntop(AF_INET,hp->h_addr,buff,sizeof(buff)); printf("\nHOST : %s --> IP ADDRESS --> %s",host,buff); printf("\n1"); write(connfd,buff,sizeof(buff)); close(connfd); } return 0; } CLIENT //DNSClient.c -- DNS CLIENT #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<stdio.h> #include<string.h> #include<stdlib.h> #include<netdb.h> #define SA struct sockaddr #define PORT 7882 int main(int argc,char **argv) { socklen_t len; struct sockaddr_in servaddr; char buff[200],host[100]; int sockfd; sockfd=socket(AF_INET,SOCK_STREAM,0); bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family=AF_INET; servaddr.sin_port=htons(PORT); servaddr.sin_addr.s_addr=inet_addr("127.0.0.1"); if(connect(sockfd,(SA *)&servaddr,sizeof(servaddr))<0) printf("Connect error"); printf("Enter the domain name"); scanf("%s",host); write(sockfd,host,sizeof(host)); if(read(sockfd,buff,sizeof(buff))<0) printf("Read error"); printf("\nThe host address is %s\n",buff); return 0;

44 of 107

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab } OUTPUT: SERVER angai@angai-desktop:~/NWLAB/DNS$ cc DNSServer.c angai@angai-desktop:~/NWLAB/DNS$ ./a.out SERVER... Server Started www.google.com HOST : www.google.com --> IP ADDRESS --> 74.125.71.105 www.rmkec.ac.in HOST : www.rmkec.ac.in --> IP ADDRESS --> 173.193.3.233 CLIENT angai@angai-desktop:~/NWLAB/DNS$ cc DNSClient.c angai@angai-desktop:~/NWLAB/DNS$ ./a.out 127.0.0.1 Enter the domain namewww.google.com The host address is 74.125.71.105 angai@angai-desktop:~/NWLAB/DNS$ ./a.out 127.0.0.1 Enter the domain namewww.rmkec.ac.in The host address is 173.193.3.233 angai@angai-desktop:~/NWLAB/DNS$

45 of 107

EX NO 7

SIMUALTION OF SLIDING WINDOW PROTOCOL

Aim To write a program in C to simulate the Sliding Window Protocol. Algorithm Server 1. A TCP socket is created. 2. An Internet socket address structure is filled in with the wildcard address (INADDR_ANY) and the servers well-known port (PORT). 3. The socket is converted into a listening socket by calling the listen function.
R.M.K Engineering College Department of CSE

CS2307 - Network Lab

46 of 107

4. The server blocks in the call to accept, waiting for the client connection to complete. 5. When the connection is established, the server reads the source file name (which is to be transferred) from the client using readn. 6. Then the contents of the source file are transferred byte by byte (assuming the window size is 1) to the client. 7. Finally, the server closes the connected socket. Client: 1. A TCP socket is created. 2. An Internet socket address structure is filled in with the servers IP address and the same port number. 3. The connect function establishes the connection with the server. 4. The client reads a source file name and the destination file name from the user, sends the source file name to the server using writen. 5. It then receives the byte by byte content of the file from the server and displays it. PROGRAM SERVER //slidingser.c -- SERVER #include<sys/socket.h> #include<netinet/in.h> #include<netdb.h> #include<sys/types.h> #include<string.h> #include<stdio.h> #include<stdlib.h> #define MAX 100 # define PORT 7386 int main(int argc,char **argv) { int sfd,cfd,slen,clen,i,ch,len; FILE *fp; char buff[MAX],filename[MAX]; struct sockaddr_in servaddr,cliaddr; if((sfd=socket(AF_INET,SOCK_STREAM,0))<0) { perror("Socket not created\n"); exit(0); } slen=sizeof(servaddr); memset(&servaddr,slen,0); servaddr.sin_addr.s_addr=INADDR_ANY; servaddr.sin_port=htons(PORT);
R.M.K Engineering College Department of CSE

CS2307 - Network Lab servaddr.sin_family=AF_INET; if(bind(sfd,(struct sockaddr *)&servaddr,slen)<0) { printf("Bind failed\n"); close(sfd); exit(1); } printf("SERVER SOCKET BINDED\n"); listen(sfd,5); printf("SERVER SOCKET listened\n"); len=sizeof(cliaddr); if((cfd=accept(sfd,(struct sockaddr *)&cliaddr,&len))<0) { printf("Accept failed\n"); close(sfd); exit(1); } printf("SERVER Socket accepted connection with a Client\n"); bzero(filename,MAX); if(recv(cfd,filename,sizeof(filename),0)<0) { printf("Did not receive the filename"); close(sfd); close(cfd); exit(1); } for(i-0;i<MAX;i++) if(filename[i]=='\n'||filename[i]=='\r') { filename[i]='\0'; break; } printf("File requested: %s\n",filename); if((fp=fopen(filename,"r"))==NULL) { printf("File could not be opened\n"); close(sfd); close(cfd); exit(1); } if((ch=fgetc(fp))==EOF) { close(sfd); close(cfd); fclose(fp); exit(1);

47 of 107

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab exit(1); } bzero(buff,sizeof(buff)); buff[0]=ch; buff[1]='\0'; send(cfd,buff,2,0); printf("Sending:%s",buff); while(!feof(fp)) { bzero(buff,sizeof(buff)); do { recv(cfd,buff,MAX,0); }while(strcmp(buff,"ACK")!=0); printf("Received ACK...\n"); if((ch=fgetc(fp))==EOF) break; bzero(buff,sizeof(buff)); buff[0]=ch; buff[1]='\0'; send(cfd,buff,2,0); printf("Sending:%s",buff); } send(cfd,"OVER",5,0); printf("Sending: OVER"); close(sfd); close(cfd); close(fp); return 0; } CLIENT //slidingcli.c -- CLIENT #include<sys/socket.h> #include<netinet/in.h> #include<sys/types.h> #include<string.h> #include<stdio.h> #include<stdlib.h> #define MAX 100 #define PORT 7386 int main(int argc,char *argv[]) { int ct,sockfd; int sfd,slen,clen,bufsize; char buff[MAX]; FILE *fp;

48 of 107

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab struct sockaddr_in serv,cliaddr; sockfd=socket(AF_INET,SOCK_STREAM,0); if(sockfd<1) { perror("Socket error"); exit(0); } printf("CLIENT SOCKED CREATED"); bzero(&serv,sizeof(serv)); serv.sin_family=AF_INET; serv.sin_port=htons(PORT); serv.sin_addr.s_addr=inet_addr(argv[1]); if(connect(sockfd,(struct sockaddr *)&serv,sizeof(serv))<0) { printf("ERROR IN CONNECT"); exit(1); } printf("CLIENT SOCKET CONNECTED"); printf("\nEnter filename"); scanf("%s",buff); send(sockfd,buff,sizeof(buff),0); do { bzero(buff,sizeof(buff)); recv(sockfd,buff,MAX,0); if(strncmp(buff,"OVER",3)==0) break; printf("\nReceived:%s, sending ACK...\n",buff); send(sockfd,"ACK",4,0); } while(1); close(sockfd); printf("\nReceived and signal(OVER) terminating\n"); return 0; }

49 of 107

OUTPUT //sample.txt GOOD DAY //SERVER rmk@rmk-desktop:~/NWLAB/SLIDING$ cc slidingser.c rmk@rmk-desktop:~/NWLAB/SLIDING$ ./a.out SERVER SOCKET BINDED

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab SERVER SOCKET listened SERVER Socket accepted connection with a Client File requested: sample.txt Sending:GReceived ACK... Sending:OReceived ACK... Sending:OReceived ACK... Sending:DReceived ACK... Sending: Received ACK... Sending:DReceived ACK... Sending:AReceived ACK... Sending:YReceived ACK... Sending: Received ACK... Sending: OVERrmk@rmk-desktop:~/NWLAB/SLIDING$ //CLIENT rmk@rmk-desktop:~/NWLAB/SLIDING$ cc slidingcli.c rmk@rmk-desktop:~/NWLAB/SLIDING$ ./a.out 127.0.0.1 CLIENT SOCKED CREATEDCLIENT SOCKET CONNECTED Enter filenamesample.txt Received:G, sending ACK... Received:O, sending ACK... Received:O, sending ACK... Received:D, sending ACK... Received: , sending ACK... Received:D, sending ACK... Received:A, sending ACK... Received:Y, sending ACK... Received: , sending ACK... Received and signal(OVER) terminating rmk@rmk-desktop:~/NWLAB/SLIDING$

50 of 107

EX NO 8

ADDITION AND SUBRACTION OF TWO NUMBERS USING REMOTE PROCEDURE CALL

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

51 of 107

AIM: To perform addition and subtraction of two numbers using remote procedure call.

THEORY:

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

52 of 107

RPCGEN is the RPC Protocol Compiler. This compiler creates the network interface portion of a distributed application, effectively hiding from the programmer the details of writing and debugging low-level network interface code. rpcgen tool generates four C files for the specification file (simp.x). The output file contains C source code for both output and data declarations. File Name simp_clnt.c simp _svc.c simp.h simp_xdr.c Description Client side communication stub procedure Server side communication stub procedure Declaration of constants and types used in the code generated for both client and server. XDR-eXternal Data Representation. Contains XDR procedure calls used in the client and server to marshal arguments.

STEPS 1. Create the specification file (simp.x). 2. Create the server file.(simpservice.c) 3. Create the client file.(simpclient.c) 4. Generate header files and stub files. 5. Compile Server file and run the server. 6. Compile client and Run the client application by specify argument list and hostname of the server.

SIMP.X 1. This defines the protocol definition for the application. 2. Define two remote procedures - Each must be called with a single parameter, a structure that holds 2 integers. 3. The return value of each procedure is an int. simpclient.c 1. Define the wrapper function that takes care of calling the RPC procedure. 2. Gather everything into a single data structure to send to the server. 3. Call the client stub created by rpcgen.

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

53 of 107

4. Create a CLIENT data structure that reference the RPC procedure SIMP_PROG, version SIMP_VERSION running on the host specified by the first command line arg. 5. Get the 2 numbers that should be added, from the user. 6. Pass the numbers to the server for calculation and prints the output in the terminal.

Simpservice.c

1. This file contains the definition of the remote add and subtract procedure used by simple RPC example 2. The return value of the procedure must be a pointer to integer. 3. Declare the variable result as static so we can return a pointer to it. 4. Define implementation of the method add_1_svc as add two arguments. 5. Define implementation of the method sub_1_svc as subtract second argument from first argument. PROGRAM //simp.x #define VERSION_NUMBER 1 %#define foo 127 struct operands { int x; int y; }; program SIMP_PROG { version SIMP_VERSION { int ADD(operands) = 1; int SUB(operands) = 2; } = VERSION_NUMBER; } = 555555555; //simpservice.c #include "simp.h" int *add_1_svc(operands *argp,struct svc_req *rqstp) { static int result;

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab printf("Got request: adding %d,%d\n",argp->x,argp->y); result=argp->x +argp->y; return(&result); } int *sub_1_svc(operands *argp,struct svc_req *rqstp) { static int result; printf("Got request:subtracting %d,%d\n",argp->x,argp->y); result=argp->x -argp->y; return(&result); } //simpclient.c #include<stdio.h> #include "simp.h" int add(CLIENT *clnt,int x,int y) { operands ops; int *result; ops.x=x; ops.y=y; result=add_1(&ops,clnt); if(result==NULL) { fprintf(stderr,"Trouble calling remote procedure\n"); exit(0); } return(*result); } int sub(CLIENT *clnt,int x,int y) { operands ops; int *result; ops.x=x; ops.y=y; result=sub_1(&ops,clnt); if(result==NULL) { fprintf(stderr,"Trouble calling remote procedure\n"); exit(0); } return(*result); }

54 of 107

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab int main(int argc,char *argv[]) { CLIENT *clnt; int x,y; if(argc!=4) { fprintf(stderr,"Usage:%s hostname num1 num\n",argv[0]); exit(0); } clnt=clnt_create(argv[1],SIMP_PROG,SIMP_VERSION,"udp"); if(clnt==(CLIENT *)NULL) { clnt_pcreateerror(argv[1]); exit(1); } x=atoi(argv[2]); y=atoi(argv[3]); printf("%d + %d=%d\n",x,y,add(clnt,x,y)); printf("%d - %d=%d\n",x,y,sub(clnt,x,y)); return(0); } OUTPUT GENERATION OF STUBS AND HEADER FILE rmk@rmk-desktop:~/NWLAB/RPC$rpcgen -C -a simp.x //Make sure that the following files are generated by rpcgen tool rmk@rmk-desktop:~/NWLAB/RPC$ ls a.out simpclient.c simp_server.c simp.x Makefile.simp simp_clnt.c simpservice.c simp_xdr.c simp_client.c simp.h simp_svc.c SERVER rmk@rmk-desktop:~/NWLAB/RPC$ cc simpservice.c simp_svc.c simp_xdr.c rmk@rmk-desktop:~/NWLAB/RPC$ ./a.out Got request: adding 6, 3 Got request: subtracting 6, 3 CLIENT rmk@rmk-desktop:~/NWLAB/RPC$ cc simpclient.c simp_clnt.c simp_xdr.c rmk@rmk-desktop:~/NWLAB/RPC$ ./a.out 127.0.0.1 6 3 6+3=9 6-3=3 rmk@rmk-desktop:~/NWLAB/RPC$

55 of 107

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

56 of 107

EX NO 9

PACKET CAPTURING USING RAW SOCKETS

AIM: To capture packets sending through a socket using raw sockets.

ALGORITHM: 1. Define the IP header's structure ipheader. 2. Define the UDP header's structure udpheader. 3. Defi ne and implement the function (csum) for checksum calculation. 4. Identify Our own headers' structures

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab 5. Get the Source and destination addresses - IP and port from the user.

57 of 107

6. Create a raw socket with UDP protocol, using Socket() system call with address family as PFINET, socket type as SOCK_RAW and protocol as IPPROTO_UDP. sd = socket(PF_INET, SOCK_RAW, IPPROTO_UDP); 7. Fabricate the UDP header. 8. Send Packets from source to destination address using sendto() system call and count the number of packets delivered successfully.

PROGRAM //rawudp.c #include <unistd.h> #include <stdio.h> #include<stdlib.h> #include <sys/socket.h> #include <netinet/ip.h> #include<string.h> #include <netinet/udp.h> #include<sys/types.h> #define PCKT_LEN 8192 // The IP header's structure struct ipheader { unsigned char iph_ihl:5, iph_ver:4; unsigned char iph_tos; unsigned short int iph_len; unsigned short int iph_ident; unsigned char iph_flag; unsigned short int iph_offset; unsigned char iph_ttl; unsigned char iph_protocol; unsigned short int iph_chksum; unsigned int iph_sourceip; unsigned int iph_destip; }; // UDP header's structure struct udpheader { unsigned short int udph_srcport; unsigned short int udph_destport;

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab unsigned short int udph_len; unsigned short int udph_chksum; }; // Function for checksum calculation. unsigned short csum(unsigned short *buf, int nwords) { // unsigned long sum; for(sum=0; nwords>0; nwords--) sum += *buf++; sum = (sum >> 16) + (sum &0xffff); sum += (sum >> 16); return (unsigned short)(~sum); } int main(int argc, char *argv[]) { int sd; char buffer[PCKT_LEN]; // Our own headers' structures struct ipheader *ip = (struct ipheader *) buffer; struct udpheader *udp = (struct udpheader *) (buffer + sizeof(struct ipheader)); // Source and destination addresses: IP and port struct sockaddr_in sin, din; int one = 1; const int *val = &one; memset(buffer, 0, PCKT_LEN); // Create a raw socket with UDP protocol sd = socket(PF_INET, SOCK_RAW, IPPROTO_UDP); if(sd < 0) { perror("socket() error"); exit(1); } else printf("socket() - Using SOCK_RAW socket and UDP protocol is OK.\n"); sin.sin_family = AF_INET; din.sin_family = AF_INET; sin.sin_port = htons(atoi(argv[2])); din.sin_port = htons(atoi(argv[4])); sin.sin_addr.s_addr = inet_addr(argv[1]); din.sin_addr.s_addr = inet_addr(argv[3]); // Fabricate the IP header

58 of 107

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab ip->iph_ihl = 5; ip->iph_ver = 4; ip->iph_tos = 16; ip->iph_len = sizeof(struct ipheader) + sizeof(struct udpheader); ip->iph_ident = htons(54321); ip->iph_ttl = 64; // hops ip->iph_protocol = 17; // UDP ip->iph_sourceip = inet_addr(argv[1]);//Source IP address ip->iph_destip = inet_addr(argv[3]);// destination IP address // Fabricate the UDP header. udp->udph_srcport = htons(atoi(argv[2]));//source port udp->udph_destport = htons(atoi(argv[4]));//destination port udp->udph_len = htons(sizeof(struct udpheader)); // Calculate the checksum ip->iph_chksum = csum((unsigned short *)buffer, sizeof(struct ipheader) + sizeof(struct udpheader)); if(setsockopt(sd, IPPROTO_IP, IP_HDRINCL, val, sizeof(one)) < 0) { perror("setsockopt() error"); exit(-1); } else printf("setsockopt() is OK.\n"); printf("Using raw socket and UDP protocol\n"); printf("Using Source IP: %s port: %u, Target IP: %s port: %u.\n", argv[1], atoi(argv[2]), argv[3], atoi(argv[4])); int count; for(count = 1; count <=5; count++) { if(sendto(sd, buffer, ip->iph_len, 0, (struct sockaddr *)&sin, sizeof(sin)) < 0) { perror("sendto() error"); exit(-1); } else { printf("Count #%u - sendto() is OK.\n", count); sleep(2); } } close(sd); return 0;

59 of 107

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab } OUTPUT rmk@rmk-desktop:~/NWLAB/RAW$ cc rawudp.c rmk@rmk-desktop:~/NWLAB/RAW$ sudo ./a.out 127.0.0.1 7221 127.0.0.1 7256 socket() - Using SOCK_RAW socket and UDP protocol is OK. setsockopt() is OK. Using raw socket and UDP protocol Using Source IP: 127.0.0.1 port: 7221, Target IP: 127.0.0.1 port: 7256. Count #1 - sendto() is OK. Count #2 - sendto() is OK. Count #3 - sendto() is OK. Count #4 - sendto() is OK. Count #5 - sendto() is OK. rmk@rmk-desktop:~/NWLAB/RAW$

60 of 107

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

61 of 107

EX NO 10

STUDY OF NS-2 WITH SAMPLE PROGRAMS

AIM: To study the Network Simulator NS2.

NS-2 Ns-2 is a discrete event simulator targeted at networking research. Ns provides substantial support for simulation of TCP, routing, and multicast protocols over wired and wireless (local and satellite) networks.

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

62 of 107

NS-2 ARCHITECTURE Downloading/Installing ns&nam One can build ns either from the various packages (Tcl/Tk, otcl, etc.), or can download an 'all-inone' package. web page: http://www.isi.edu/nsnam/ns/ns-build.html

Starting ns Start ns with the command 'ns <tclscript>', where '<tclscript>' is the name of a Tcl script file which defines the simulation scenario (i.e. the topology and the events). Just start ns without any arguments and enter the Tcl commands in the Tcl shell, but that is definitely less comfortable. 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.

Starting nam One 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 one can execute it directly out of the Tcl simulation script for the simulation which you want to visualize.

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

63 of 107

First TCL Script 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]

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab $ns namtrace-all $nf

64 of 107

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 } 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 Ns-2 MAIN CONSOLE WITH NETWORK ANIMATOR

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

65 of 107

EX NO 10 A -

SETTING UP NODES AND LINKS

ALGORITHM: 1. Define new simulator object 2. Define a new NAM Trace file and open it 3. Define a 'finish' procedure to flush trace record in the `trace and trace output files. 4. Create two nodes

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

66 of 107

5. Create duplex links between the nodes with 1Mb and 10 ms Link with DropTail option 6. Call the finish procedure after 5 seconds of simulation time 7. Run the simulation PROGRAM: #Create a simulator object set ns [new Simulator] #Open the nam trace file set nf [open outa.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 outa.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 #Call the finish procedure after 5 seconds of simulation time $ns at 5.0 "finish" #Run the simulation $ns run

OUTPUT

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

67 of 107

Setting Up Nodes and Links

EX NO 10 B -

PACKET TRANSFER BETWEEN TWO NODE

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

68 of 107

ALGORITHM 1. Define new simulator object 2. Define a new NAM Trace file and open it 3. Define a 'finish' procedure to flush trace record in the `trace and trace output files. 4. Create two nodes 5. Create duplex links between the nodes with 1Mb and 10 ms Link with DropTail option 6. Create a UDP agent and attach it to node n0 7. Create a CBR traffic source and attach it to udp0 8. Create a Null agent (a traffic sink) and attach it to node n1 9. onnect the traffic source with the traffic sink 10. Schedule events for the CBR agent 11. Call the finish procedure after 5 seconds of simulation time 12. Run the simulation PROGRAM #Create a simulator object set ns [new Simulator] #Open the nam trace file set nf [open outb.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 outb.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

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab #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 #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 OUTPUT

69 of 107

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

70 of 107

Packet transfer between Two Nodes

EX NO 10 C ALGORITHM

SIMPLE TOPOLOGY

1. Define new simulator object 2. Define a new NAM Trace file and open it 3. Define a 'finish' procedure to flush trace record in the `trace and trace output files. 4. Create four nodes 5. Create links between the nodes 6. Monitor the queue for the link between node 2 and node 3 7. Create a CBR traffic source and attach it to udp0

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab 8. Create a UDP agent and attach it to node n1 9. C reate a CBR traffic source and attach it to udp1 10. Create a Null agent (a traffic sink) and attach it to node n3 11. Connect the traffic sources with the traffic sink 12. Schedule events for the CBR agent 13. Call the finish procedure after 5 seconds of simulation time 14. Run the simulation PROGRAM #Create a simulator object set ns [new Simulator] #Define different colors for data flows $ns color 1 Blue $ns color 2 Red #Open the nam trace file set nf [open outc.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 outc.nam & exit 0 } #Create four nodes set n0 [$ns node] set n1 [$ns node] set n2 [$ns node] set n3 [$ns node] #Create 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 SFQ

71 of 107

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab $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 #Monitor the queue for the link between node 2 and node 3 $ns duplex-link-op $n2 $n3 queuePos 0.5 #Create a UDP agent and attach it to node n0 set udp0 [new Agent/UDP] $udp0 set class_ 1 $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 UDP agent and attach it to node n1 set udp1 [new Agent/UDP] $udp1 set class_ 2 $ns attach-agent $n1 $udp1 # 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 #Create a Null agent (a traffic sink) and attach it to node n3 set null0 [new Agent/Null] $ns attach-agent $n3 $null0 #Connect the traffic sources with the traffic sink $ns connect $udp0 $null0 $ns connect $udp1 $null0 #Schedule events for the CBR agents $ns at 0.5 "$cbr0 start" $ns at 1.0 "$cbr1 start" $ns at 4.0 "$cbr1 stop" $ns at 4.5 "$cbr0 stop" #Call the finish procedure after 5 seconds of simulation time $ns at 5.0 "finish" #Run the simulation

72 of 107

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab $ns run OUTPUT

73 of 107

Simple Topology

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab EX 10 D SIMPLE NETWORK MODEL

74 of 107

ALGORITHM 1. Define new simulator object 2. Define a new NAM Trace file and open it 3. Define a 'finish' procedure to flush trace record in the `trace and trace output files. 4. Create seven nodes 5. Create links between the nodes 6. Create a UDP agent and attach it to node n(0) 7. Create a CBR traffic source and attach it to udp0 8. Create a Null agent (a traffic sink) and attach it to node n(3) 9. Connect the traffic source with the traffic sink 10. Schedule events for the CBR agent and the network dynamics 11. Call the finish procedure after 5 seconds of simulation time 12. Run the simulation PROGRAM #Create a simulator object set ns [new Simulator] #Tell the simulator to use dynamic routing $ns rtproto DV #Open the nam trace file set nf [open outd.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 outd.nam & exit 0 } #Create seven nodes for {set i 0} {$i < 7} {incr i} { set n($i) [$ns node]

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab } #Create links between the nodes for {set i 0} {$i < 7} {incr i} { $ns duplex-link $n($i) $n([expr ($i+1)%7]) 1Mb 10ms DropTail } #Create a UDP agent and attach it to node n(0) set udp0 [new Agent/UDP] $ns attach-agent $n(0) $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 n(3) set null0 [new Agent/Null] $ns attach-agent $n(3) $null0 #Connect the traffic source with the traffic sink $ns connect $udp0 $null0 #Schedule events for the CBR agent and the network dynamics $ns at 0.5 "$cbr0 start" $ns rtmodel-at 1.0 down $n(1) $n(2) $ns rtmodel-at 2.0 up $n(1) $n(2) $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 OUTPUT

75 of 107

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

76 of 107

Simple Network Model

Ex No 11

IMPLEMENTATION OF UNICAST ROUTING PROTOCOL

AIM: To implement Unicast Routing protocol using network simulator (ns-2).

ALGORITHM 1. Define new simulator 2. Define different colors for data flows (for NAM) 3. Define a new Trace file and open it 4. Define a new NAM Trace file and open it 5. Define a 'finish' procedure to flush trace record in the `trace and trace output files. 6. Define the routing protocol as Distance Vector (DV)
R.M.K Engineering College Department of CSE

CS2307 - Network Lab 7. Create six nodes n0,n1,..n5

77 of 107

8. Create links between the nodes with 0.3Mb and 10 ms Link with DropTail option 9. Give node position (for NAM) to place six nodes in the layout 10. Setup a TCP connection attach TCP Source Agent to node n0 and TCP sink agent to node n5 11. Setup a FTP over TCP connection 12. Define configuration such that link between nodes n1 and n4 to be failed at 1.0 interval, and up again at 4.5 interval 13. Start the simulation PROGRAM: set ns [new Simulator] #Define different colors for data flows (for NAM) $ns color 1 Blue $ns color 2 Red #Open the Trace file set file1 [open unicast.tr w] $ns trace-all $file1 #Open the NAM trace file set file2 [open unicastout.nam w] $ns namtrace-all $file2 #Define a 'finish' procedure proc finish {} { global ns file1 file2 $ns flush-trace close $file1 close $file2 exec nam unicastout.nam & exit 0 } # Next line should be commented out to have the static routing $ns rtproto DV #Create six nodes set n0 [$ns node] set n1 [$ns node] set n2 [$ns node]

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab set n3 [$ns node] set n4 [$ns node] set n5 [$ns node] #Create links between the nodes $ns duplex-link $n0 $n1 0.3Mb 10ms DropTail $ns duplex-link $n1 $n2 0.3Mb 10ms DropTail $ns duplex-link $n2 $n3 0.3Mb 10ms DropTail $ns duplex-link $n1 $n4 0.3Mb 10ms DropTail $ns duplex-link $n3 $n5 0.5Mb 10ms DropTail $ns duplex-link $n4 $n5 0.5Mb 10ms DropTail #Give node position (for NAM) $ns duplex-link-op $n0 $n1 orient right $ns duplex-link-op $n1 $n2 orient right $ns duplex-link-op $n2 $n3 orient up-down $ns duplex-link-op $n1 $n4 orient up-left $ns duplex-link-op $n3 $n5 orient left-up $ns duplex-link-op $n4 $n5 orient right-up #Setup a TCP connection set tcp [new Agent/TCP/Newreno] $ns attach-agent $n0 $tcp set sink [new Agent/TCPSink/DelAck] $ns attach-agent $n5 $sink $ns connect $tcp $sink $tcp set fid_ 1 #Setup a FTP over TCP connection set ftp [new Application/FTP] $ftp attach-agent $tcp $ftp set type_ FTP $ns rtmodel-at 1.0 down $n1 $n4 $ns rtmodel-at 4.5 up $n1 $n4 $ns at 0.1 "$ftp start" $ns at 6.0 "finish" $ns run

78 of 107

OUTPUT

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

79 of 107

Implementation of Unicast Routing Protocol

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

80 of 107

EX No 12

PERFORMANCE COMPARISION OF ROUTING PROTOCOLS

AIM: To implement two routing algorithms and compare their performance using network simulator (ns2)

A) DISTANCE VECTOR ROUTING ALGORITHM

ALGORITHM: 1. Define new simulator 2. Define different colors for data flows (for NAM) 3. Define a new Trace file and open it 4. Define a new NAM Trace file and open it 5. Define a 'finish' procedure to flush trace record in the `trace and trace output files. 6. Define the routing protocol as Distance Vector (DV) 7. Create six nodes n0,n1,..n5 8. Create links between the nodes with 0.3Mb and 10 ms Link with DropTail option 9. Give node position (for NAM) to place six nodes in the layout 10. Setup a TCP connection attach TCP Source Agent to node n0 and TCP sink agent to node n5 11. Setup a FTP over TCP connection 12. Define configuration such that link between nodes n1 and n4 to be failed at 1.0 interval, and up again at 4.5 interval 13. Start the simulation PROGRAM routing1.tcl
R.M.K Engineering College Department of CSE

CS2307 - Network Lab set ns [new Simulator] #Define different colors for data flows (for NAM) $ns color 1 Blue $ns color 2 Red #Open the Trace file set file1 [open routing1.tr w] $ns trace-all $file1 #Open the NAM trace file set file2 [open routing1.nam w] $ns namtrace-all $file2 #Define a 'finish' procedure proc finish {} { global ns file1 file2 $ns flush-trace close $file1 close $file2 exec nam routing1.nam & exit 0 } # Next line should be commented out to have the static routing $ns rtproto DV #Create six nodes set n0 [$ns node] set n1 [$ns node] set n2 [$ns node] set n3 [$ns node] set n4 [$ns node] set n5 [$ns node] #Create links between the nodes $ns duplex-link $n0 $n1 0.3Mb 10ms DropTail $ns duplex-link $n1 $n2 0.3Mb 10ms DropTail $ns duplex-link $n2 $n3 0.3Mb 10ms DropTail $ns duplex-link $n1 $n4 0.3Mb 10ms DropTail $ns duplex-link $n3 $n5 0.5Mb 10ms DropTail $ns duplex-link $n4 $n5 0.5Mb 10ms DropTail #Give node position (for NAM) $ns duplex-link-op $n0 $n1 orient right

81 of 107

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab $ns duplex-link-op $n1 $n2 orient right $ns duplex-link-op $n2 $n3 orient up-down $ns duplex-link-op $n1 $n4 orient up-left $ns duplex-link-op $n3 $n5 orient left-up $ns duplex-link-op $n4 $n5 orient right-up #Setup a TCP connection set tcp [new Agent/TCP/Newreno] $ns attach-agent $n0 $tcp set sink [new Agent/TCPSink/DelAck] $ns attach-agent $n5 $sink $ns connect $tcp $sink $tcp set fid_ 1 #Setup a FTP over TCP connection set ftp [new Application/FTP] $ftp attach-agent $tcp $ftp set type_ FTP $ns rtmodel-at 1.0 down $n1 $n4 $ns rtmodel-at 3.0 up $n1 $n4 $ns at 0.1 "$ftp start" $ns at 6.0 "finish" $ns run PROGRAM:

82 of 107

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

83 of 107

Distance Vector Routing Algorithm

B ) LINK STATE ROUTING ALGORITHM

ALGORITHM: 1. Define new simualtor

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab 2. Define different colors for data flows (for NAM) 3. Define a new Trace file and open it 4. Define a new NAM Trace file and open it

84 of 107

5. Define a 'finish' procedure to flush trace record in the `trace and trace output files. 6. Define the routing protocol as Link State (LS) 7. Create six nodes n0,n1,..n5 8. Create links between the nodes with 0.3Mb and 10 ms Link with DropTail option 9. Give node position (for NAM) to place six nodes in the layout 10. Setup a TCP connection attach TCP Source Agent to node n0 and TCP sink agent to node n5 11. Setup a FTP over TCP connection 12. Define configuration such that link between nodes n1 and n4 to be failed at 1.0 interval, and up again at 4.5 interval 13. Start the simulation PROGRAM #routing2.tcl set ns [new Simulator] #Define different colors for data flows (for NAM) $ns color 1 Blue $ns color 2 Red #Open the Trace file set file1 [open routing2.tr w] $ns trace-all $file1 #Open the NAM trace file set file2 [open routing2.nam w] $ns namtrace-all $file2 #Define a 'finish' procedure proc finish {} { global ns file1 file2 $ns flush-trace close $file1 close $file2

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab exec nam routing2.nam & exit 0 } # Next line should be commented out to have the static routing $ns rtproto LS #Create six nodes set n0 [$ns node] set n1 [$ns node] set n2 [$ns node] set n3 [$ns node] set n4 [$ns node] set n5 [$ns node] #Create links between the nodes $ns duplex-link $n0 $n1 0.3Mb 10ms DropTail $ns duplex-link $n1 $n2 0.3Mb 10ms DropTail $ns duplex-link $n2 $n3 0.3Mb 10ms DropTail $ns duplex-link $n1 $n4 0.3Mb 10ms DropTail $ns duplex-link $n3 $n5 0.5Mb 10ms DropTail $ns duplex-link $n4 $n5 0.5Mb 10ms DropTail #Give node position (for NAM) $ns duplex-link-op $n0 $n1 orient right $ns duplex-link-op $n1 $n2 orient right $ns duplex-link-op $n2 $n3 orient up-down $ns duplex-link-op $n1 $n4 orient up-left $ns duplex-link-op $n3 $n5 orient left-up $ns duplex-link-op $n4 $n5 orient right-up #Setup a TCP connection set tcp [new Agent/TCP/Newreno] $ns attach-agent $n0 $tcp set sink [new Agent/TCPSink/DelAck] $ns attach-agent $n5 $sink $ns connect $tcp $sink $tcp set fid_ 1 #Setup a FTP over TCP connection set ftp [new Application/FTP] $ftp attach-agent $tcp $ftp set type_ FTP $ns rtmodel-at 1.0 down $n1 $n4

85 of 107

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab $ns rtmodel-at 3.0 up $n1 $n4 $ns at 0.1 "$ftp start" $ns at 6.0 "finish" $ns run OUTPUT

86 of 107

Before Link failure between Nodes n1 and n4

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

87 of 107

While Link failure between Nodes n1 and n4

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab After failed link between Nodes n1 and n4 up

88 of 107

Sample Trace file //routing1.tr

. . + 0.00017 0 1 rtProtoDV 6 ------- 0 0.2 1.1 -1 0 - 0.00017 0 1 rtProtoDV 6 ------- 0 0.2 1.1 -1 0 + 0.007102 2 1 rtProtoDV 6 ------- 0 2.1 1.1 -1 1 - 0.007102 2 1 rtProtoDV 6 ------- 0 2.1 1.1 -1 1 + 0.007102 2 3 rtProtoDV 6 ------- 0 2.1 3.1 -1 2 - 0.007102 2 3 rtProtoDV 6 ------- 0 2.1 3.1 -1 2 r 0.01033 0 1 rtProtoDV 6 ------- 0 0.2 1.1 -1 0 r 0.017262 2 1 rtProtoDV 6 ------- 0 2.1 1.1 -1 1 + 0.017262 1 0 rtProtoDV 6 ------- 0 1.1 0.2 -1 3 - 0.017262 1 0 rtProtoDV 6 ------- 0 1.1 0.2 -1 3 . .

AWK Script AWK is a language for processing files of text. A file is treated as a sequence of records, and by default each line is a record. Each line is broken up into a sequence of fields, so we can think of the first word in a line as the first field, the second word as the second field, and so on //measure-loss.awk 1. Initialization. 2. Set two variables - fsDrops: packets drop., numFs: packets sent

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

89 of 107

3. Count the number of packets sent by checking the status of the packet (source and destination) and flag as receive (r) 4. Count the number of packets dropped by checking the status of the packet (source and destination) and flag as drop (d) COMPARISION 1. Save the above file as measure-loss.awk 2. Open terminal 3. After running routing1.tcl and routing2.tcl 4. Run the awk script to count number of packets sent between nodes 0 and 1 Type the command $gwak -f measure-loss.awk <filename.tr> PROGRAM: measure-loss.awk BEGIN { # Initialization. Set two variables. fsDrops: packets drop. numFs: packets sent fsDrops = 0; numFs = 0; } { action = $1; time = $2; from = $3; to = $4; type = $5; pktsize = $6; flow_id = $8; src = $9; dst = $10; seq_no = $11; packet_id = $12; if (src==0.0 && dst==5.0 && action == "+") numFs++; if (action == "d") fsDrops++; } END { printf("number of packets sent:%d lost:%d\n", numFs, fsDrops); } /*
R.M.K Engineering College Department of CSE

CS2307 - Network Lab steps 1. save the above file as measure-loss.awk 2. Open terminal 3. after running routing1.tcl and routing2.tcl 4. Run the awk script to count number of packets sent between nodes 0 and 1 Type the command $gwak -f measure-loss.awk routing1.tr number of packets sent:616 lost:2 $ $gawk -f measure-loss.awk routing1.tr number of packets sent:203 lost:0 */ /* Open routing1.tr search the file . . d 1 1 4 tcp 1040 ------ 1 0.0 5.0 17 62 .. . You will have a trace log showing the dropped packet information */

90 of 107

Ex No 13 AIM:

PERFORMANCE COMPARISION OF MAC PROTOCOLS

To implement two MAC protocols and compare their performance using network simulator (ns2)

A ) UNSLOTTED ALOHA 1. Define new simualtor 2. Define different colors for data flows (for NAM) 3. Define a new Trace file and open it 4. Define a new NAM Trace file and open it 5. Define the MAC protocol as Unslotted ALOHA

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab 6. Create four nodes n0,n1,..n4

91 of 107

7. Create links between the nodes with 2Mb and 10 ms Link and 1.7Mb and 20 ms with DropTail option 8. Give node position (for NAM) to place six nodes in the layout 9. Set Queue Size of link between node n2 and n3 as 10 10. Setup a TCP connection attach TCP Source Agent to node n0 and TCP sink agent to node n3 11. Setup a FTP over TCP connection 12. Setup a UDP connection attach UDP Source Agent to node n0 and UDP sink agent to node n3 13. Setup CBR traffic over TCP connection 14. Define a 'finish' procedure to flush trace record in the `trace and trace output files. 15. Schedule events for simulation 16. Run the simulation PROGRAM: #Create a simulator object set ns [new Simulator] #Open the All trace file set f [open mac1out.tr w] $ns trace-all $f #open nam trace file set ft [open mac1out.nam w] $ns namtrace-all $ft #$ns macType Mac/Sat/UnslottedAloha $ns macType Mac/Sat/UnslottedAloha #Create four nodes set n0 [$ns node] set n1 [$ns node] set n2 [$ns node] set n3 [$ns node] #Create links between the nodes $ns duplex-link $n0 $n2 2Mb 10ms DropTail $ns duplex-link $n1 $n2 2Mb 10ms DropTail

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab $ns duplex-link $n2 $n3 1.7Mb 20ms DropTail #Set Queue Size of link (n2-n3) to 10 $ns queue-limit $n2 $n3 10 #Setup a TCP connection set tcp [new Agent/TCP] $ns attach-agent $n0 $tcp set sink [new Agent/TCPSink] $ns attach-agent $n3 $sink $ns connect $tcp $sink $tcp set fid_ 1 #Setup a FTP over TCP connection set ftp [new Application/FTP] $ftp attach-agent $tcp #Setup a UDP connection set udp [new Agent/UDP] $ns attach-agent $n1 $udp set null [new Agent/Null] $ns attach-agent $n3 $null $ns connect $udp $null $udp set fid_ 2 #Setup a CBR over UDP connection set cbr [new Application/Traffic/CBR] $cbr attach-agent $udp $cbr set packet_size_ 1000 $cbr set rate_ 1mb #Schedule events for the CBR and FTP agents $ns at 0.1 "$cbr start" $ns at 1.0 "$ftp start" $ns at 4.0 "$ftp stop" $ns at 4.5 "$cbr stop" #Call the finish procedure after 5 seconds of simulation time $ns at 5.0 "finish" #Define a 'finish' procedure proc finish {} { global ns f $ns flush-trace #Close the trace file close $f

92 of 107

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab exec nam mac1out.nam & exit 0 } #Run the simulation $ns run OUTPUT:

93 of 107

Unslotted ALOHA

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab B ) SLOTTED ALOHA 1. Define new simualtor 2. Define different colors for data flows (for NAM) 3. Define a new Trace file and open it 4. Define a new NAM Trace file and open it 5. Define the MAC protocol as Slotted ALOHA 6. Create four nodes n0,n1,..n4

94 of 107

7. Create links between the nodes with 2Mb and 10 ms Link and 1.7Mb and 20 ms with DropTail option 8. Give node position (for NAM) to place six nodes in the layout 9. Set Queue Size of link between node n2 and n3 as 10 10. Setup a TCP connection attach TCP Source Agent to node n0 and TCP sink agent to node n3 11. Setup a FTP over TCP connection 12. Setup a UDP connection attach UDP Source Agent to node n0 and UDP sink agent to node n3 13. Setup CBR traffic over TCP connection 14. Define a 'finish' procedure to flush trace record in the `trace and trace output files. 15. Schedule events for simulation 16. Run the simulation PROGRAM: #Create a simulator object set ns [new Simulator] #Open the All trace file set f [open mac2out.tr w] $ns trace-all $f #open nam trace file set ft [open mac2out.nam w] $ns namtrace-all $ft #$ns macType Mac/Sat/SlottedAloha $ns macType Mac/Sat/SlottedAloha
R.M.K Engineering College Department of CSE

CS2307 - Network Lab

95 of 107

#Create four nodes set n0 [$ns node] set n1 [$ns node] set n2 [$ns node] set n3 [$ns node] #Create links between the nodes $ns duplex-link $n0 $n2 2Mb 10ms DropTail $ns duplex-link $n1 $n2 2Mb 10ms DropTail $ns duplex-link $n2 $n3 1.7Mb 20ms DropTail #Set Queue Size of link (n2-n3) to 10 $ns queue-limit $n2 $n3 10 #Setup a TCP connection set tcp [new Agent/TCP] $ns attach-agent $n0 $tcp set sink [new Agent/TCPSink] $ns attach-agent $n3 $sink $ns connect $tcp $sink $tcp set fid_ 1 #Setup a FTP over TCP connection set ftp [new Application/FTP] $ftp attach-agent $tcp #Setup a UDP connection set udp [new Agent/UDP] $ns attach-agent $n1 $udp set null [new Agent/Null] $ns attach-agent $n3 $null $ns connect $udp $null $udp set fid_ 2 #Setup a CBR over UDP connection set cbr [new Application/Traffic/CBR] $cbr attach-agent $udp $cbr set packet_size_ 1000 $cbr set rate_ 1mb #Schedule events for the CBR and FTP agents $ns at 0.1 "$cbr start" $ns at 1.0 "$ftp start" $ns at 4.0 "$ftp stop" $ns at 4.5 "$cbr stop"

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

96 of 107

#Call the finish procedure after 5 seconds of simulation time $ns at 5.0 "finish" #Define a 'finish' procedure proc finish {} { global ns f $ns flush-trace #Close the trace file close $f exec nam mac2out.nam & exit 0 } #Run the simulation $ns run OUTPUT

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

97 of 107

Slotted ALOHA

Ex No 14 AIM:

STUDY OF UDP & TCP PERFORMANCE

To implement UDP protocol and Study the performance using network simulator (ns2)

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

98 of 107

A ) UNSLOTTED ALOHA 1. 2. 3. 4. 5. 6. Define new simulator Create n number of nodes Set the link between each nodes Create UDP & TCP agent Attach the UDP & TCP agent Trace the protocol using CBR & FTP

7. Define a 'finish' procedure to flush trace record in the `trace and trace output files. 8. Schedule events for simulation 9. Run the simulation Program set ns [new Simulator] $ns color 0 blue $ns color 1 red $ns color 2 white set n0 [$ns node] set n1 [$ns node] set n2 [$ns node] set n3 [$ns node] set f [open out.tr w] $ns trace-all $f set nf [open out.nam w] $ns namtrace-all $nf $ns duplex-link $n0 $n2 5Mb 2ms DropTail $ns duplex-link $n1 $n2 5Mb 2ms DropTail $ns duplex-link $n2 $n3 1.5Mb 10ms DropTail $ns duplex-link-op $n0 $n2 orient right-up $ns duplex-link-op $n1 $n2 orient right-down $ns duplex-link-op $n2 $n3 orient right $ns duplex-link-op $n2 $n3 queuePos 0.5 set udp0 [new Agent/UDP] $ns attach-agent $n0 $udp0 set cbr0 [new Application/Traffic/CBR] $cbr0 attach-agent $udp0
R.M.K Engineering College Department of CSE

CS2307 - Network Lab

99 of 107

set udp1 [new Agent/UDP] $ns attach-agent $n3 $udp1 $udp1 set class_ 1 set cbr1 [new Application/Traffic/CBR] $cbr1 attach-agent $udp1 set null0 [new Agent/Null] $ns attach-agent $n3 $null0 set null1 [new Agent/Null] $ns attach-agent $n1 $null1 $ns connect $udp0 $null0 $ns connect $udp1 $null1 $ns at 1.0 "$cbr0 start" $ns at 1.1 "$cbr1 start" set tcp [new Agent/TCP] $tcp set class_ 2 set sink [new Agent/TCPSink] $ns attach-agent $n0 $tcp $ns attach-agent $n3 $sink $ns connect $tcp $sink set ftp [new Application/FTP] $ftp attach-agent $tcp $ns at 1.2 "$ftp start" $ns at 1.35 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n3 $sink" puts [$cbr0 set packetSize_] puts [$cbr0 set interval_] $ns at 3.0 "finish" proc finish {} { global ns f nf $ns flush-trace close $f close $nf puts "running nam..." exec nam out.nam & exit 0 }

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab $ns run Output :

100 of 107

Study of UDP Performance

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

101 of 107

Study of TCP Performance

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab ADDITONAL EXERCISE (BEYOND THE SYLLABUS)

102 of 107

1. DEVELOP A CLIENT SERVER APPLICATION FOR CHAT USING TCP SOCKETS

AIM
To write a c program in UNIX to perform the full duplex chat by sending and receiving the message from the client to server and vice versa using TCP.

ALGORITHM
Chat Server 1. Include necessary header files to support functions for Socket definitions, Socket Types, Internet addresses, I/Ofunctions, Unix system calls. 2. Declare variables for Socket ID,Portnumber,Socket addresses, buffer,etc. 3. Create Socket for server. 4. Bind socket with addresses. 5. Specify number of allowed connections. 6. Wait for connection. 7. Accept connection (If any). 8. Repeat the steps 8and 9 until the socket is closed. 9. Retrieve information from Connected Socket and display it. 10. Send information to Connected Socket. 11. Close Connected socket. Chat Client 1. Include necessary header files to support functions for Socket definitions, Socket types, Internet addresses, I/O functions, Unix system calls. 2. Declare variables for Socket ID, Portnumber, Socket addresses, Character buffer, etc. 3. Create Socket for Client. 4. Connect client socket to the server socket addresses. 5. Repeat the steps 8and 9 until the socket is closed. 6. Send information to Connected Socket

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab


7. Retrieve information from Connected Socket and display it.. 8. Close Connected socket.

103 of 107

PROGRAM
Server #include<stdio.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<netdb.h> #define SERV_TCP_PORT 5005 int main(int argc,char *argv[]) { int sockfd,newsockfd,clength; struct sockaddr_in serv_addr,cli_addr; char buffer[4096]; sockfd=socket(AF_INET,SOCK_STREAM,0); serv_addr.sin_family=AF_INET; serv_addr.sin_addr.s_addr=INADDR_ANY; serv_addr.sin_port=htons(SERV_TCP_PORT); bind(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)); listen(sockfd,5); clength=sizeof(cli_addr); newsockfd=accept(sockfd,(struct sockaddr *)&cli_addr,&clength); do { bzero(buffer,4096); read(newsockfd,buffer,4096); printf("\n Client:%s",buffer); bzero(buffer,4096); R.M.K Engineering College Department of CSE

CS2307 - Network Lab


printf("\n Server:"); fgets(buffer,4096,stdin); write(newsockfd,buffer,4096); } while(strcmp(buffer,"bye\n")!=0); close(sockfd); return(0); } Client Program

104 of 107

#include<stdio.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<netdb.h> #define SERV_TCP_PORT 5005 int main(int argc,char *argv[]) { int sockfd; struct sockaddr_in serv_addr; struct hostent * server; char buffer[4096]; sockfd=socket(AF_INET,SOCK_STREAM,0); serv_addr.sin_family=AF_INET; serv_addr.sin_addr.s_addr=inet_addr("127.0.0.1"); serv_addr.sin_port=htons(SERV_TCP_PORT); connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)); printf("\n Enter your message to send:\n"); do { bzero(buffer,4096); printf("\n client: "); fgets(buffer,4096,stdin); write(sockfd,buffer,4096); bzero(buffer,4096); read(sockfd,buffer,4096); printf("\n Server : %s",buffer); } while(strcmp(buffer,"bye\n")!=0); close(sockfd); return(0); }

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab SAMPLE INPUT AND OUTPUT Server Program Client :hi good morning Server :hello how are you? Client: I am fine Server: Client:see you tomorrow Server:ok bye Client:bye

105 of 107

Client Program
Enter your message to send: client: hi good morning Server : hello client: am fine Server : how are you? client: see you tomorrow Server : ok bye client: bye Result

Thus the program was written in C in UNIX platform to write a c program in UNIX to stimulate the concept of client server chat application using TCP

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

106 of 107

2. WRITE A PROGRAM THAT TAKES A BINARY FILE AS INPUT AND PERFORM BIT STUFFING.

AIM To write a program that takes a binary file as input and performs the bit stuffing.

ALGORITHM

Chat Server 1. Include necessary header files to support functions for Socket definitions, Socket Types, Internet addresses, I/Ofunctions, Unix system calls. 2. Declare variables for Socket ID,Portnumber,Socket addresses, buffer,etc. 3. Create Socket for server. 4. Bind socket with addresses. 5. Specify number of allowed connections. 6. Wait for connection. 7. Accept connection (If any). 8. Take the binary input file. 9. Perform a bit stuffing by replacing every sixth bit by 0, if it is 1 , else check the next sixth bit and repeat the process 10. Repeat the steps 8and 9 until the socket is closed. 11. Retrieve information from Connected Socket and display it. 12. Send information to Connected Socket. 13. Close Connected socket.

Chat Client 1. Include necessary header files to support functions for Socket definitions, Socket types, Internet addresses, I/O functions, Unix system calls.

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

107 of 107

2. Declare variables for Socket ID, Portnumber, Socket addresses, Character buffer, etc. 3. Create Socket for Client. 4. Connect client socket to the server socket addresses. 5. Enter the source file name for which the bit stuffing is performed. 6. Repeat the steps 8and 9 until the socket is closed. 7. Send information to Connected Socket 8. Retrieve information from Connected Socket and display it.. 9. Close Connected socket. PROGRAM SERVER #include<stdio.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<netdb.h> #include<fcntl.h> #include<stdlib.h> #include<unistd.h> #define SERV_TCP_PORT 3434 #define max 60 void stuff(); int i,j,tem; char buff[4096],t; FILE *f1; Int main(int arg,char*argv) { int sockfd,newsockfd,clength; struct sockaddr_in serv_addr,cli_addr;

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab


char t[max],str[max]; strcpy(t,exit); sockfd=socket(AF__INET,SOCK_STREAM,0); serv_addr.sin_family=AF_INET; serv_addr.sin_addr.s_addr=INADDR_ANY; serv_addr.sin_port=htons(SERV_TCP_PORT); bind(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)); listen(sockfd,5); for(;;) { clength=sizeof(cli_adr); new sockfd=accept(sockfd,(struct sockaddr *)&cli_addr,&clength); close(sockfd); read(newsockfd,&str,max); printf(\n CLIENT MESSAFE \n FILENAME: %s \n,str); f1=fopen(str,r); while(fgets(buff,4096,f1)!=NULL) { stuff(); write(newsockfd, buff,max); printf(\n); } fclose(f1); exit(0); } printf(\n file transferred \n); return 0; } void stuff() { i=j=tem=0;

108 of 107

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab


printf(\n Inout %s \n,buff); do { if(buff[i]==1) { if(j==4) { tem=(i-4); t=0; for(;tem<=i;tem++) printf(%c,buff[tem]); j=-1; printf(%c,t); } i+=1; j+=1; } else { tem=I; tem=tem-j; for(:tem<=i,tem++) printf(%c,buff[tem]); i+=1; j=0; } } while(buff[i]!=\0); }

109 of 107

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab


SAMPLE OUTPUT : CLIENT MESSAGE FILENAME :source.txt Input 1111111111111 111110111110 CLIENT #include<stdio.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<netdb.h> #include<fcntl.h> #include<stdlib.h> #include<unistd.h>

110 of 107

#define SERV_TCP_PORT 3434 #define max 60 int main(int argc,char *argv[]) { int sockfd; struct sockaddr_in serv_addr; struct hostent * server; char send[max], recv[max],s[max],name[max]; sockfd=socket(AF_INET,SOCK_STREAM,0); serv_addr.sin_family=AF_INET; serv_addr.sin_addr.s_addr=inet_addr("127.0.0.1"); serv_addr.sin_port=htons(SERV_TCP_PORT);
connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)); for(;;) { printf(\n source filename :\t); scanf(%s,send); write(sockfd,send,max); while(1)

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab


{ read(sockfd,recv,max); } exit(0); } close(sockfd); return ; } SAMPLE OUTPUT Source filename: source.txt RESULT:

111 of 107

Thus a program in c is written that takes a binary file as input and performs the bit stuffing

3.WRITE A PROGRAM THAT TAKES A BINARY FILE AS INPUT AND PERFORM BIT CRC AIM To write a c program in UNIX to stimulate CRC and to generate the CRC remainder. Also send and receive and check the same for error. ALGORITHM 1. 2. 3. 4. 5. 6. 7. 8. Get the data to be transmitted. Add three 0s at the end of the data Perform modulo 2 division and find the remainder with the division being (1101)2 Append the remainder at the end of data. Transmit the data Receive the data at the receiver side. Perform the modulo 2 division an find the remainder with the divisor being same (1101)2 If the remainder is 0, then no error in transmission else there is an error in transmission.

PROGRAM #include<stdio.h> int exor( int a, int b) { int c; c=a+b; if(c==2) return 0; R.M.K Engineering College Department of CSE

CS2307 - Network Lab


return c; } int crc(long div) { printf(\n Inside CRC); long t,rem; int r1,r2,r3,r4; int I,n,result,d[15]; t=div; printf(\n Divident of modulo 2 division is =%lddiv); printf(\n Divident of modulo 2 division is = 1101); for(i=0;t!=0;i++) { rem=t%10; t=t/10; d[i]=(int)rem; } n=i; r4=d[n-1]; r3=d[n-2]; r2=d[n-3]; r1=d[n-4]; for(i=n-5;i>=-1;i--) { if(r4==1) { r4=exor(r3,1); r3=exor(r2,0); r2=exor(r1,1); r1=d[i]; } else

112 of 107

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab


{ r4=r3; r3=r2; r2=r1; r1=d[i]; } } printf(\ The remainder of modulo 2 ivision =%d%d%d. r4,r3,r2); result=r4*100+r3*10+r2; printf(\n End of CRC \n); return result: } long transmitter(long data) { int rem; printf( \n The given data to be transmitted =%ld\n,data); data=data*1000; rem=crc(data); data=data+rem; printf(\n\n The transmitted data = %ld \n,data); return data ; } void receiverlong td) { int rem; printf(|n The received data = %ld \n, td); rem=crc(td); if(rem==0) printf(\n No error in Transmission);

113 of 107

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab


else printf(\n Error in Transmission); } main() { long data,tx; printf( enter the data:); scanf(%ld,&data); tx=transmitter(data); receiver(tx); }

114 of 107

SAMPLE INPUT/OUPUT

Enter the data : 100100 The given data to be transmitted =100100 Inside CRC Divident of modulo 2 division is =10010000 Divisor of modulo 2 dividion is=1101 The Remainder of modulo 2 division -001 End of CRC

The transmitted data =100100001 The received data =100100001 Inside CRC Divident of modulo 2 division is =100100001 Divisor of modulo 2 division is =1101 The remainder of modulo 2 division=000 End of CRC

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab


No error in Transmission RESULT:

115 of 107

Thus a c program is written in UNIX to stimulate CRC and to generate the CRC remainder. Also the same is sent and received and checked the same for error. 4.Write a Client to download a file from a HTTP Server AIM To write a c program in UNIX to download a file from a HTTP server. ALGORITHM Server 1. Include necessary header files to support functions for Socket definitions, Socket Types, Internet addresses, I/Ofunctions, Unix system calls. 2. Declare variables for Socket ID,Portnumber,Socket addresses, buffer,etc. 3. Create Socket for server. 4. Bind socket with addresses. 5. Specify number of allowed connections. 6. Wait for connection. 7. Accept connection (If any). 8. Repeat the steps 8and 9 until the socket is closed. 9. Read the requested file to be transmitted from the client 10. The requested file is transferred by write to the new location.

Chat Client 1. Include necessary header files to support functions for Socket definitions, Socket types, Internet addresses, I/O functions, Unix system calls. 2. Declare variables for Socket ID, Portnumber, Socket addresses, Character buffer, etc. 3. Create Socket for Client. 4. Connect client socket to the server socket addresses. 5. Repeat the steps 8and 9 until the socket is closed.

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab


6. Send file name to the Connected Socket 7. Retrieve information from Connected Socket and display it..

116 of 107

Program

HTTP SERVER #include<fcntl.h> #include<stdlib.h> #include<unistd.h> #define SERV_TCP_PORT 9009 #define MAX 80 int main(int argc,char *argv[]) { FILE *fp; int sockfd,newsockfd,clength; struct sockaddr_in serv_addr,cli_addr; char s[MAX],t[MAX],str[MAX]; strcpy(t,"exit"); sockfd=socket(AF_INET,SOCK_STREAM,0); serv_addr.sin_family=AF_INET; serv_addr.sin_addr.s_addr=INADDR_ANY; serv_addr.sin_port=htons(SERV_TCP_PORT); bind(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr)); listen(sockfd,5); for(;;) { clength=sizeof(cli_addr); newsockfd=accept(sockfd,(struct sockaddr*)&cli_addr,&clength); close(sockfd);

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab


read(newsockfd,&str,MAX); printf("File Name Requested :%s\n",str); fp=fopen(str,"r"); while(fgets(s,79,fp)!=NULL) { printf("%s",s); write(newsockfd,s,MAX); } write(newsockfd,s,MAX); fclose(fp); exit(0); } printf("\nThe Requested file is tranfered...\n"); return 0; } HTTP CLIENT

117 of 107

#include<string.h> #include<fcntl.h> #include<stdlib.h> #include<unistd.h> #define SERV_TCP_PORT 9009 #define MAX 80 int main(int argc,char *argv[]) { FILE *fp; int sockfd; char s[MAX],name[MAX],sendline[MAX],recvline[MAX+1]; struct sockaddr_in serv_addr;

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab


strcpy(s,"exit"); sockfd=socket(AF_INET,SOCK_STREAM,0); serv_addr.sin_family=AF_INET; serv_addr.sin_addr.s_addr=inet_addr("127.0.0.1"); serv_addr.sin_port=htons(SERV_TCP_PORT); connect(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr)); for(;;) { printf("\nEnter the File Name:\n"); scanf("%s",sendline); printf("Enter the Destination File Name:\n"); scanf("%s",name); fp=fopen(name,"w"); write(sockfd,sendline,MAX); while(1) { read(sockfd,recvline,MAX); printf("%s",recvline); fputs(recvline,fp); } fclose(fp); exit(0); } close(sockfd); return 0; } Result

118 of 107

Thus the program was written in C in UNIX platform to enable and the output was verified.

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab Appendix A (SIMPLE PROGRAMS)

119 of 107

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); } }} 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");}

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

120 of 107

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 */ /* 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"); }
}

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() { int fd; struct sockaddr_in server; struct sockaddr_in client; /* file descriptors */ /* server's address information */ /* client's address information */

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 */

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab bzero(&(server.sin_zero),8); /* zero the rest of the structure */

121 of 107

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 ); } close(fd); /* close fd */
}

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() { int fd, fd2; struct sockaddr_in server; struct sockaddr_in client; /* file descriptors */ /* server's address information */ /* client's address information */

int sin_size; if ((fd=socket(AF_INET, SOCK_STREAM, 0)) == -1 ) /* calls socket() */ { printf("socket() error\n"); exit(-1); }

R.M.K Engineering College

Department of CSE

CS2307 - Network Lab

122 of 107

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) { printf("listen() error\n"); exit(-1); } printf("server is in accept mode \n "); 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 */ close(fd2); /* close fd2 */ } } /* calls listen() */

R.M.K Engineering College

Department of CSE

You might also like