npm lab manual

70
SRINIVASAN ENGINEERING COLLEGE PERAMBALUR-621212 Department of Information Technology IT1353 – NETWORK PROGRAMMING LABORATORY PREPARED BY T.Rajalakshmi Assistant Professor (IT), Srinivasan Engineering college,Perambalur-621212 Academic year(2012-13) VI SEMESTER

Upload: selvijegan

Post on 14-Apr-2015

216 views

Category:

Documents


8 download

TRANSCRIPT

Page 1: NPM Lab Manual

SRINIVASAN ENGINEERING COLLEGE

PERAMBALUR-621212

Department of Information Technology

IT1353 – NETWORK PROGRAMMING LABORATORY

PREPARED BY

T.Rajalakshmi

Assistant Professor (IT),

Srinivasan Engineering college,Perambalur-621212

Academic year(2012-13) VI SEMESTER

Page 2: NPM Lab Manual

PREFACE

Network Programming Management Laboratory manual is intended to provide a basic knowledge of network programming using Unix C for students and readers. This manual provides a guide for the developers in networking. Networking is developing technology becoming a new emerging trend and developing a variety of programmers and users.

Page 3: NPM Lab Manual

Acknowledgement

I give all glory and thanks to our god almighty for showering upon, the necessary wisdom and grace for accomplishing the lab manual.

I am highly indebted to our respectable chairman, SHRI.A.SRINIVASAN

founder of Dhanalakshmi Srinivasan Group of institutions for providing with sufficient facilities that contributed to the success in this endeavor.

I am very thankful to our reputable, beloved principal DR.B.KARTHIKEYAN M.E., Ph.D., for his continuous encouragement and for motivating me to complete this lab manual.

I would like to express my sincere thanks and deep sense of gratitude to our Head of the Department S. SATHISH KUMAR M.E., for his valuable guidance, suggestions and constant encouragement paved way for the completion of the manual.

Page 4: NPM Lab Manual

Contents

S.NO Title of the Experiment

1. Simulation of ARP / RARP.

2. Develop a client that contacts a given DNS server to resolve a given host name

3. Simulation of OSPF routing protocol.

4. Develop a client server application for chat.

5. Develop a trace route program.

6. Signal handling and handling zombie.

7. Implementation of RPC.

8. Write a client to download a file from HTTP server.

9. Implementation of FTP.

10. Multiplexed TCP server and client.

11. Study of NS2

Page 5: NPM Lab Manual

INTRODUCTION OF THE LANGUAGE

Unix has become popular among program developers as it includes several features which they find to be very desirable. C programming language files which are to be compiled by the cc command must end in the character ".c".

MAIN FEATURES

Features of C Programming Language :

C Programming is widely used in Computer Technology, We can say that C Programming is inspiration for development of other languages. We can use C Programming for different purposes. Below are some of the Features of C Programming language–

Low Level Features :

1. C Programming provides low level features that are generally provided by the Lower level languages. C is Closely Related to Lower level Language such as “Assembly Language“.

2. It is easier to write assembly language codes in C programming.

Portability :

1. C Programs are portable i.e they can be run on any Compiler with Little or no Modification

2. Compiler and Preprocessor make it Possible for C Program to run it on Different PC.

Powerfull

1. Provides Wide variety of ‘Data Types‘

2. Provides Wide variety of ‘Functions’

3. Provides useful Control & Loop Control Statements

• A Powerful Multi-User System

1. More than one user can use the machine at a time supported via terminals (serial or network

connection)

2. a regular timed interrupt event (provided by a clock)

3. saving the interrupted programs state and data

4. restoring the next programs state and data

5. running that program till the next timed interrupt occurs

• Shell Command Interpreter

• Hierarchical File Structure

• Multi-Tasking with Background Processing Capabilities (&)

more than one program can be run at a time

• Extensible via the C Language

• Networking Capabilities

• Security Features

• Widely Accepted

• More Efficient

APPLICATIONS

Page 6: NPM Lab Manual

Unix C language is used for creating

• Computer applications

• Writing embedded software/firmware for various electronics

• Industries

• Communications products which use micro-controllers

• Developing verification software, test code, simulators etc.

• Hardware products.

• Research

• System designing

• Networking

• Database connectivity

Best applications written in C/C++ are

• Adobe Systems

• Google Applications

• MySQL

• Microsoft

• Symbian OS

Page 7: NPM Lab Manual

LIST OF EXPERIMENTS

1. Simulation of ARP / RARP.

2. Develop a client that contacts a given DNS server to resolve a given hostname.

3. Simulation of OSPF routing protocol.

4. Develop a client server application for chat.

5. Develop a trace route program.

6. Signal handling and handling zombie.

7. Implementation of RPC.

8. Write a client to download a file from HTTP server.

9. Implementation of FTP.

10. Multiplexed TCP server and client.

11. Study of NS2/Glomosim.

Page 8: NPM Lab Manual

IT1353 – NETWORK PROGRAMMING LABORATORY

Objective

• To effectively use Unix and C to write, test, debug, and maintain modest-sized program.

• To use standard C libraries (including the standard C library, stdio, and ctype) and their associated header files effectively in writing programs

Page 9: NPM Lab Manual

Ex No. 1A

SIMULATION OF ARP

Aim

To map the IP address with the MAC address using ARP.

Explanation

Address Resolution Protocol (ARP) is a telecommunications protocol used for resolution of network layer addresses into link layer addresses.

• Get the IP address from the client. • If there is no response client display there is no response from the system

• If the client responses with the IP address, convert it to MAC address and display it.

Algorithm

Step 1. Include the necessary header file Step 2. Get the IP address to find from the MAC address Step 3. Convert the character format IP address to 32 bit network byte structure Step 4. Map the ip address with the ARP structure Step 5. Create the socket for the particular machine Step 6. Retrieve the hardware address from ARP cache Step 7. Print the hardware address

Page 10: NPM Lab Manual

SIMULATION OF ARP PROGRAM #include<stdio.h> #include<string.h> #include<stdlib.h> int main() { int sys[5],ip[5],et[5],i,arp; for(i=0;i<5;i++) { et[i]=i*3; ip[i]=rand()%50; } arp=rand()%6; printf("\nSERVER->IP ADDRESS=192.168.11%d",ip[arp]); for(i=0;i<5;i++) { if(i!=arp) printf("\nSYSTEM%d->NO RESPONSE",i+10); else printf("\nSYSTEM%d->ETHERNET ADDRESS=%d(a.b%d 10.25%d",i+1,(i*2)%10,et[i]); } getch(); return 0; } OUTPUT SERVER->IP ADDRESS=192.168.11.30 SYSTEM10->NO RESPONSE SYSTEM2->ETHERNET ADDRESS=2(a.b3 10.25956 SYSTEM12->NO RESPONSE SYSTEM13->NO RESPONSE SYSTEM14->NO RESPONSE

Page 11: NPM Lab Manual

Result

Hence the IP address with the MAC address using ARP is mapped successfully

VIVA QUESTION AND ANSWER

Define ARP?

Address Resolution Protocol (ARP) is a telecommunications protocol used for resolution of network layer addresses into link layer addresses.

Define IP address?

An Internet Protocol address (IP address) is a numerical label assigned to each device participating in a computer network

Define MAC Address?

A Media Access Control address (MAC address) is a unique identifier assigned to network interfaces for communications on the physical network segment

Page 12: NPM Lab Manual

Ex No.1B

SIMULATION OF RARP

Aim

To map the ip address with the MAC address using RARP.

Explanation

RARP permits a physical address, such as an Ethernet address, to be translated into an IP address. Hosts such as diskless workstations often only know their hardware interface addresses, or MAC address, when booted but not their IP addresses. They must discover their IP addresses.

• Get the MAC address from the client. • If there is no response client display there is no response from the system

• If the client responses with the MAC address, convert it to IP address and display it.

Algorithm

Step 1. Include the necessary header file Step 2. Get the IP address to find from the MAC address Step 3. Convert the character format IP address to 32 bit network byte structure Step 4. Map the ip address with the ARP structure Step 5. Create the socket for the particular machine Step 6. Retrieve the hardware address from ARP cache Step 7. Print the hardware address

Page 13: NPM Lab Manual

SIMULATION OF RARP PROGRAM : #include<stdio.h> #include<string.h> #include<stdlib.h> int main() { int sys[5],ip[5],et[5],i,arp; clrscr(); for(i=0;i<5;i++) { et[i]=i*3; ip[i]=rand()%50; } arp=rand()%6; printf("rarp\n"); printf("\nSYSTEM%d->ETHETRMNET ADDRESS=%dCA.B%d10.25%d",i+1); for(i=0;i<5;i++) { if(i!=arp) printf("\nSYSTEM%d->NO RESPONSE",i+1); else printf("\IP ADDRESS=192.158.11.%d",ip[1]); } getch(); return 0; } OUTPUT: SYSTEM6->ETHETRMNET ADDRESS=950CA.B92 10.25%d SYSTEM1->NO RESPONSE IP ADDRESS=192.158.11.30 SYSTEM3->NO RESPONSE SYSTEM4->NO RESPONSE SYSTEM5->NO RESPONSE

Page 14: NPM Lab Manual

Result

Hence the IP address with the MAC address using RARP is mapped successfully

VIVA QUESTION AND ANSWER

Define RARP?

Reverse Address Resolution Protocol permits a physical address, such as an Ethernet address, to be translated into an IP address

What are the other names for MAC address?

It may also be known as an Ethernet hardware address (EHA), hardware address or physical address

Define IP address?

An Internet Protocol address (IP address) is a numerical label assigned to each device participating in a computer network

Define MAC Address?

A Media Access Control address (MAC address) is a unique identifier assigned to network interfaces for communications on the physical network segment

Page 15: NPM Lab Manual

Ex No.2

DNS SERVER TO RESOLVE A GIVEN HOST NAME

Aim

To develop a client that contacts a given DNS server to resolve a given hostname.

Explanation

Domain Name System is the naming convention that divides the Internet into logical domains identified in Internet Protocol version 4 (IPv4) as a 32-bit portion of the total address

• Get the host name to be resolve using gethostname() • Check the host name using nslookup • Print the IP address, host name, Address length and Address type. • List the addresses stored in lookup

Algorithm

Step 1. Find the host name by using gethostbyname() Step 2. The host name is followed by the list of alias names Step 3. Pointer points to the array of pointers to the individual address Step 4. For each address call the inet_ntop() and print the returned string

Page 16: NPM Lab Manual

DNS SERVER TO RESOLVE A GIVEN HOST NAME PROGRAM #include<stdio.h> #include<netdb.h> #include<arpa/inet.h> #include<netinet/in.h> int main(int argc,char**argv) { char h_name; int h_type; struct hostent *host; struct in_addr h_addr; if(argc!=2) { fprintf(stderr,"USAGE:nslookup\n"); } if((host=gethostbyname(argv[1]))==NULL) { fprintf(stderr,"(mini)nslookup failed on %s\n",argv[1]); } h_addr.s_addr=*((unsigned long*)host->h_addr_list[0]); printf("\n IP ADDRESS=%s\n",inet_ntoa(h_addr)); printf("\n HOST NAME=%s\n",host->h_name); printf("\nADDRESS LENGTH =%d\n",host->h_length); printf("\nADDRESS TYPE=%d\n",host->h_addrtype); printf("\nLIST OF ADDRESS=%s\n",inet_ntoa(h_addr_list[0])); } OUTPUT [it28@localhost ~]$ vi nandns.c [it28@localhost ~]$ cc nandns.c [it28@localhost ~]$ ./a.out 90.0.0.36 IP ADDRESS=90.0.0.36 HOST NAME=90.0.0.36 ADDRESS LENGTH =4 ADDRESS TYPE=2 LIST OF ADDRESS=90.0.0.36

Page 17: NPM Lab Manual

Result

Hence the program to develop a client that contacts a given DNS server to resolve a given host name is executed successfully.

VIVA QUESTION AND ANSWER

Define DNS?

Domain Name System is the naming convention that divides the Internet into logical domains identified in Internet Protocol version 4 (IPv4) as a 32-bit portion of the total address

Define host name?

A hostname is a label that is assigned to a device connected to a computer network and that is used to identify the device in various forms of electronic communication such as the World Wide Web, e-mail or Usenet.

Define DNS server?

DNS servers, which store and answer name queries for resource records.

Define DNS Client?

DNS clients, also known as resolvers, which query servers to look up and resolve names to a type of resource record specified in the query.

Some examples of DNS?

Hostname (www), the Domain Name (mydomain) and the Top Level Domain (com)

Page 18: NPM Lab Manual

Ex No.3

SIMULATION OF OSPF ROUTING PROTOCOL

Aim

To write a program to simulate the OSPF routing protocol

Explanation

Open Shortest Path First (OSPF) is a link-state routing protocol for Internet Protocol (IP) networks. It is used to allow routers to dynamically learn routes from other routers and to advertise routes to other routers.

OSPF selects the best routes by finding the lowest cost paths to a destination. All router interfaces (links) are given a cost. The cost of a route is equal to the sum of all the costs configured on all the outbound links between the router and the destination network, plus the cost configured on the interface that OSPF received the Link State Advertisement on

• Get the distance between the nodes • Get the distance vector of the hosts • Compare the distance of all nodes and find the shortest among them

• Display the shortest distance between the nodes

Algorithm

Step 1. Read the number of nodes Step 2. Read the distance between one node to the other for every node Step 3. Assign the distance from a node to itself as zero Step 4. Find the shortest path from the given node to other node and design the same as

distance Step 5. Print the distance from one node to every other node in the form of matrix.

Page 19: NPM Lab Manual

SIMULATION OF OSPF ROUTING PROTOCOL PROGRAM #include<stdio.h> main() { int d[10][10],inter[10][10]; int i,j,k,m; printf("\n Enter the distance between Hosts:"); for(i=1;i<=4;i++) { for(j=0;j<=4;j++) { inter [i][j]=0; } } for(i=1;i<=4;i++) { for(j=1;j<=4;j++) { printf("\n Enter the distance between %d and %d ",i,j); scanf("%d",&d[i][j]); } } printf("\n Enter the distance Vector \n"); printf("\n\t H1 \t H2 \t H3 \t H4 \n"); for(i=1;i<=4;i++) { printf("\n Host %d: \t",i); for(j=1;j<=4;j++) { printf("%d\t",d[i][j]); }} for(i=1;i<=4;i++) { for(j=1;j<=4;j++) { m=0; for(k=1;k<=4;k++) { if(d[i][j]>d[i][k]+(d[k][j])) { d[i][j]=d[i][k]+d[k][j]; inter[j][m]=k; }

Page 20: NPM Lab Manual

m=m+1; } } } printf("\n Minimum distance host1 another \n"); i=1; printf("\n H1 \t H2 \t H3 \t H4 \t"); for(j=1;j<=4;j++) { printf("%d\t",d[i][j]); } printf("\n\n"); }

Page 21: NPM Lab Manual

OUTPUT: [it28@localhost ~]$ vi ospf.c [it28@localhost ~]$ cc ospf.c [it28@localhost ~]$ ./a.out Enter the distance between Hosts: Enter the distance between 1 and 1 1 Enter the distance between 1 and 2 2 Enter the distance between 1 and 3 3 Enter the distance between 1 and 4 4 Enter the distance between 2 and 1 1 Enter the distance between 2 and 2 2 Enter the distance between 2 and 3 3 Enter the distance between 2 and 4 4 Enter the distance between 3 and 1 1 Enter the distance between 3 and 2 2 Enter the distance between 3 and 3 3 Enter the distance between 3 and 4 4 Enter the distance between 4 and 1 1 Enter the distance between 4 and 2 2 Enter the distance between 4 and 3 3 Enter the distance between 4 and 4 4 Enter the distance Vector H1 H2 H3 H4 Host 1: 1 2 3 4 Host 2: 1 2 3 4 Host 3: 1 2 3 4 Host 4: 1 2 3 4 Minimum distance host1 another

H1 H2 H3 H4 1 2 3 4

Page 22: NPM Lab Manual

Result

Hence a program to simulate the OSPF routing protocol is executed successfully.

VIVA QUESTION AND ANSWER

Define OSPF?

Open Shortest Path First (OSPF) is a link-state routing protocol for Internet Protocol (IP) networks. It is used to allow routers to dynamically learn routes from other routers and to advertise routes to other routers.

Define Routers?

A router is specialized computer connected to more than one network running software that allows the router to move data from one network to another.

How OSPF works?

OSPF selects the best routes by finding the lowest distance paths to a destination. All router interfaces (links) are given a distance.

Page 23: NPM Lab Manual

Ex No.4

DEVELOP A CLIENT SERVER APPLICATION FOR CHAT

Aim

To write a program to develop a client server application for chat.

Explanation

A server selectively shares its resources, a client is initiates contact with a server in order to make use of a resource. Data, CPUs, printers, and data storage devices are all examples of resources.

The client creates a Socket to connect himself to the server. This socket allows you to get the input and output streams. Then it creates an InetAddress object using the host name or its IP. Then it send and receives data. The server listens to the connection accepts it and then starts chatting with client.

• Initialize the socket of client and server using socket (AF_INET,SOCK_STREAM,0) • Initialize server family, port and address • Connect the client with server using connect() and bind it • Server accepts the connection using accept() • The chat starts with port address and a message • The client starts messaging and server responses it with reply message • The connection is closed in both sides using close()

Algorithm

Server:

Step 1. Create s socket with address family AF_INET, type SOCK_STREAM and default protocol

Step 2. Initialize the socket and set the attributes. Assign any port number as desired Step 3. Bind the server to socket using bind() Step 4. Establish the listen function Step 5. Wait for client request establish a connection using accept() Step 6. Repeat step7 to 9 until server send “bye” Step 7. Reads message from the client using read() function Step 8. If the client message is “bye” goto step 10 Step 9. Accept the server message and write it to the client using write() Step 10. Close the connection Step 11. Goto step5

Client:

Step 1. Create s socket with address family AF_INET, type SOCK_STREAM and default protocol

Step 2. Initialize the socket and set the attributes. Assign required port number Step 3. Connect to the server using connect() to initiate port number Step 4. Repeat step 5 to 7 until server send “bye” Step 5. Accept the server message and write it to the client using write() Step 6. If the client message is “bye” Step 7. Reads message from the client using read() function

Page 24: NPM Lab Manual

DEVELOP A CLIENT SERVER APPLICATION FOR CHAT PROGRAM: CLIENT: #include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<netinet/in.h> #include<string.h> #include<sys/socket.h> #include<arpa/inet.h> #include<errno.h> int main() { int sd,nsd,i,port=8787; char c[30]="\0",buf[1024]="\0",buf1[1024]="\0"; FILE *fp; struct sockaddr_in ser; if((sd=socket(AF_INET,SOCK_STREAM,0))<0) { printf("\n error:socket creation"); return 0; } bzero((char*)&ser,sizeof(ser)); printf("\n port address is %d",port); ser.sin_family=AF_INET; ser.sin_port=htons(port); ser.sin_addr.s_addr=htonl(INADDR_ANY); if(connect(sd,(struct sockaddr*)&ser,sizeof(ser))==-1) { printf("\n error:binding"); return 0; } printf("client module\n"); while(1) { printf("client"); fgets(buf1,sizeof(buf1),stdin); if(buf1[0]=='q'); { printf(" exit(0)"); } if((i=send(sd,buf1,sizeof(buf1),0))==-1) {

Page 25: NPM Lab Manual

perror("send"); break; } strcpy(buf1,"\0"); if((i=recv(sd,buf,sizeof(buf),0))==-1) { perror("recv"); break; } printf("server%s\n",buf); } close(sd); return 0; } OUTPUT: [it28@localhost ~]$ vi ccli.c [it28@localhost ~]$ cc ccli.c [it28@localhost ~]$ ./a.out port address is 8787client module clienthai exit(0)serverhai clienti am student exit(0)serveri am proff client PROGRAM: SERVER: #include<unistd.h> #include<sys/types.h> #include<netinet/in.h> #include<string.h> #include<sys/socket.h> #include<stdio.h> int main() { int sd,nsd,cpid,n,i,port=8787; char c[30]="\0",buf1[1024]="\0",buf[1024]="\0"; struct sockaddr_in ser; struct sockaddr_in cli; FILE *fp; if((sd=socket(AF_INET,SOCK_STREAM,0))<0) {

Page 26: NPM Lab Manual

printf("\n Error:socket creation"); return 0; } bzero((char*)&ser,sizeof(ser)); ser.sin_family=AF_INET; ser.sin_port=htons(port); ser.sin_addr.s_addr=htonl(INADDR_ANY); if(bind(sd,(struct sockaddr*)&ser,sizeof(ser))<0) { printf("\n error:binding"); return 0; } i=sizeof(cli); listen(sd,1); printf("\n server module \n"); if((nsd=accept(sd,(sd,(struct sockaddr*)&cli),&i))==-1) { perror("accept"); printf(" exit(0)"); } while(1) { if((i=recv(nsd,buf1,sizeof(buf1),0))==-1) { perror("send"); break; } printf("Client:%s\n",buf1); printf("server"); fgets(buf,sizeof(buf),stdin); if((i=send(nsd,buf,sizeof(buf),0))==-1) { perror("recv"); break; } if(buf[0]=='q') printf(" exit(0)"); } if(nsd==-1) { printf("\n error:client accept the problem"); return 0; } close(sd); close(nsd); return 0; }

Page 27: NPM Lab Manual

OUTPUT: [it28@localhost ~]$ vi cser.c [it28@localhost ~]$ cc cser.c [it28@localhost ~]$ ./a.out server module hai Client:hai serverClient:i am student serveri am proff Client:i am student Server

Page 28: NPM Lab Manual

Result

Hence program to develop a client server application for chat is executed successfully.

VIVA QUESTION AND ANSWERS

Define Client?

A client is a computer or computer program that initiates contact with a server in order to make use of a resource.

Define server?

A server is a computer system that selectively shares its resources. Data, CPUs, printers, and data storage devices are all examples of resources.

Define Socket?

A network socket is an endpoint of an inter-process communication flow across a computer network. Today, most communication between computers is based on the Internet Protocol; therefore most network sockets are Internet sockets.

What is the use of listen()?

listen - listen for socket connections and limit the queue of incoming connections

What is the use of connect()?

The connect() function shall attempt to make a connection on a socket.

What is the use of accept()?

The accept() function shall extract the first connection on the queue of pending connections, create a new socket with the same socket type protocol and address family as the specified socket, and allocate a new file descriptor for that socket.

Define client server model?

In the client-server model, the server is a centralized system. The more simultaneous clients a server has, the more resources it needs.

Page 29: NPM Lab Manual

Ex No.5

DEVELOP A TRACE ROUTE PROGRAM.

Aim

To write a program to develop a trace route program.

Explanation

• Traceroute is a computer network diagnostic tool for displaying the route (path) and

measuring transit delays of packets across an Internet Protocol (IP) network.

• Traceroute sends a sequence of Internet Control Message Protocol (ICMP) echo request

packets addressed to a destination host.

• Determining the intermediate routers traversed involves adjusting the time-to-live (TTL), aka

hop limit, Internet Protocol parameter.

• Routers decrement this and discard a packet when the TTL value has reached zero, returning

the ICMP error message ICMP Time Exceeded.

• Traceroute works by increasing the TTL value of each successive set of packets sent.

• Traceroute uses the returned ICMP messages to produce a list of routers that the packets have

traversed.

• Implementations of traceroute rely on ICMP (type 11) packets being sent to the originator.

Algorithm

Step 1. Add the ICMP header file to program for developing a trace route Step 2. Declare the variables and data types for ICMP header which includes message type,

header length, version length of packet, protocol source, destination, IP, unique ID, sequence etc.

Step 3. Use switch cases for the response from destination router along the way, cannot reach to destination to the source.

Step 4. It display maximum of 30 hops Step 5. This program runs under super user only.

Page 30: NPM Lab Manual

DEVELOP A TRACE ROUTE PROGRAM

PROGRAM : #include<stdio.h> #include<stdlib.h> #include<errno.h> #include<string.h> #include<sys/un.h> #include<sys/time.h> #include<sys/times.h> #include<sys/iostl.h> #include<unistd.h> #include<netinet/in.h> #include<netdb.h> #define ICMP_ECHOREPLY 0 #define ICMP_DESTUNREACH 3 #define ICMP_SRCQUENCH 4 #define ICMP_REDIRECT 5 #define ICMP_ECHO 8 #define ICMP_TIMEOUT 11 #define ICMP_PARMERR 12 #define MAX_HOPS 30 #define ICMP_MIN 8 typedef struct iphdr { unsigned int h_len:4; //Length of the header unsigned int version:4; //Version of IP unsigned char tos; //Type of service unsigned short total_len; //Total length of the packet unsigned short ident; //Unique identifier unsigned short frag_and_flags; //Flags unsigned char ttl; //Time to live unsigned char proto; //Protocol(TCP,UDP etc) unsigned short checksum; //IP checksum unsigned int sourceIP; //Source IP unsigned int destIP; //Destination IP } IpHeader; typedef struct_ihdr { char i_type; //ICMP message type char i_code; //Sub code unsigned short i_cksum; unsigned short i_id; //Unique id unsigned short i_seq; //Sequence number unsigned long timestamp; } IcmpHeader; #define DEF_PACKET_SIZE

Page 31: NPM Lab Manual

#define MAX_PACKET void usage(char* progname) { printf(“usage:%s host-name [max-hops]\n”,progname); exit(-1); } int set_ttl(int s,int nTimeToLive) { int nRet; nRet=setsockopt(s,IPPROTO_IP,IP_TTL,(int*)&nTimeToLive,sizeof(int)); if(nRet<0) {

perror(“setsockopt in set_ttl:”); return 0;

} return 1; } int decode_resp(char* buf,int bytes,struct sockaddr_in* from,int ttl) { IpHeader* iphdr = NULL; IcmpHeader* icmphdr = NULL; unsigned short iphdrlen; struct hostent* lpHostlent = NULL; struct in_addr inaddr = from->sin_addr; iphdr = (IpHeader*)buf; iphdrlen = iphdr->h_len* 4; if(bytes<iphdrlen + ICMP_MIN) printf(“Too few bytes from %s\n”,inet_ntoa(from->sin_addr)); icmphdr = (IcmpHeader*)(buf + iphdrlen); switch(icmphdr->i_type) { case ICMP_ECHOREPLY: //Response from destination lpHostent = gethostbyaddr((const char*)&from->sin_addr,4,AF_INET); if(lpHostent!=NULL) printf(“gethostbyaddr success\n”); return 1; break; case ICMP_TIMEOUT: //Response from router along the way printf(“%2d %s\n”,ttl,inet_ntoa(inaddr)); return 0; break; case ICMP_DESTUNREACH: //Can’t reach the destination at all printf(“%2d %s reports:Host is unreachable\n”,ttl,inet_ntoa(inaddr)); return 1;

Page 32: NPM Lab Manual

break; default: printf(“non-echo type %drecvd\n”,icmphdr->i_type); return 1; break; } return 0; } unsigned short checksum(unsigned short* buffer,int size) { unsigned long cksum = 0; while(size > 1) { cksum+ =*buffer++; size- = sizeof(unsigned short); } if(size) cksum+ = *(unsigned char*)buffer; cksum = (cksum >> 16)+(cksum & 0xffff); cksum+ = (cksum >> 16); return(unsigned short)(~cksum); } void fill_icmp_data(char* icmp_data,int datasize) { IcmpHeader* icmp_hdr; char* datapart; icmp_hdr = (IcmpHeader*)icmp_data; icmp_hdr->i_type = ICMP_ECHO; icmp_hdr->i_code = 0; icmp_hdr->i_id = (unsigned short)getpid(); icmp_hdr->i_cksum = 0; icmp_hdr->i_seq = 0; datapart = icmp_data + sizeof(IcmpHeader); memset(datapart,’E’,datasize – sizeof(IcmpHeader)); } long GetTickCount() { struct tms tm; return times(&tm); } int main(int argc,char** argv) { int sockRaw; struct hostent* hp = NULL; struct sockaddr_in dest,

Page 33: NPM Lab Manual

from; int ret,datasize,fromlen = sizeof(from),done = 0,maxhops,ttl = 1; char* icmp_data,*recvbuf; int bOpt; unsigned short seq_no = 0; struct timeval timeout; if(argc < 2) usage(argv[0]); if(argc ==3) maxhops = MAX_HOPS; sockRaw = socket(AF_INET,SOCK_RAW,IPPROTO_ICMP); if(sockRaw <0) { perror(“socket”); exit(-1); } timeout.tv_sec = 1; timeout.tv_usec = 0; ret = setsockopt(sockRaw,SOL_SOCKET,SO_RCVTIMEO,&timeout,sizeof(struct timeval)); if(ret == -1) { perror(“setsockopt in send:”); return -1; } Memset(&dest,0,sizeof(struct sockaddr_in)); dest.sin_ family = AF_INET; if((dest.sin_addr.s_addr = inet_addr(argv[1])) ==INADDR_NONE) { hp=gethostbyname(argv[1]); if(hp) memcpy(&dest.sin_addr,hp->h_addr,hp->h_length); else { printf(“Unable to resolve%s\n”,argv[1]); exit(-1); } } datasize=DEF_PACKET_SIZE; datasize+=sizeof(IcmpHeader); icmp_data=malloc(MAX_PACKET*sizeof(char)); recvbuf=malloc(MAX_PACKET*sizeof(char)); if((!icmp_data)||(!recvbnf)) { perror(“malloc:”); return -1; } memset(icmp_data,0,MAX_PACKET);

Page 34: NPM Lab Manual

fill_icmp_data(icmp_data,datasize); printf(“\n Tracing route to %s over a maximum of %d hops:\n\n”,argv[1],maxhops); for(tt1=1;((ttl<maxhops)&&(!done));ttl++) { int bwrote; set_ttl(sockRaw,ttl); ((IcmpHeader*)icmp_data)->i_cksum=0; ((IcmpHeader*)icmp_data)->timestamp=GetTickCount(); ((IcmpHeader*)icmp_data)->i_seq=seq_no++; ((IcmpHeader*)icmp_data)->i_cksum=checksum((unsigned short*)icmp_data,datasize); Bwrote=sendto(sockRaw,icmp_data,datasize,0,(struct sockaddr*)&dest,sizeof(dest)); If(bwrote<0) { perror(“sendto:”); return -1; } ret=recvfrom(sockRaw,recvbuf,MAX_PACKET,0,(struct sockaddr*)&from,&fromlen); if(ret<0) { perror(“recvfrom:”); return -1; } done=decode_resp(recvbuf,ret,&from,ttl); sleep(1); } free(recvbuf); free(icmp_data); return 0; } OUTPUT: [This program runs under superuser only] [root@localhost~]# vi tracert.c [root@localhost~]#cc tracert.c [root@localhost~]# ./a.out www.dsgroups.org over a maximum of 30 hops:

1 192.168.11.1 2 210.212.249.179 3 210.212.249.179

Page 35: NPM Lab Manual

Result

Hence a program to develop a trace route program is executed successfully.

VIVA QUESTIONS AND ANSWERS

Define Trace route?

Traceroute is a computer network diagnostic tool for displaying the route (path) and measuring transit delays of packets across an Internet Protocol (IP) network

Define TTL?

Time to live (TTL) is a mechanism that limits the lifespan or lifetime of data in a computer or network

Use of ICMP in trace route?

Traceroute uses the returned ICMP messages to produce a list of routers that the packets have

traversed.

Define ICMP?

ICMP is a network protocol useful in Internet Protocol (IP) network management and administration. ICMP is a required element of IP implementations.

Page 36: NPM Lab Manual

Ex No.6A

SIGNAL HANDLING

Aim

To write a program to handle signal by system call.

Explanation

A signal is a limited form of inter-process communication used in Unix. It is an asynchronous notification sent to a process or to a specific thread within the same process in order to notify it of an event that occurred. When a signal is sent, the operating system interrupts the target process's normal flow of execution. Execution can be interrupted during any non-atomic instruction.

• Initialize the signal using signal() • Set a task to print and this task is repeated until the signal is interrupted

Algorithm

Step 1. Read the input Step 2. Initialize or call the function declaring it Step 3. Set a loop or perform a task Step 4. In between it is interrupted by a signal Step 5. Perform addition and return back to previous task Step 6. Display the result

Page 37: NPM Lab Manual

SIGNAL HANDLING PROGRAM #include<stdio.h> #include<signal.h> int main() { int i; signal(SIGINT,0); for(i=0;i<5;i++) { printf("we are in third year\n"); sleep(1); } } OUTPUT [it28@localhost ~]$ vi signal.c [it28@localhost ~]$ cc signal.c [it28@localhost ~]$ ./a.out we are in third year we are in third year we are in third year we are in third year we are in third year

Page 38: NPM Lab Manual

Result

Hence a program to handle signal by system call is executed successfully.

VIVA QUESTIONS AND ANSWERS

Define signal handling

A signal is a limited form of inter-process communication used in Unix. It is an asynchronous notification sent to a process or to a specific thread within the same process in order to notify it of an event that occurred.

Define Signal()

When a signal() is called , the operating system interrupts the target process's normal flow of execution.

Page 39: NPM Lab Manual

Ex No.6B

HANDLING ZOMBIE

Aim

To write a program to handle zombie by Unix document

Explanation

A zombie process or dead process is a process that has completed execution but still has an entry in the process table.

Zombies usually happens if a child-process was spawned, but died before the parent-process started "listening" for it's return-value. As the child is technically done (the subprogram is finished), except that nobody was there to receive it's return-value, it becomes a zombie.

In order to deal with Zombies, you need to know three things about each process:

1. The process ID (PID)

2. The process's parent ID (PPID)

3. The state of the process.

Algorithm

Step 1. Read the input Step 2. Initialize or call the function declaring it Step 3. Set a loop or perform a task Step 4. In between it is interrupted by a signal Step 5. Perform addition and return back to previous task Step 6. Display the result

Page 40: NPM Lab Manual

HANDLING ZOMBIE PROGRAM #include<stdio.h> int main() { int i=0,pid; printf("Ready to fork...\n"); pid=fork(); if(pid==0) { printf("child starts...\n"); for(i=0;i<5;i++) { printf("I am a child \n"); sleep(1); } printf("child ends...\n"); } } OUTPUT [it28@localhost ~]$ vi handling.c [it28@localhost ~]$ cc handling.c [it28@localhost ~]$ ./a.out Ready to fork... child starts... I am a child [it28@localhost ~]$ I am a child I am a child I am a child I am a child child ends...

Page 41: NPM Lab Manual

Result

Hence a program to handle zombie by Unix document is executed successfully.

VIVA QUESTIONS AND ANSWERS

Define Zombie process? A zombie process or dead process is a process that has completed execution but still has an entry in the process table How to deal with zombie? The process ID (PID)

2. The process's parent ID (PPID)

3. The state of the process.

Page 42: NPM Lab Manual

Ex No.7

IMPLEMENTATION OF RPC

Aim

To write a program to implement RPC.

Explanation

A remote procedure call (RPC) is an inter-process communication that allows a computer program to cause a subroutine or procedure to execute in another address space (commonly on another computer on a shared network) without the programmer explicitly coding the details for this remote interaction

• In RPC, the sender makes a request in the form of a procedure, function, or method call. RPC

translates these calls into requests sent over the network to the intended destination.

• The RPC recipient then processes the request based on the procedure name and argument list,

sending a response to the sender when complete.

• The process is initiated by the client, which sends a request message to a known remote server

to execute a specified procedure with supplied parameters.

• The remote server sends a response to the client, and the application continues its process.

• While the server is processing the call, the client is blocked,it waits until the server has

finished processing before resuming execution.

Algorithm

Step 1. Write a specification file “remote x” Step 2. Use “rpegen” to generate file (remote.h, remote_svc.c and remote_clnt.c) Step 3. Use rpegen to generate sample server program Step 4. Use rpegen to generate sample client program Step 5. Modify sample server and sample client program Step 6. Use gcc to compile server program and client program Step 7. Login to a machine to run the server program or run in background Step 8. Login to another machine to run the client program Step 9. Use rcpinfor to manage RPC resource

Page 43: NPM Lab Manual

IMPLEMENTATION OF RPC PROGRAM /*program: remote.x*/ program REMOTE_PROG{ version REMOTE_VERS{ string REMOTE_USER(void)=1; }=1; }=0x32345678; /*Program: remote server.c*/ #include<stdio.h> #include<string.h> #include<utmp.h> #include"remote.h" char** remote_users_1_svc(void*argp,struct svc_req*rqstp) { static char*result; FILE *fp; struct utmp tmp; char buffer[1024]; char tmp_buff[10]; buffer[0]='\0'; fp=fopen("/var/run/utmp","rb"); while(!feof(fp)){ fread(&tmp,sizeof(struct utmp),1,fp); if(strlen(tmp.ut_name)){ sprintf(tmp_buff,"%.8s",tmp.ut_name); strcat(buffer,tmp_buff); } } fclose(fp); result=buffer; return&result; } /*Program Name: remote users.c */ #include<stdio.h> #include"remote.h" void remote_prog_1(char *host) { CLIENT *clnt; char**result_1; char *remote_users_1_arg; #ifndef DEBUG clnt=clnt_create(host,REMOTE_PROG,REMOTE_VERS,"udp");

Page 44: NPM Lab Manual

if(clnt==NULL) { clnt_pcreateerror(host); exit(1); } #endif /*DEBUG*/ result_1=remote_users_1_((void*)&remote_users_1_arg,clnt); if(result_1==(char**)NULL){ clnt_perror(clnt,"call failed"); } printf("Users logging on server %s\n%s\n",host,*result_1); #ifndef DEBUG clnt_destroy(clnt); #endif /*DEBUG*/ } int main(int argc,char *argv[]) { char *host; if(argc <2){ printf("usage: %s Server_host \n",argv[0]); exit(1); } host=argv[1]; remote_prog_1(host); exit(0); } //login.c #include<stdio.h> #include<string.h> #include<utmp.h> int main(int argc,char*argv[]) { /*static char*result;*/ FILE *fp; struct utmp tmp; char buffer[1024]; char tmp_buff[10]; buffer[0]='\0'; fp=fopen("/var/run/utmp",rb); while(!feof(fp)){ fread(*tmp,sizeof(struct utmp),1,fp); if(strlen(tmp.ut_name)){ sprintf(tmp_buff,"%.8s",tmp.ut_name); strcat(buffer.tmp_buff); } }

Page 45: NPM Lab Manual

fclose(fp); printf("%s\n",buffer); } OUTPUT [it28@localhost ~]$ vi remote.x [it28@localhost ~]$ vi nanrpc.x [it28@localhost ~]$ vi nanrpc.c [it28@localhost ~]$ rpcgen remote.x [it28@localhost ~]$ c [it28@localhost ~]$ rpcgen remote.x [it28@localhost ~]$ rpcgen -Ss remote.x >remote_server.c [it28@localhost ~]$ rpcgen -Sc remote.x >remote_user.c [it28@localhost ~]$ gcc -o remote_server remote_server.c remote_svc.c -Insl [it28@localhost ~]$ gcc -o remote _user remote_user.c remote_clnt.c -Insl gcc: _user: No such file or directory [it28@localhost ~]$ cc login.c [it28@localhost ~]$ ./a.out pcd rebootrunlevelLOGINLOGINLOGINLOGINLOGINLOGINit28it12it15it28it17cplab32cplab31it15it20it1it5

Page 46: NPM Lab Manual

Result

Hence a program to implement RPC is executed successfully.

VIVA QUESTIONS AND ANSWERS

Define RPC A remote procedure call (RPC) is an inter-process communication that allows a computer program to cause a subroutine or procedure to execute in another address space (commonly on another computer on a shared network) without the programmer explicitly coding the details for this remote interaction

Define remote server

Computer that is not attached to a user'skeyboard but over which he or she has some degree of control, whether it is in the same room, another part of a building, or another part of the world. Define rpegen?

Rpegen is used to create files for remote server and client.

Page 47: NPM Lab Manual

Ex No.8

DOWNLOAD A FILE FROM HTTP SERVER

Aim

To write a program to download a file from HTTP server

Explanation

• Create a file buffer to read the contents of file • Get the host name and send a request to the host • Create a socket and connect to the socket. (AF_INET, SOCK_STREAM) • Initialize the socket with inet address and host name • Send a request to the host to download the file • If the connection is established, read the contents of the file and copy it to the file buffer • If the file is fully read close the connection

Algorithm

Step 1. Set the command line argument and allocate yes or no for the rest of argv[1]=’1’ Step 2. Copy ‘I’ info host and info integers Step 3. Otherwise assign port to argv[1] Step 4. Print the host and the request Step 5. Create a socket and connect the socket Step 6. Print the download page into a buffer Step 7. Print and then open a file in a write mode. Write the download page into the file Step 8. Close the socket and file

Page 48: NPM Lab Manual

DOWNLOAD A FILE FROM HTTP SERVER PROGRAM #include<stdio.h> #include<stdlib.h> #include<netdb.h> #include<netinet/in.h> #include<arpa/inet.h> #include<sys/types.h> #include<sys/codket.h> #define size 100 int main(int argc,char *argv[]) { struct sockaddr_in sock; struct hostent *hp,port; char *req, *hostname, *cp; FILE *local; char buff[size]; int con,i,l,nrv,sd; if(argc!=3) { printf("\n Usage: %s <server> filename",argv[0]); exit(1); } if(cp=strchr(argv[1],'/')) { *cp='\0'; l=strlen(argv[1]); hostname=malloc(l+1); strcpy(hostname,argv[1]); *cp='/'; l=strlen(cp); req=malloc(l+1); strcpy(req,cp); } else { hostname=argv[1]; req="/"; } printf("\n Host = %s \n Req =%s",hostname,req); sd=socket(AF_INET,SOCK_STREAM,0); if(sd<0) { perror("\n Cannot Open Socket");

Page 49: NPM Lab Manual

exit(1); } bzero(&sock,sizeof(sock)); sock.sin_family=AF_INET; con=inet_pton(AF_INET,argv[1],&sock); sock.sin_port=htons(80); con=connect(sd,(struct sockaddr*)&sock,sizeof(sock)); if(con<0) { perror("\n connection failed "); exit(1); } sprintf(buff,"Get HTTP: %s //1.1\r\n Host: %s\r\n Connection : Class \r\n\r",req,hostname); printf("Buff=%s \n",buff); l=strlen(buff); local=fopen(argv[2],"w"); write(sd,buff,1); do { nrv=read(sd,buff,size); if(nrv>0) { for(i=0;i<nrv;i++) putc(buff[i],local); } else break; } while(1); close(sd); fclose(local); return 0; } OUTPUT [it28@localhost ~]$ vi download.c [it28@localhost ~]$ cc download.c [it28@localhost ~]$ ./a.out http:/192.168.11.208/z:hi.txt hello.txt host=http: connection failed: Connection refused req=/192.168.11.208/z:hi.txt

Page 50: NPM Lab Manual

Result

Hence a program to download a file from HTTP server is executed successfully.

VIVA QUESTIONS AND ANSWERS

Define HTTP server?

The software that services HTTP requests, which is the protocol of the Web. The term may refer only to the HTTP services in the Web server, or the term can be used as a synonym for "Web server." See Web server and HTTP.

Define bind()?

The bind() function shall assign a local socket address address to a socket identified by descriptor socket that has no local socket address assigned. Sockets created with the socket() function are initially unnamed; they are identified only by their address family.

Define sys/socket.h?

The <sys/socket.h> header defines the sockaddr structure with its family.

Definenetinet/in.h?

The <netinet/in.h> header shall define the sockaddr_in structure that includes at least the following members:

sa_family_t sin_family AF_INET.

in_port_t sin_port Port number.

struct in_addr sin_addr IP address.

Page 51: NPM Lab Manual

Ex No.9

IMPLEMENTATION OF FTP

Aim

To write a program to enable a file transfer between the client and server

Explanation

File Transfer Protocol (FTP) is a standard network protocol used to transfer files from one host or to another host over a TCP-based network. FTP works on a principle of client-server model and uses data-connection between client and server.

• A Client makes a TCP connection to the server. This connection remains open for the duration of the session and thus is called a control session.

• Then another connection is opened called the data connection(Data Transfer). • The control connection is used for authenticating , command and administrating exchanged

between the client and the server • The server responds on the requests with status codes • When an active connection is established, the server opens a data connection to the client on

the client machine. All data from the server is then passed over this connection.

Algorithm

Server:

Step 1. Create s socket with address family AF_INET, type SOCK_STREAM and default protocol

Step 2. Initialize the socket and set the attributes. Assign any port number as desired Step 3. Bind the server to socket using bind() Step 4. Wait for client request, on request establish a connection using accept() Step 5. Read the source and destination files from the client Step 6. Open the source and destination files. Step 7. Read on client of the source file and send it to client Step 8. Repeat step7 to 8 until the end of source file Step 9. Close the connection and goto step 4

Client:

Step 1. Create s socket with address family AF_INET, type SOCK_STREAM and default protocol

Step 2. Initialize the socket and set the attributes. Assign required port number Step 3. Connect to the server using connect() to initiate request Step 4. Send the source and destination file name to the server Step 5. Receive string from the server and print it at the console Step 6. Send the string to the file Step 7. Repeat step 5 to 6 and 7 until the server terminates the connection.

Page 52: NPM Lab Manual

Server Program:

#include<stdio.h>

#include<sys/socket.h>

#include<netinet/in.h>

#include<stdlib.h>

#include<unistd.h>

#include<string.h>

#include<netdb.h>

#include<arpa/inet.h>

#include<sys/types.h>

#include<time.h>

#define MAX 100;

int main ()

{int listenfd,connfd,n,nl;

struct sockaddr_in serv;

char str1 [100],str2[100],fname[20],fname1[20],s[2],

int port=9999;

FILE*f1*f2;

listenfd=socket(AF_INET,SOCK_STREAM,0);

bzero(&serv,sizeof(serv);

serv.sin_family=AF_INET;

serv.sin_addr.s_addr=htonl(INADDR_ANY);

serv.sin_port=htons(port);

bind(listenfd,(struct sockaddr*)&serv,sizeof(serv));

listen(listenfd,5);

for(;;)

{

connfd=accept(listenfd,(struct sockaddr*)NULL,NULL);

printf("\nClient requesting");

n=read(connfd,fname,20);

fname(n)='\0';

printf("\n Received:%s\n",fname);

f1=fopen(fname)."r");

strcpy(s,"ab");

write(connfd,s,strlen(s));

n1=read(connfd,fname1,20);

fname1[n1]=;\0';

printf("stored in:%s\n"'fname 1);

Page 53: NPM Lab Manual

f2=fopen(fname1,"w");

while(!feof(f1))

{fgets(str1,50f1);

write(connfd,str,1,strlen(str1));

n=read(connfd,str,2,100);

str2[n]='\0';

fputs(str2,f2);

}

fclose(f1);

fclose(f2);

close(connfd);

}

return 0;

}

Client Program:

#include<stdio.h>

#include<sys/socket.h>

#include<netinet/in.h>

#include<stdlib.h>

#include<unistd.h>

#include<string.h>

#include<netdb.h>

#include<arpa/inet.h>

#include<sys/types.h>

#include<time.h>

#define MAX 100;

main(int argc,char**argv)

{int sockfd,n,connfd;

char str[100],str1[100],s[2];

struct sockaddr_in serv;

if(argc!=5)

{exit(0);}

if(sockfd=socket(AF_INET,SOCK_STREAM,0))<0)

{

printf("\n Error ! Socket not created...\n");

exit (0);

}

Page 54: NPM Lab Manual

bzero(&serv,sizeof(serv));

serv.sin_family=AF_INET;

serv.sin_port=htons(atoi(argv[2]));

if(inet_pton(AF_INET,argv[1],&serv.sin_addr)<=0)

{

printf("\n error in conversion of IP address from string to num\n"),

exit(0);

}

if(connect(sockfd,(struct sockaddr*)&serv,sizeof(serv))<0)

{

printf("\n Error!Conx not established...\n);

exit(0);

}

printf("\n connected...sending file name%s\n",argv[3]);

write(sockfd,argv[],strlen(argv[3]));

read(sockfd,s,3);

write(sockfd,argv[4],strlen(argv[4]));

str1[0]='\0';

while((n=read(sockfd,str,100))>0)

{

str[n]='\0';

printf("%s\n",str);

write(sockfd,str,strlen(str));

}

if(n<0)

printf("\n Read error...\n");

exit (0);

}

Page 55: NPM Lab Manual

SAMPLE INPUT OUTPUT:

Server Side:

[cseb17@localhost cseb 17]$ cc trj3server.c

[cseb17@localhost cseb 17]$.a/out

Client requesting

Received:new.c

Stored in : thanga.c

Client side:

[cseb17@localhost cseb 17]$cc trj3client.c

[cseb17@localhost cseb 17]$./a.out 127.0.0.1 6142 new.c.thanga.c

connected...sending filename new.c

hai how are you?

Page 56: NPM Lab Manual

Result

Hence a program to enable a file transfer between the client and server is executed successfully.

VIVA QUESTIONS AND ANSWERS

Define FTP?

File Transfer Protocol (FTP) is a standard network protocol used to transfer files from one host or to another host over a TCP-based network.

Define control connection?

The control connection is used for authenticating , command and administrating exchanged between the client and the server

Define arpa/inet.h

arpa/inet.h - definitions for internet operations. The in_port_t and in_addr_t typesare defined in this.

Define netbd.h?

netdb.h - definitions for network database operations

Page 57: NPM Lab Manual

Ex No.10

MULTIPLEXED TCP SERVER AND CLIENT

Aim

To write a client server program to get time and data information using the multiplexed TCP client server.

Explanation

A TCP multiplexing system improves the efficiency of the Server connection.TCP multiplexing systems keep client-side connections open with longer timeouts.

Servers typically need to be able to handle multiple clients simultaneously.

It allows multiple clients to connect and stay connected, efficient use of resources, and keeping the server responsive to each of the clients.

Client request for connection and send a request. The server creates a port with Socket and respond client by accepting connection. The Client is now ready to access the server date and time. It reads the date and time of server and displays it.

Algorithm

Server

Step 1. Declare the necessary arrays and variables Step 2. Set the server port address using socket() Step 3. Get the current date and time Step 4. Connect to the client Step 5. Stop the process

Client

Step 1. Get the client machine address Step 2. Connect to server Step 3. Read from the server the current date and time Step 4. Display the current date and time Step 5. Close the connection

Page 58: NPM Lab Manual

Multiplexed TCP Client-Server

Server

#include<stdio.h>

#include<sys/types.h>

#include<sys/socket.h>

#include<netinet/in.h>

#inc1ude<time.h>

#include<string.h>

#define MAX_BUF 30

#define PORT 2100

int main()

{

intsersoc,clisoc;

intconn,len,wri;

char str[MAX_BUF];

pid_tpid;

time_t ticks;

socklen_t clilen;

structsockaddr_in servaddr;

structsockaddr_in cliaddr;

servaddr.sin_family=AF_INET;

servaddr.sin_port=htons(PORT);

servaddr.sin_addr.s_addr=htonl(INADDR_ANY);

if((sersoc=socket(AF_INET,SOCK_STREAM,0))<0)

{

perror( "Socket Error");

exit(0);

}

if(bind(sersoc,(struct sockaddr*)&servaddr,sizeof(servaddr))<0)

{

perror("Bind Error");

exit(0);

}

listen(sersoc, 10);

for(;;)

{

len=sizeof(cliaddr) ;

conn=(accept(sersoc,(struct sockaddr *)&clisoc,&len));

if((pid=fork())==0)

Page 59: NPM Lab Manual

{

close(sersoc);

ticks=time(NULL);

strcpy(str,ctime(&ticks));

if((wri==(write(conn,str,sizeof(str),0)))<0)

{

printf("Write Error");

exit(0);

}

close(conn);

exit(0);

}

close(conn); }

c1ose(sersoc);

return 0;

}

Client

#inc1ude<stdio.h>

#inc1ude<sys/types.h>

#include<sys/socket.h>

#include<netinet/in.h>

#include<time.h>

#include<arpa/inet.h>

#define CLI_PORT 2100

#define BUFF_SIZE 30

int main(int argc,char **argv)

{

int clisoc,IPPORT_IP,re;

char recbuff[BUFF_SIZE];

structsockaddr_in cliaddr;

bzero(&cliaddr,sizeof(cliaddr));

cliaddr.sin_family=AF_INET;

cliaddr.sin_port=htons(2100);

cliaddr.sin_addr.s_addr=inet_addr(argv[1]);

if((clisoc=socket(AF_INET,SOCK_STREAM,0))<0)

{

perror( "Socket Error");

exit(0);

}

Page 60: NPM Lab Manual

if((connect(clisoc,(struct sockaddr *)&c1iaddr,sizeof(cliaddr)))<0)

{

perror("connect error”);

exit(0);

}

if((re=(read(clisoc,recbuff,sizeof(recbuff),0)))<0)

{

printf("Read error");

exit(0);

}

printf("The current date and time: %s\n",recbuff)

close(clisoc);

return 0;

}

OUTPUT:

Server

[it44@localhost~l$ cc.mulser.c

[it44@localhost ~]$ ./a.out

Client

[it44@localhost~]$ CC.mulcli.c

[it44@localhost~] $./a.out 192.168.11.208

The current date and time: Fri Dec 12 01:38:17 2012

Page 61: NPM Lab Manual

Result

Hence a program for multiplexed TCP client and server is executed successfully.

VIVA QUESTION AND ANSWERS

Define TCP Multiplexing?

A TCP multiplexing system improves the efficiency of the Server connection. TCP multiplexing systems keep client-side connections open with longer timeouts

Define sys/types.h?

sys/types.h - data types. dev_t, id_t, pid_t, size_t, time_t are defined in this header file.

Page 62: NPM Lab Manual

STUDY OF NETWORK SIMULATORS – NS2

The Class Simulator

The overall simulator is described by a Tcl class Simulator. It provides a set of interfaces for configuring a simulation and for choosing the type of event scheduler used to drive the simulation. A simulation script generally begins by creating an instance of this class and calling various methods to create nodes, topologies, and configure other aspects of the simulation.

A subclass of Simulator called OldSim is used to support ns v1 backward compatibility. The procedures and functions described in this chapter can be found in ~ns/tcl/lib/ns-lib.tcl, ~ns/scheduler. {cc,h}, and, ~ns/heap.h.

Simulator Initialization

When a new simulation object is created in tcl, the initialization procedure performs the following operations:

_initialize the packet format (calls create_packetformat)

_create a scheduler (default to a calendar scheduler)

_create a “null agent” (a discard sink used in various places)

The packet format initialization sets up field offsets within packets used by the entire simulation. The scheduler runs the simulation in an event – driven manner and may be replaced by alternative schedulers which provide somewhat different semantics. The null agent is created with the following call:

Set nullAgent_[new Agent/Null]

This agent is generally useful as a sink for dropped packets or as a destination for packets that are not counted or recorded.

Schedulers and Events

The simulator is an event – driven simulator. There are presently four schedulers available in the simulator, each of which is implemented using a different data structure: a simple linked list, heap, calendar queue (default), and a special type called “real – time”. Each of these are described below. The scheduler runs by selecting the next earliest event, executing it to completion, and returning to execute the next event. Unit of time used by scheduler is seconds. Presently, the simulator is single- threaded, and only one event in execution at any given time. If more than one event are scheduled to execute at the same time, their execution is performed on the first scheduled – first dispatched manner. Simultaneous events are not recorded anymore by schedulers (as it was in earlier versions) and all schedulers should yield the same order of dispatching given the same input.

No partial execution of events or pre – emption is supported.

An event generally comprises a “firing time” and a handler function. The actual definition of an event is found in ~ns/scheduler.h:

class Event {

public:

Event* next_; /* event list */

Page 63: NPM Lab Manual

Handler* handler_; /* handler to call when event ready */

double time_; /* time at which event is ready */

int uid_; /* unique ID */

Event() : time_(0), uid_(0) {}

};

/*

* The base class for all event handlers. When an event’s scheduled

*time arrives, it is passed to handle which must consume it.

*i.e., if needs to be freed it, it must be freed by the handler.

*/

class Handler {

public:

virtual void handle(Event* event);

};

Two types of objects are derived from the base class Event: packets and “at-events”. An at-event is a tcl procedure execution scheduled to occur at a particular time. This is frequently used in simulation scripts.

A simple example of how it is used is as follows:

Set ns_[new Simulator]

$ns_use-scheduler Heap

$ns_at 300.5 “$self complete_sim”

This tcl code fragment first creates a simulation object, then changes the default scheduler implementation to be heap-based (see below), and finally schedules the function $self complete_sim to be executed at time 300.5 (seconds)(Note that this particular code fragment expects to be encapsulated in an object instance procedure, where the appropriate reference to $self is correctly defined). At – events are implemented as events where the handler is effectively an execution of the tcl interpreter.

Page 64: NPM Lab Manual

The List Scheduler

The list scheduler (class Scheduler/List) implements the scheduler using a simple linked – list structure. The list is kept in time – order (earliest to latest), so event insertion and deletion require scanning the list to find the appropriate entry. Choosing the next event for execution requires trimming the first entry off the head of the list. This implementation preserves event execution in a FIFO manner for simultaneous events.

The Head Scheduler

The heap scheduler (class Scheduler/Heap) implements the scheduler using a heap structure. This structure is superior to the list structure for a large number of events, as insertion and deletion times are in O(log n) for n events. This implementation in ns v2 is borrowed from the MaRS – 2.0 simulator [1]; it is believed that MaRs itself borrowed the code from NetSim[14], although this lineage has not been completely verified.

The Calendar Queue Scheduler

The calendar queue scheduler (class Scheduler/Calendar) uses a data structure analogous to a one-year desk calendar, in which events on the same month/day of multiple years can be recorded in one day. It is formally described in [6], and informally described in Jain (p.410) [15]. The implementation of Calendar queues in ns v2 was contributed by David Wetherall(presently at MIT/LCS).

The Real – Time Scheduler

The real – time scheduler (class Scheduler/RealTime) attempts to synchronize the execution of events with real – time. It is currently implemented as a subclass of the list scheduler. The real – time capability in ns is still under development, but is used to introduce an ns simulated network into a real – world topology to experiment with easily – configured network topologies, cross – traffic, etc. This only works for relatively slow network traffic data rates, as the simulator must be able to keep pace with the real – world packet arrival rate, and this synchronization is not presently enforced.

Precision of the scheduler clock used in ns

Precision of the scheduler clock can be defined as the smallest time – scale of the simulator that can be correctly represented. The clock variable for ns is represented by a double. As per the IEEE std for floating numbers, a double, consisting of 64 bits must allocate the following bits between its sign, exponent and mantissa field.

sign exponent mantissa

1 bit 11 bits 52 bits

Any floating number can be represented in the form (X_2n) where X is the mantissa and n is the exponent. Thus the precision of timeclock in ns can be defined as (1=2(52)). As simulation runs for longer times the number of remaining bits to represent the time educes thus reducing the accuracy. Given 52 bits we can safely say time upto around (2(40)) can be represented with considerable accuracy. Anything greater than that might not be vary accurate as you have remaining 12 bits to represent the time change. However (2(40)) is a very large number and we donot anticipate any problem regarding precision of time in ns.

Page 65: NPM Lab Manual

Commands:

Synopsis:

ns<otclfile><arg><arg>..

Description:

Basic command to run a simulation script in ns. The simulator (ns) is invoked via the ns interpreter, an extension of the vanilla otclsh command shell. A simulation is defined by OTcl script (file). Several examples of OTcl scripts can be found under ns/tcl/ex directory.

The following is a list of simulator commands commonly used in simulation scripts:

set ns_ [new Simulator]

This command creates an instance of the simulator object.

setns_ [$ns_now]

The scheduler keeps track of time in a simulation. This returns scheduler’s notion of current time.

$ns_ halt

This stops or paused the scheduler.

$ns_ run

This starts the scheduler.

$ns_at <time><event>

This schedulers an <event> (which is normally a piece of code) to be executed at the specified <time>.

e.g $ns_ at $opt(stop) “puts ``NS EXITING..``; $ns_halt”

or, $ns_ at 10.0 “$ftp start”

$ns_ cancel <event>

Cancels the event. In effect, event is removed from scheduler’s list of ready to run events.

$ns_ create-trace <type><file><src><dst><optional arg: op>

This creates a trace-object of type <type> between <src> and <dst> object and attaches trace-object to <file> for writing trace-outputs. If op is defined as “nam”, this creates nam tracefiles; otherwise if op is not defined, ns tracefiles are created on default.

$ns_ flush-trace

Flushes all trace object write buffers.

$ns_ gen-map

This dumps information like nodes, node components, links etc created for a given simulation. This may be broken for some scenarios (like wireless).

$ns_ at-now <args>

Page 66: NPM Lab Manual

This is an effect like command “$ns_ at $now $args”. Note that this function may not work because of tcl’s string number resolution.

These are additional simulator (internal) helper functions (normally used for developing/changing the ns core code):

$ns_ use-scheduler <type>

Used to specify the type of scheduler to be used for simulation. The different types of scheduler available are List, Calendar, Heap and RealTime. Currently Calendar is used as default.

$ns_ after <delay><event>

Scheduling an <event> to be executed after the lapse of time <delay>.

$ns_ clearMemTrace

Used for memory debugging purposes.

$ns_ is-started

This returns true if simulator has started to run and false if not.

$ns_ dumpq

Command for dumping events queued in scheduler while scheduler is halted.

$ns_ create_packerformat

This sets up simulator’s packet format.

Page 67: NPM Lab Manual

Ex No.11

Node Creation using NS2

Aim:

To write a NS2 script to procedure 2 nodes and 1 link.

Explanation

• ns2 script starts with creating simulator object “set ns [new Simulator]” • To create nodes use “set n0 [$ns node] set n1 [$ns node]”. • To connect the nodes with the link use “$ns duplex-link $n0 $n1 1Mb 10ms DropTail” • Open the “namtrace” file for visualizing.

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

• Define a 'finish' procedure proc finish {} { global ns tracefile nf $ns flush-trace close $nf close $tracefile # close tracefile exec nam out.nam & #Execute nam on the trace file exit 0 }

Procedure:

Two nodes, one link

1. Define a very simple topology with two nodes that are connected by a link. 2. Define the two nodes. (Note: You have to insert the code in this section before the line

‘$ns run’, or even better, before the line ‘$ns at 5.0 “finish”’).

3. A new node object is created with the command ‘$ns node’. 4. After creating two nodes, assigns them to the handles ‘n0’ and ‘n1’. 5. Connects the two nodes.

6. This line tells the simulator object to connect the nodes n0 and n1 with a duplex link with the bandwidth 1Megabit, a delay of 10ms and a DropTail queue.

7. Save the file and start the script with ns example1.tcl’. nam will be started automatically.

set n0 [$ns node]

set n1 [$ns node]

$ns duplex-link $n0 $n1 1Mb 10ms DropTail

Page 68: NPM Lab Manual

Result:

Thus the node has been created using NS2.

VIVA QUESTION AND ANSWERS

What is simulation?

Simulation is the imitation of the operation of a real-world process or system over time.

Feature of NS2 simulator

ns (from network simulator) is a name for series of discrete event network simulators.

• Protocols: TCP, UDP, HTTP, Routing algorithms etc • Traffic Models: CBR, VBR, Web etc • Error Models: Uniform, bursty etc • Radio propagation, Mobility models • Energy Models • Topology Generation tools • Visualization tools

• Extensibility

Define List scheduler

The list scheduler (class Scheduler/List) implements the scheduler using a simple linked – list structure to choose the next event for execution.

Define ns

Basic command to run a simulation script in ns. The simulator (ns) is invoked via the ns interpreter, an extension of the vanilla otclsh command shell

How to create nodesin ns2?

set n0 [$ns node] is used to create new nodes in ns2. n0 is the name of the node.

How to create link between nodes?

$ns duplex-link $n0 $n1 1Mb 10ms DropTail

the simulator object to connect the nodes n0 and n1 with a duplex link with the bandwidth 1Megabit, a delay of 10ms and a DropTail queue.

Page 69: NPM Lab Manual

Question Set

1. Write a program to implement simulation of ARP.

2. Write a program to implement simulation of RARP.

3. Write a program to develop a client that contacts a given DNS server to

resolve a given hostname.

4. Write a program to implement simulation of OSPF routing protocol.

5. Write a program to develop a client server application for chat.

6. Write a program to develop a trace route program.

7. Write a program to implement Signal handling

8. Write a program to implement handling zombie.

9. Write a program to implement RPC.

10. Write a program for client to download a file from HTTP server.

11. Write a program to implement FTP.

12. Write a program to implement Multiplexed TCP server and client

Page 70: NPM Lab Manual

REFERENCES

• W.Richardstevens,”Unix Network Programming Vol – I”, 2ND EDITION, Prentice Hall of India/Pearson Education, 1998

• http://enggedu.com/lab_exercise/network_lab/network_lab_exercise_programs.php • http://www.davcetkanina.org/download/comp/cn-lab-manual.pdf • www.scribd.com › Research › Science

• ibno.com › Academic Section › Engineering and Technology