GNANAVEL S



Ex.No: STUDYOF SOCKETSDate:Socketsareamechanism forexchangingdatabetweenprocesses. Theseprocessescan eitherbeonthesamemachine,orondifferentmachinesconnected viaanetwork.Once asocketconnectionisestablished, datacanbesentinbothdirectionsuntiloneofthe endpointscloses theconnection.Study of MethodsSOCKETSocket- end point for communication.Synopsis:#include <sys/types.h>/* See NOTES */#include <sys/socket.h>int socket(int domain, int type, int protocol);Description:socket() creates an endpoint for communication and returns a descriptor. The domain argument specifies a communication domain; this selects the protocol family which will be used for communication. These families are defined in <sys/socket.h>.SOCK_STREAMProvides sequenced, reliable, two-way, connection-based byte streams. An out-of-band data transmission mechanism may be supported.SOCK_DGRAMSupports datagrams (connectionless, unreliable messages of a fixed maximum length).SOCK_RAWProvides raw network protocol access.LISTENlisten - listen for connections on a socketSynopsis:#include <sys/types.h>#include <sys/socket.h>int listen(int sockfd, int backlog);Description:listen() marks the socket referred to by sockfd as a passive socket, that is, as a socket that will be used to accept incoming connection requests using accept().BINDbind - bind a name to a socketSynopsis:#include <sys/types.h>#include <sys/socket.h>int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);Description:When a socket is created with socket(2), it exists in a name space (address family) but has no address assigned to it. bind() assigns the address specified to by addr to the socket referred to by the file descriptor sockfd. addrlen specifies the size, in bytes, of the address structure pointed to by addr.ACCEPTaccept - accept a connection on a socketSynopsis:#include <sys/types.h>#include <sys/socket.h>int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);Description:The accept() system call is used with connection-based socket types (SOCK_STREAM,SOCK_SEQPACKET). It extracts the first connection request on the queue of pending connections for the listening socket, sockfd, creates a new connected socket, and returns a new file descriptor referring to that socket.BZERObzero - write zero-valued bytesSynopsis:#include <strings.h>void bzero(void *s, size_t n);Description:The bzero() function sets the first n bytes of the byte area starting at s to zero(bytes containing'\0').CONNECTconnect - initiate a connection on a socketSynopsis:#include <sys/types.h>#include <sys/socket.h>int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);Description:The connect() system call connects the socket referred to by the file descriptor sockfd to the address specified by addr. The addrlen argument specifies the size of addr.BCOPYbcopy - copy byte sequenceSynopsis:#include <strings.h>void bcopy(const void *src, void *dest, size_t n);Description:The bcopy() function copies n bytes from src to dest. The result is correct, even when both areas overlap.READread - read from a file descriptorSynopsis:#include <unistd.h>ssize_t read(int fd, void *buf, size_t count);Description:read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf. If count is zero, read() returns zero and has no other results. If count is greater than SSIZE_MAX, the result is unspecifiedWRITEwrite - write to a file descriptorSynopsis:#include <unistd.h>ssize_t write(int fd, const void *buf, size_t count);Description:write() writes up to count bytes from the buffer pointed buf to the file referred to by the file descriptor fd.RECVFROMrecvfrom - receive a message from a socketSynopsis:#include <sys/socket.h>ssize_t recvfrom(int socket, void *restrict buffer, size_t length, int flags, struct sockaddr *restrict address,socklen_t *restrict address_len);Description:The recvfrom() function shall receive a message from a connection-mode or connectionless-mode socket. It is normally used with connectionless-mode sockets because it permits the application to retrieve the source address of received data.SENDTOsendto- send a message on a socketSynopsis:#include <sys/types.h>#include <sys/socket.h>ssize_t sendto(int sockfd, const void *buf, size_t len, int flags, const struct sockaddr *dest_addr, socklen_t addrlen);Description:The system call sendto() is used to transmit a message to another socket.Client-Server Model:?Server – An entity which is a provider of information.?Client – An entity which is a seeker of information.?Example – Apache is a web server providing web pages (information) andInternet Explorer is a web client which requests those pages from the server.?In the socket programming world almost all communication is based on theClient-Server model.?The Server starts up first and waits for a client to connect to it. After a client successfully connects, it requests some information. The Server serves this information to the client. The client then disconnects and the Server waits for more clients.Fig:TCPServer-ClientInteractionResultEx.no:2 TCP ECHO SERVER AND ECHO CLIENT02.07.13AIM:To write a C program to implement TCP echo server and echo client.ALGORITHM:SERVER:Check if the number of arguments is less than two and if so throw an errorGet the socket using socket() function of tcp , check if the value is less than zero and if it is not less then call bzero function to clear the bufferAssign the values to the structure members and then call the bind message function to bind the socketListen for the connection and if there is a connection accept it Get the message from the client and display it.CLIENT:Check if the number of arguments is less than two and if so throw an errorGet the port number and the socketUse the gethostname(parameter) method to get hostClear the buffer and then assign the family to AF_INETCopy the message to the buffer using bcopy methodConnect to the server and prompt the user to enter the message and then pass the message to the server.Copy the message from the buffer and display the message from the buffer.CODING://TCPechoSERVER#include<sys/socket.h>#include<netinet/in.h>#include<stdio.h>#include<sys/types.h>#include<stdlib.h>#include<string.h>intmain(intargc,char*argv[]){inti,sockfd,newsockfd,clilen,n;structsockaddr_inserv_addr,cliaddr;charbuffer[256];if(argc!=2){fprintf(stderr,"\nError!NoportProvided\n");exit(1);}sockfd=socket(AF_INET,SOCK_STREAM,0);if(sockfd<0)printerror("\nErrorOpeningSocket");elseprintf("\nSocketSuccessfullyCreated");bzero((char*)&serv_addr,sizeof(serv_addr));serv_addr.sin_family=AF_INET;serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);serv_addr.sin_port=htons(atoi(argv[1]));if(bind(sockfd,(structsockaddr*)&serv_addr,sizeof(serv_addr))<0)printerror("\nErrorinBinding");listen(sockfd,5);clilen=sizeof(cliaddr);newsockfd=accept(sockfd,(structsockaddr*)&cliaddr,&clilen);if(newsockfd<0)printerror("\nErroronaccept");while(1){bzero(buffer,256);n=read(newsockfd,buffer,255);if(n<0)printerror("\nErrorreadingfromsocket\n");printf("\nMsgrecievedatserver:%s",buffer);n=write(newsockfd,buffer,50);if(n<0)printerror("\nErrorwritinginsocket\n");}}intprinterror(char*msg){perror(msg);exit(1);}//TCPechoCLIENT#include<sys/types.h>#include<sys/socket.h>#include<stdio.h>#include<stdlib.h>#include<string.h>#include<netinet/in.h>intmain(intargc,char*argv[]){inti,sockfd,connfd,n,a=1;structsockaddr_inserv_addr,cli_addr;charbuffer[256],str[10],str1[10];if(argc!=3){fprintf(stderr,"Type%sfollowedbyhostnameandtheportnumber\n",argv[0]);exit(0);}sockfd=socket(AF_INET,SOCK_STREAM,0);if(sockfd<0){printerror("\nErroropeningSocket");exit(0);}else{printf("\nSocketsuccessfullycreated\n");bzero((char*)&serv_addr,sizeof(serv_addr));serv_addr.sin_family=AF_INET;serv_addr.sin_port=htons(atoi(argv[1]));serv_addr.sin_addr.s_addr=htonl(atoi(argv[2]));if(connect(sockfd,&serv_addr,sizeof(serv_addr))<0)printerror("\nErrorConnecting");for(;a!=0;){printf("|nPleaseenterthemessage\n");bzero(buffer,256);scanf("%s",buffer);n=write(sockfd,buffer,strlen(buffer));if(n<0)printerror("\nErrorwritingtothesocket");bzero(buffer,256);printf("\nServerecho'smessage");n=read(sockfd,buffer,255);if(n<0)printerror("\nErrorreadingfromsocket");printf("%s",buffer);if(strcmp(buffer,"stop")==0)a=0;}return0;}}intprinterror(char*msg){perror(msg);exit(0);}OUTPUTTCP echo SERVER[net113@linuxlab113]$gcc-os9server.c[net113@linuxlab113]$./s91122SocketSuccessfullyCreatedMsgrecievedatserver:haiMsgrecievedatserver:helloMsgrecievedatserver:howareyouMsgrecievedatserver:stop[net113@linuxlab113]$OUTPUTTCP echo CLIENT[net113@linuxlab113]$gcc-oc9client.c[net113@linuxlab113]$./c91122localhostSocketsuccessfullycreatedPleaseenterthemessage haiServerecho'smessagehaiPleaseenterthemessage helloServerecho'smessagehelloPleaseenterthemessage howareyouServerecho'smessagehowareyouPleaseenterthemessage stopServerecho'smessagestop[net113@linuxlab113]$RESULT:Thus a C program to implement TCP echo server and echo client is verified and executed successfully.Ex.no:3 UDP ECHO SERVERS AND ECHO CLIENT09.07.13ALGORITHM:SERVER:Get the Portno from the command line arguments.Check the number of command line argument it must be 2,if not prompt an error message .Clear the buffer using bzero functionEstablish the connection of the socketAssign the protocol address to socket using bind functionCalculate the length of the client address Using recvfrom function receive the message from the clientUsing sendto function send the same message to the clientCLIENT:Get the name and port number from command line argument.Choose the number of command line arguments,it must be 3,if not prompt an error message.Open the socketClear the buffer using bzero functionGet the message from user using fgets function and send to receiver using sendto functionCODING:// UDP echo SERVER#include<sys/socket.h>#include<netinet/in.h>#include<stdio.h>#include<sys/types.h>#include<stdlib.h>#include<string.h>int main(int argc,char *argv[]){int i,sockfd,newsockfd,clilen,n;struct sockaddr_in serv_addr,cliaddr;char buffer[256];if(argc!=2){fprintf(stderr,"\n Error!No port Provided\n");exit(1);}sockfd=socket(AF_INET,SOCK_DGRAM,0);if(sockfd<0)printerror("\n Error Opening Socket");elseprintf("\n Socket Successfully Created");bzero((char *)&serv_addr,sizeof(serv_addr));serv_addr.sin_family=AF_INET;serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);serv_addr.sin_port=htons(atoi(argv[1]));if(bind(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr))<0)printerror("\n Error in Binding");clilen=sizeof(cliaddr);while(1){bzero(buffer,256);n=recvfrom(sockfd,buffer,255,0,(struct sockaddr *)&cliaddr,&clilen);if(n<0)printerror("\n Error reading from socket\n");printf("\n Msg recieved at server: %s",buffer);n=sendto(sockfd,buffer,strlen(buffer),0,(struct sockaddr *)&cliaddr,sizeof(cliaddr));if(n<0)printerror("\n Error writing in socket\n");}return 0;}int printerror(char *msg){perror(msg);exit(1);}// UDP echo CLIENT#include<sys/types.h>#include<sys/socket.h>#include<stdio.h>#include<stdlib.h>#include<string.h>#include<netinet/in.h>int main(int argc,char *argv[]){int i,sockfd,clilen,n,a=1;struct sockaddr_in serv_addr,cliaddr;char buffer[256],str[10],str1[10];if(argc!=3){fprintf(stderr,"Type %s followed by host name and the port number \n",argv[0]);exit(0);}sockfd=socket(AF_INET,SOCK_DGRAM,0);if(sockfd<0){printerror("\n Error opening Socket");exit(0);}else{printf("\n Socket successfully created\n");}bzero((char *)&serv_addr,sizeof(serv_addr));serv_addr.sin_family=AF_INET;serv_addr.sin_port=htons(atoi(argv[1]));serv_addr.sin_addr.s_addr=htonl(atoi(argv[2]));clilen=sizeof(serv_addr);while(a!=0){printf("|n Please enter the message\n");bzero(buffer,256);fgets(buffer,255,stdin);n=sendto(sockfd,buffer,strlen(buffer),0,(struct sockaddr *)&serv_addr,clilen);if(n<0)rinterror("\nError writing to the socket");bzero(buffer,256);printf("\n Server echo's message");n=recvfrom(sockfd,buffer,255,0,(struct sockaddr *)&serv_addr,&clilen);if(n<0)printerror("\n Error reading from socket");printf("%s",buffer);if(strncmp(buffer,"stop",4)==0)a=0;}return 0;}int printerror(char *msg){perror(msg);}OUTPUTUDP echo SERVER[net113@linuxlab 113]$ gcc -o u us.c[net113@linuxlab 113]$ ./u 6677Socket Successfully CreatedMsg recieved at server: hiMsg recieved at server: helloMsg recieved at server: how are youMsg recieved at server: stopOUTPUTUDP echo CLIENT[net113@linuxlab 113]$ gcc -o c uc.c[net113@linuxlab 113]$ ./c 6677 localhostSocket successfully createdPlease enter the message hiServer echo's message hiPlease enter the message helloServer echo's message helloPlease enter the message how are youServer echo's message how are youPlease enter the message stopServer echo's message stop[net113@linuxlab 113]$ RESULT:Thus a C program to implement UDP echo server and client is verified and executed successfully.Ex.no:4 TCP CHAT SERVER AND CLIENT16.07.13AIM:To write a C program to implement chat server and client using tcp socketsALGORITHM:SERVER:Create socket for server using socket()Bind the socket with the port number specified as command line argument.Accept the connection request received from the clientIf the connection variable returns zero then the server accepts the connection requestRead the message sent to the serverEnter and write the message to the clientCLIENT:Create socket for client using socket()Send connection request to serverEnter and write the message to be sentRead the message from the serverIf the buffer contains “exit” then the client is terminating.Close the socket.CODING://TCPchatSERVER#include<netinet/in.h>#include<sys/socket.h>#include<sys/types.h>#include<stdlib.h>#include<string.h>#include<stdio.h>intmain(intargc,char*argv[]){inti,sockfd,newsockfd,clilen,n,a=1;structsockaddr_inserv_addr,cliaddr;charbuffer[256];if(argc!=2){fprintf(stderr,"\nError!NoportProvided\n");exit(1);}sockfd=socket(AF_INET,SOCK_STREAM,0);if(sockfd<0)printerror("\nErrorOpeningSocket");elseprintf("\nSocketSuccessfullyCreated");bzero((char*)&serv_addr,sizeof(serv_addr));serv_addr.sin_family=AF_INET;serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);serv_addr.sin_port=htons(atoi(argv[1]));if(bind(sockfd,(structsockaddr*)&serv_addr,sizeof(serv_addr))<0)printerror("\nErrorinBinding");listen(sockfd,5);clilen=sizeof(cliaddr);newsockfd=accept(sockfd,(structsockaddr*)&cliaddr,&clilen);if(newsockfd<0)printerror("\nErroronaccept");while(a!=0){bzero(buffer,256);n=read(newsockfd,buffer,255);if(n<0)printerror("\nErrorreadingfromsocket\n");printf("\nMsgrecievedatserver:%s",buffer);printf("\nEnterthemessagetobesent");gets(buffer);n=write(newsockfd,buffer,50);if(n<0)printerror("\nErrorwritinginsocket\n");if(strcmp(buffer,"stop")==0)a=0;}}intprinterror(char*msg){perror(msg);exit(1);}//TCPchatCLIENT#include<sys/types.h>#include<sys/socket.h>#include<stdio.h>#include<stdlib.h>#include<string.h>#include<netinet/in.h>intmain(intargc,char*argv[]){inti,sockfd,connfd,n,a=1;structsockaddr_inserv_addr,cli_addr;charbuffer[256],str[10],str1[10];if(argc!=3){fprintf(stderr,"Type%sfollowedbyhostnameandtheportnumber\n",argv[0]);exit(0);}sockfd=socket(AF_INET,SOCK_STREAM,0);if(sockfd<0){printerror("\nErroropeningSocket");exit(0);}else{printf("\nSocketsuccessfullycreated\n");bzero((char*)&serv_addr,sizeof(serv_addr));serv_addr.sin_family=AF_INET;serv_addr.sin_port=htons(atoi(argv[1]));serv_addr.sin_addr.s_addr=htonl(atoi(argv[2]));if(connect(sockfd,&serv_addr,sizeof(serv_addr))<0)printerror("\nErrorConnecting");while(a!=0){printf("|nPleaseenterthemessage\n");bzero(buffer,256);gets(buffer);n=write(sockfd,buffer,strlen(buffer));if(n<0)printerror("\nErrorwritingtothesocket");bzero(buffer,256);printf("\nServerecho'smessage");n=read(sockfd,buffer,255);if(n<0)printerror("\nErrorreadingfromsocket");printf("%s",buffer);if(strcmp(buffer,"stop")==0)a=0;}return0;}}intprinterror(char*msg){perror(msg);exit(0);}OUTPUTTCP chat SERVER[net113@linuxlab113]$gcc-otpstpserver.c[net113@linuxlab113]$./tps4455SocketSuccessfullyCreatedMsgrecievedatserver:hiEnterthemessagetobesenthelloMsgrecievedatserver:howareyouEnterthemessagetobesentfinetooMsgrecievedatserver:hmmEnterthemessagetobesentstop[net113@linuxlab113]$OUTPUTTCP chat CLIENT[net113@linuxlab113]$gcc-otpctpclient.c[net113@linuxlab113]$./tpc4455localhostSocketsuccessfullycreatedPleaseenterthemessage hiServerecho'smessagehelloPleaseenterthemessage howareyouServerecho'smessagefinetooPleaseenterthemessage hmmServerecho'smessagestop[net113@linuxlab113]$RESULT:Thus a C program to implement TCP chat server and client was verified successfully. Ex.no:5 UDP CHAT SERVER AND CLIENT23.07.13AIM:To write a C program to implement chat server and client using udp sockets.ALGORITHM:SERVER:Create socket for server using socket()Bind the socket with the port number specified as command line argument.Accept the connection request received from the clientIf the connection variable returns zero then the server accepts the connection requestRead the message sent to the serverEnter and write the message to the clientCLIENT:Create socket for client using socket()Send connection request to serverEnter and write the message to be sentRead the message from the serverIf the buffer contains “exit” then the client is terminating.Close the socket.CODING:// UDP chat SERVER#include<netinet/in.h>#include<string.h>#include<sys/socket.h>#include<netinet/in.h>#include<stdio.h>#include<stdlib.h>#include<sys/types.h>int main(int argc,char *argv[]){int a=1,sockfd,newsockfd,clilen,n;struct sockaddr_in serv_addr,cliaddr;char buffer[256];if(argc!=2){fprintf(stderr,"\nError!No port provided");exit(1);}sockfd=socket(AF_INET,SOCK_DGRAM,0);if(sockfd<0)printerror("\nError opening socket.");elseprintf("\nSuccess");bzero((char*)&serv_addr,sizeof(serv_addr));serv_addr.sin_family=AF_INET;serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);serv_addr.sin_port=htons(atoi(argv[1]));if(bind(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr))<0)printf("\nError Binding.");clilen=sizeof(cliaddr);while(a!=0){bzero(buffer,256);n=recvfrom(sockfd,buffer,255,0,(struct sockaddr*)&cliaddr,&clilen);if(n<0)printerror("Error reading from socket.");printf("\nMsg received at server:%s",buffer);if(strncmp(buffer,"stop",4)==0)a=0;printf("\nEnter msg to be sent:");fgets(buffer,255,stdin);n=sendto(sockfd,buffer,255,0,(struct sockaddr*)&cliaddr,sizeof(cliaddr));if(n<0)printerror("\nError writing to socket.");}return 0;}int printerror(char *msg){perror(msg);exit(1);}// UDP chat CLIENT#include<sys/types.h>#include<sys/socket.h>#include<stdio.h>#include<stdlib.h>#include<string.h>#include<netinet/in.h>int main(int argc,char *argv[]){int sockfd,connfd,n,a=1;struct sockaddr_in serv_addr,cli_addr;int clilen;char buffer[256];if(argc!=3){fprintf(stderr,"Type %s followed bu hostname and then port no\n",argv[0]);exit(0);}sockfd=socket(AF_INET,SOCK_DGRAM,0);if(sockfd<0){printerror("\nError opening socket.");exit(0);}else{printf("\nSocket successfully created.");}bzero((char*)&serv_addr,sizeof(serv_addr));serv_addr.sin_family=AF_INET;serv_addr.sin_port=htons(atoi(argv[1]));serv_addr.sin_addr.s_addr=htonl(atoi(argv[2]));clilen=sizeof(serv_addr);while(a!=0){printf("\nEnter the message.");bzero(buffer,256);fgets(buffer,255,stdin);n=sendto(sockfd,buffer,strlen(buffer),0,(struct sockaddr*)&serv_addr,sizeof(serv_addr));if(n<0)printerror("\nError writing to socket.");bzero(buffer,256);printf("\nServer's echo msg");n=recvfrom(sockfd,buffer,255,0,(struct sockaddr*)&serv_addr,&clilen);if(n<0)printerror("\nError reading from socket.");printf("%s",buffer);if(strncmp(buffer,"stop",4)==0)a=0;}return 0;}int printerror(char *msg){perror(msg);}OUTPUTUDP chat SERVER[net103@linuxlab ~]$ gcc -o us udps.c[net103@linuxlab ~]$ ./us 8877socket successfully createdmessage recieved at server: hiEnter the message : hellomessage recieved at server: how are youEnter the message : STOP[net103@linuxlab ~]$ OUTPUTUDP chat CLIENT[net103@linuxlab ~]$ gcc -o uc udpc.c[net103@linuxlab ~]$ ./uc 8877 localhostsocket successfully createdplease enter message: hiserver echo's message: helloplease enter message: how are youserver echo's message: STOP[net103@linuxlab ~]$ RESULT:Thus a C program to implement UDP chat server and client was verified successfully.Ex.no:6 PACKET CAPTURING AND FILTERING USING RAW SOCKETS30.07.13AIM:To capture packets and filter it using rawsockets.ALGORITHM:Get the Ethernet number and the number of packets to captureSpecify in command line argumentCreate new raw socket and bind itUsing while loop get packet until packets_to_sniff becomes zeroCreate a socket communicationBind socket interfaceTo get interface index and assign protocol address to socket using bind()Close the socketCODING://Implementation of Raw Sockets#include<unistd.h>#include<stdio.h>#include<stdlib.h>#include<sys/socket.h>#include<netinet/ip.h>#include<netinet/udp.h>#define PCKT_LEN 8192struct ipheader{unsigned char iph_iphl,iph_ver;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;};struct udpheader{unsigned short int udph_srcport;unsigned short int udph_destport;unsigned short int udph_len;unsigned short int udph_chksum;};unsigned short csum(unsigned short *buf,int nwords){unsigned long sum;for(sum=0;sum>0;nwords--){sum+=*buf++;sum=(sum>>16)+(sum & 0xffff);sum+=(sum>>16);}return (unsigned short)(~sum);}int main(int argc,char *argv[]){int sd,count;char buffer[PCKT_LEN];struct ipheader *ip=(struct ipheader *)buffer;struct udpheader *udp=(struct udpheader *)(buffer+sizeof(struct ipheader));struct sockaddr_in sin,din;int one=1;const int *val=&one;memset(buffer,0,PCKT_LEN);if(argc!=5){printf("Insufficient Parameters\n ");printf("{Usage:%s<source hostname/ip><source port><target hostname/ip><target port>\n",argv[0]);exit(0);}sd=socket(PF_INET,SOCK_RAW,IPPROTO_UDP);if(sd<0){printf("Socket not successfully created: socket() ERROR\n");exit(0);}elseprintf("Socket successfully created using SOCK_RAW\n using socket()");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]);ip->iph_iphl=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;ip->iph_protocol=17;ip->iph_sourceip=inet_addr(argv[1]);ip->iph_destip=inet_addr(argv[3]);udp->udph_srcport=htons(atoi(argv[2]));udp->udph_destport=htons(atoi(argv[4]));udp->udph_len=htons(sizeof(struct udpheader));ip->iph_chksum=csum((unsigned short *)buffer,sizeof(struct ipheader)+sizeof(struct udpheader));if(setsockopt(sd,IPPROTO_IP,IP_HDRINCL,val,sizeof(one))<0){printf("setsockopt() - Error");exit(0);}elseprintf("setsockopt() SUCCESSFULL\n");printf("Trying\n");printf("Usingsourceip%s\tport%u\n,Targetip%s\tport%u\n",argv[1],atoi(argv[2]),argv[3],atoi(argv[4]));for(count=1;count<=20;count++){if(sendto(sd,buffer,ip->iph_len,0,(struct sockaddr *)&sin,sizeof(sin))<0){perror("sendto() error");exit(0);}else{printf("count:#%u-sendto() is Successfull\n",count);sleep(2);}}close(sd);return 0;}OUTPUTRAW SOCKET[root@localhost student]# gcc socket.c[root@localhost student]# ./a.out 172.16.2.4 4500 172.16.2.6 4566Socket successfully created using SOCK_RAW using socket() setsockopt() SUCCESSFULLTryingUsing source ip 172.16.2.4port 4500 Target ip 172.16.2.6 port 4566count:#1-sendto() is Successfulcount:#2-sendto() is Successfulcount:#3-sendto() is Successfulcount:#4-sendto() is Successfulcount:#5-sendto() is Successfulcount:#6-sendto() is Successfulcount:#7-sendto() is Successfulcount:#8-sendto() is Successfulcount:#9-sendto() is Successfulcount:#10-sendto() is Successfulcount:#11-sendto() is Successfulcount:#12-sendto() is Successfulcount:#13-sendto() is Successfulcount:#14-sendto() is Successfulcount:#15-sendto() is Successfulcount:#16-sendto() is Successfulcount:#17-sendto() is Successfulcount:#18-sendto() is Successfulcount:#19-sendto() is Successfulcount:#20-sendto() is Successful[root@localhost student]# RESULT:Thus a program to capture packets and filter using raw sockets was executed successfully. Ex.no:8 PROGRAMS USING SIMPLE DNS13.08.13ALGORITHM:SERVER:Test for the current number of arguments.Create a UDP socket run the block to accept the connection foreverReceive the source address from the receiver,for the client and then echo that address Open the DNS file and then match the source address with the address of the fileIf the address is found,then display the address in the file using sendto()Catch the exception if anyCLIENT:Find the send address of the website in the command line argument and send it to the serverReceive the message from the client and then terminate with null characterDisplay the string echo bufferCODING:// DNS SERVER#include<stdio.h>#include<stdlib.h>#include<string.h>#include<sys/socket.h>#include<netinet/in.h>#include<sys/types.h>int main(int argc,char *argv[]){int sockfd,n,a=1;char buffer[256];char name[256];char ip[20];struct sockaddr_in serv_addr,cliaddr;int clilen;FILE *fp1;if(argc!=2){fprintf(stderr,"\nPort not provided\n");exit(0);}sockfd=socket(AF_INET,SOCK_DGRAM,0);if(sockfd<0)printerror("\nError opening the socket\n");elseprintf("Socket successfully created\n");bzero((char *)&serv_addr,sizeof(serv_addr));serv_addr.sin_family=AF_INET;serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);serv_addr.sin_port=htons(atoi(argv[1]));if(bind(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr))<0)printerror("\nError binding");clilen=sizeof(cliaddr);while(a!=0){bzero(buffer,256);n=recvfrom(sockfd,buffer,256,0,(struct sockaddr *)&serv_addr,&clilen);if(n<0)printerror("Error on reading from socket\n");fp1=fopen("file.txt","r");while(!feof(fp1)){fscanf(fp1,"%s%s",name,ip);if(strcmp(buffer,name)==0){printf("The name of the domain is %s\n the device's IP address is %s\n",name,ip);n=sendto(sockfd,ip,strlen(ip),0,(struct sockaddr *)&serv_addr,sizeof(serv_addr));if(n<0)printerror("Error writing to socket");}}fclose(fp1);if(strcmp(buffer,"stop")==0)a=0;}return 0;}int printerror(char *msg){perror(msg);}// DNS CLIENT#include<sys/socket.h>#include<sys/types.h>#include<netinet/in.h>#include<stdio.h>#include<string.h>#include<stdlib.h>#include<sys/socket.h>int main(int argc,char *argv[]){int clilen,sockfd,n,a=1;struct sockaddr_in serv_addr,cliaddr;char buffer[256],str[10],str1[10];if(argc!=3){fprintf(stderr,"Type %s followed by host name and the port no.\n",argv[0]);exit(0);}sockfd=socket(AF_INET,SOCK_DGRAM,0);if(sockfd<0){printerror("\nError opening the socket\n");exit(0);}else{printf("\nSocket successfully created\n");bzero((char *)&serv_addr,sizeof(serv_addr));serv_addr.sin_family=AF_INET;serv_addr.sin_port=htons(atoi(argv[1]));serv_addr.sin_addr.s_addr=htonl(atoi(argv[2]));clilen=sizeof(serv_addr);while(a!=0){bzero(buffer,256);printf("Enter the domain name\n");scanf("%s",buffer);n=sendto(sockfd,buffer,strlen(buffer),0,(struct sockaddr *)&serv_addr,sizeof(serv_addr));if(n<0)printerror("\nError writing to socket\n");bzero(buffer,256);printf("Server's message:");n=recvfrom(sockfd,buffer,255,0,(struct sockaddr *)&serv_addr,&clilen);if(n<0)printerror("error reading from socket\n");printf("The IP address is %s\n",buffer);if(strcmp(buffer,"stop")==0)a=0;}}return 0;}int printerror(char *msg){perror(msg);}OUTPUTDNS SERVER[net113@linuxlab ~]$ gcc -o ds dnss.c[net113@linuxlab ~]$ ./ds 7766Socket successfully createdThe name of the domain is the device's IP address is 172.56.54.2The name of the domain is the device's IP address is 172.62.2.54[net113@linuxlab ~]$ OUTPUTDNS CLIENT[net113@linuxlab ~]$ vi file.txt[net113@linuxlab ~]$ gcc -o dc dnsc.c[net113@linuxlab ~]$ ./dc 7766 localhostSocket successfully createdEnter the domain name Server's message: The IP address is 172.56.54.2Enter the domain name Server's message: The IP address is 172.62.2.54Enter the domain name stopRESULT:Thus a C program to implement the concept of DNS is executed successfully.Ex.no:10 SIMULATION OF SLIDING WINDOW PROTOCOL27.08.13AIM:To write a C program to implement sliding window protocolALGORITHM:SERVER:Create a socket for the sender using socket()Bind the socket using bind() with the port number specifiedEnter the text to be transmittedCopy the texdt to framesCheck for errors in the transmitted frameIf no error is received print “transmission is successful”.Else display the error and retransmit the frameIf “exit” , close the socket connectionCLIENT:Create socket for the receiver using socket()Comment the server using port numberRead frames sent by the server and check if the frames are being transmitted correctlyIf no, send error to the server and read the re-transmitted frameRead the sequence where error has occurredIf “exit” then close socket().CODING:// SLIDING WINDOW SERVER#include<netinet/in.h>#include<stdio.h>#include<sys/types.h>#include<stdlib.h>#include<string.h>#include<sys/socket.h># define size 4int main(int argc,char *argv[]){int sockfd,newsockfd,clilen,n,a=1,ch,len,i,status,j;struct sockaddr_in serv_addr,cliaddr;char frame[256],str[20],temp[20],ack[20];if(argc!=2){fprintf(stderr,"\n Error!No port Provided\n");exit(1);}sockfd=socket(AF_INET,SOCK_STREAM,0);if(sockfd<0)printerror("\n Error Opening Socket");elseprintf("\n Socket Successfully Created");bzero((char *)&serv_addr,sizeof(serv_addr));serv_addr.sin_family=AF_INET;serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);serv_addr.sin_port=htons(8246);if(bind(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr))<0)printerror("\n Error in Binding");listen(sockfd,5);len=sizeof(&cliaddr);newsockfd=accept(sockfd,(struct sockaddr *)&cliaddr,&len);if(newsockfd<0)printerror("\n Error on accept");printf("Enter the text\n");scanf("%s",str);i=0;while(i<strlen(str)){memset(frame,0,20);strncpy(frame,str+i,size);printf("Transmitting frames");len=strlen(frame);for(j=0;j<len;j++){printf("%d",i+j);sprintf(temp,"%d",i+j);strcat(frame,temp);}printf("\n\n");write(newsockfd,frame,sizeof(frame));read(newsockfd,ack,20);sscanf(ack,"%d",&status);if(status==-1)printf("Transmission success\n");else{printf("Recieved error in %d \n\n",status);printf("Retransmitting the frame");for(j=0;;){frame[j]=str[j+status];printf("%d",j+status);j++;if(((j+status) % 4)==0)break;}printf("\n\n");frame[j]='\0';len=strlen(frame);for(j=0;j<len;j++){sprintf(temp,"%d",j+status);strcat(frame,temp);}write(newsockfd,frame,sizeof(frame));}i+=size;}write(newsockfd,"exit",sizeof("exit"));printf("Exiting");sleep(5);close(newsockfd);close(sockfd);}int printerror(char * msg){perror(msg);}//SLIDING WINDOW CLIENT#include<sys/types.h>#include<sys/socket.h>#include<stdio.h>#include<stdlib.h>#include<string.h>#include<netinet/in.h>int main(int argc,char *argv[]){int i,sockfd,connfd,choice,n,a=1;struct sockaddr_in serv_addr,cli_addr;char buffer[256],str[10],str1[10],err[10];if(argc!=3){fprintf(stderr,"Type %s followed by host name and the port number \n",argv[0]);exit(0);}sockfd=socket(AF_INET,SOCK_STREAM,0);if(sockfd<0){printerror("\n Error opening Socket");exit(0);}elseprintf("\n Socket successfully created\n");bzero((char *)&serv_addr,sizeof(serv_addr));serv_addr.sin_family=AF_INET;serv_addr.sin_port=htons(8246);serv_addr.sin_addr.s_addr=INADDR_ANY;connect(sockfd,&serv_addr,sizeof(serv_addr));for(;;){read(sockfd,str,20);if(!strcmp(str,"exit")){printf("\n Exiting");break;}printf("Received %s\n",str);printf("Do you want to report error(1-yes,0-no)");scanf("%d",&choice);if(!choice)write(sockfd,"-1",sizeof(-1));else{printf("Enter the sequence no.of frames where error have occurred ");scanf("%s",err);write(sockfd,err,sizeof(err));read(sockfd,str,20);printf("Recieved the Retransmitted String %s",str);}}}int printerror(char *msg){perror(msg);}OUTPUTSLIDING WINDOW SERVER[net113@linuxlab ~]$ gcc -o sl sliss.c[net113@linuxlab ~]$ ./sl 8246Socket Successfully Created Enter the textNetworksTransmitting frames 0123Received error in 2Retransmitting the frame 23Transmitting frames 4567Transmission successExiting[net113@linuxlab ~]$ OUTPUTSLIDING WINDOW CLIENT[net113@linuxlab ~]$ gcc -o s2 slic.c[net113@linuxlab ~]$ ./s2 8246 localhostSocket successfully createdReceived Netw0123Do you want to report error (1-yes, 0-no)1Enter the sequence no. of frames where errors have occurred 2Received the Retransmitted String Received twDo you want to report error (1-yes, 0-no)0Received orks4567Do you want to report error (1-yes, 0-no)0[net113@linuxlab ~]$RESULT:Thus, a C program to implement sliding window protocol was executed successfully.Ex. No:Date:REMOTE PROCEDURE CALLAim:To write a C program to implement arithmetic operations using remote procedure calls.Algorithm:1. Define structure variable, add and sub functions.2. Create client stub and server stub by running rpcgen command.3. Get the two operands for adding and subtracting.4. Pass the two numbers in command line as arguments.5. If the argument count is less, print error message.6. Else print the added/subtracted value by calling remote procedure.Source Code://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 <stdio.h>#include "simp.h"int * add_1_svc(operands *argp, struct svc_req *rqstp){static int result;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" /* Created for us by rpcgen - has everything we need ! *//* Wrapper function takes care of calling the RPC procedure */int add( CLIENT *clnt, int x, int y){operands ops;int *result;// Gather everything into a single data structure to send to the server ops.x = x;ops.y = y;// Call the client stub created by rpcgen result = add_1(&ops,clnt);if (result==NULL){fprintf(stderr,"Trouble calling remote procedure\n");exit(0);}return(*result);}// Wrapper function takes care of calling the RPC procedure int sub( CLIENT *clnt, int x, int y){operands ops;int *result;/* Gather everything into a single data structure to send to the server */ops.x = x;ops.y = y;/* Call the client stub created by rpcgen */result = sub_1(&ops,clnt);if (result==NULL){fprintf(stderr,"Trouble calling remote procedure\n");exit(0);}return(*result);}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);}/* get the 2 numbers that should be added */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:[student@localhost ~]$ rpcgen simp.x[root@localhost net90]# gcc -o server simpservice.c simp_svc.c simp_xdr.c[root@localhost net90]# gcc -o client simpclient.c simp_clnt.c simp_xdr.c[student@localhost ~]$ ./serverGot request: adding 20, 10Got request: subtracting 20, 10[net90@localhost ~]$ ./client localhost 20 1020 + 10 = 3020 - 10 = 10Result:Ex. No:Date:STUDY OF NS-2 SIMULATORIntroduction:? NS-2 is an open source event-driven simulator specifically for researching communication networks.? NS-2 was developed at UC Berkeley.? It implements network protocols such as TCP and UDP.? NS-2 is a discrete event simulator targeted at networking research.? NS-2 provides substantial support for simulation of TCP, routing, and multicast protocols over wired and wireless (local and satellite) networks.? NS-2 has always included substantial contributions from other researchers, including wireless code from the UCB Daedelus and CMU Monarch projects and Sun Microsystems.Features of ns-2:? Call back driven events? Attributes system that manages default and per object simulation values.? Helps uses that allow using simpler API when configuring simulations.? It's not easy to modify and assembly different components and to change different parameters without a very visual and easy-to-use descriptive language.? When a user wants to make a new network object, he can either write the new object or assemble a compound object from the existing object library, and plumb the data path through the object. This plumbing makes NS2 very powerful.? Another feature of NS2 is the event scheduler.Basic Architecture of ns-2:NS-2 provides users with an executable command ns, which takes the input argument, the name of tcl simulation scripting file. In most cases, a simulation trace file is created and is used to plot graph and to create animation. NS-2 consists of two key languages: C++ and Object oriented Tool Command Language(OTCL). The C++ and OTCL are linked using TCL. In the OTCL command a handle acts as the front end which interacts with uses and other OTCL objects.NS-2 provides a large number of built in C++ objects. It is advisable to use these C++ objects to set up a simulation using a TCL Simulation script. After simulation NS-2 outputs either text-based or animation-based results. To interpret these results graphically and interactively tools such as NAM and XGRAPH are used.Tools:Nam (Network Animator)-> Packet-level animation-> Well-supported by ns-> Commandline start: “nam <nam-tracefile>”Xgraph-> Convert trace output into xgraph format-> Commandline start: “xgraph”Gnuplot-> Convert ASCII Text e.g. trace into 2D/3D plot-> Commandline start: “gnuplot <scriptfile>”Simulation Steps:Step 1: Simulation designThe first step in simulating a network is to design the simulation. In this step,the users should determine the simulations purposes, a network configurations and assumptions, the performance measures and the type of expected results.Step 2: Configuring and Running SimulationThis step implements the design in the first step. It consists of two phases:? Network configuration phase? Simulation phaseStep 3: Post Simulation ProcessingThe main task in this step includes verifying the integrity of the program and evaluating the performance of the simulated network.Result:Ex. No:Date:DV ROUTING PROTOCOLAim:To simulate the Distance Vector (DV) routing protocol.Algorithm:1. Create a new simulator instance.2. Set the color for data flows in NAM with blue and red color.3. Open the trace file and NAM file in write mode.4. In the finish function, flush the trace file and execute the NAM file.5. Create a node for the corresponding network path.6. Create the link between the nodes, set the duplex-link and speed, time and droptail techniques.7. Set the position for the nodes and set the queue limits of nodes.8. Set up the TCP and UDP connection between the nodes.9. Set up FTP over TCP connection.10.Start ns and simulate till 5 minutes are over.11. Display using xgraph the simulated data.Source Code://dv.tclset 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 dv.tr w]$ns trace-all $file1#Open the NAM trace file set file2 [open dv.nam w]$ns namtrace-all $file2#Define a 'finish' procedure proc finish {} {global ns file1 file2$ns flush-trace close $file1 close $file2exec nam dv.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$ns duplex-link-op $n1 $n2 orient right$ns duplex-link-op $n2 $n3 orient up$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 connectionset tcp [new Agent/TCP/Newreno]$ns attach-agent $n0 $tcpset 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 runOutput:[student@localhost ~]$ ns dv.tcl[student@localhost~]$ raw2xg -adv.tr>dv.xg[student@localhost~]$xgraphdv.xg -t“Simulationof DVroutingprotocol”Result:Ex. No:Date:COMPARISON OF LS AND DVAim: To compare the performance of Link State (LS) and Distance Vector (DV) routing protocol.Algorithm:1. Create a new simulator instance.2. Set the color for data flows in NAM with blue and red color.3. Open the trace file and NAM file in write mode for both LS and DV.4. Create six nodes.5. Create duplex link between the nodes created and with proper orientation.6. Set up a TCP connection7. Then set up FTP over TCP.8. In the finish function, flush the trace file and execute the NAM file.9. The link from node 1 to node 4 is set to down at time 1.0 and up at time 4.510.Start ns and simulate till 5 minutes are over.11. The comparison of LS and DV is displayed using xgraph tool.Source Code://dv.tcl Previous experiment code can be used//ls.tclset 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 ls.tr w]$ns trace-all $file1#Open the NAM trace file set file2 [open ls.nam w]$ns namtrace-all $file2#Define a 'finish' procedure proc finish {} {global ns file1 file2$ns flush-trace close $file1 close $file2exec nam ls.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$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 connectionset tcp [new Agent/TCP/Newreno]$ns attach-agent $n0 $tcpset 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 runOutput:[student@localhost ~]$ ns dv.tcl[student@localhost ~]$ ns ls.tcl[student@localhost ~]$ raw2xg -a ls.tr > ls.xg[student@localhost~]$ raw2xg -adv.tr>dv.xg[student@localhost~]$xgraphls.xgdv.xg -t“Comparisonof LS&DV”Result:Ex. No:Date:PERFORMANCE OF TCP Aim: To simulate the performance of TCP in static routing technique.Algorithm:1. Create a new simulator instance.2. Set the color for data flows in NAM with blue and red color.3. Open the trace file and NAM file in write mode.4. In the finish function, flush the trace file and execute the NAM file.5. Create a node for the corresponding network path.6. Create the link between the nodes, set the duplex-link and speed, time and droptail techniques.7. Set the position for the nodes and set the queue limits of nodes.8. Set up the TCP connection.9. Set up FTP over TCP connection.10.Start ns and simulate till 5 minutes are over.11. Display using xgraph the simulated data.Source Code://tcpPerf.tclset ns [new Simulator]#Define different colors for data flows (for NAM)$ns color 1 Blue$ns color 2 Red#Open the Trace fileset file1 [open tcpPerf.tr w]#Open the NAM trace fileset file2 [open tcpPerf.nam w]$ns namtrace-all $file2#Define a 'finish' procedure proc finish {} {global ns file1 file2$ns flush-trace close $file1 close $file2exec nam tcpPerf.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$ns duplex-link-op $n1 $n2 orient right$ns duplex-link-op $n2 $n3 orient up$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 connectionset tcp [new Agent/TCP/Newreno]$ns attach-agent $n0 $tcpset 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 runOutput:[student@localhost ~]$ ns tcpPerf.tcl[student@localhost ~]$ xgraph tcpPerf.xg -t “Performance of TCP in Static Routing”Result:Ex. No:Date:PERFORMANCE OF UDPAim:To analyze the performance of UDP using ns2.Algorithm:1. Create a new simulator instance.2. Set the color for data flows in NAM with blue and red color.3. Open the trace file and NAM file in write mode.4. Create six nodes.5. Create duplex link between the nodes created and with proper orientation.6. Set up a UDP connection7. Then set up FTP over UDP8. Set up Constant Bit Rate(CBR) and packet size to 1000..9. In the finish function, flush the trace file and execute the NAM file.10.Start ns and simulate till 5 minutes are over.11. The simulated data is displayed using xgraph tool.Source Code://udpPerf.tclset ns [new Simulator]#define different colors for dataflows (for NAM)$ns color 1 Blue$ns color 2 Red#open the trace fileset file1 [open UDPoutDV.tr w]set winfile [open WinFile w]$ns trace-all $file1#open the NAM trace fileset file2 [open UDPoutDV.nam w]$ns namtrace-all $file2#define a finish procedure proc finish {} {global ns file1 file2$ns flush-trace close $file1 close $file2exec nam UDPoutDV.nam &exit 0}#next line should be commented out to have a static routing$ns rtproto DV#create nodesset 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 nodes$ns duplex-link $n0 $n2 2Mb 10ms DropTail$ns duplex-link $n1 $n2 2Mb 10ms DropTail$ns duplex-link $n2 $n3 0.3Mb 100ms DropTail$ns duplex-link $n3 $n2 0.3Mb 100ms DropTail$ns duplex-link $n3 $n4 0.5Mb 40ms DropTail$ns duplex-link $n3 $n5 0.5Mb 30ms DropTail#give node position for NAM$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$ns duplex-link-op $n3 $n2 orient left$ns duplex-link-op $n3 $n4 orient right-up$ns duplex-link-op $n3 $n5 orient right-down#set queue size of link (n2 - n3) to 10$ns queue-limit $n2 $n3 20#set udp connectionset udp [new Agent/UDP]$ns attach-agent $n1 $udp set null [new Agent/Null]$ns attach-agent $n5 $null$ns connect $udp $null$udp set fid_ 2#setup a cbr over udp connectionset cbr [new Application/Traffic/CBR]$cbr attach-agent $udp$cbr set type_ CBR$cbr set packet_size_ 1000$cbr set rate_ 0.01Mb$cbr set random_ false$ns at 0.1 "$cbr start"$ns at 11.5 "$cbr stop"$ns at 12.0 "finish"$ns runOutput:[student@localhost ~]$ ns udpPerf.tclResult:Ex. No:Date:PERFORMANCE OF MACAim:To analyze the performance of MAC protocol using ns2 simulator.Algorithm:1. Create a new simulator instance.2. Set the color for data flows in NAM with blue and red color.3. Open the trace file and NAM file in write mode.4. Set up a LAN with six nodes.5. The CSMA/CD protocol is set for this newly created LAN and bandwidth as1MB.6. Set up a TCP connection7. Then set up FTP over TCP.8. Set up window size as 4096 and packet size to 1024.9. In the finish function, flush the trace file and execute the NAM file.10.Start ns and simulate till 5 minutes are over.11. The simulated data is displayed using xgraph tool.Source Code://macproto.tclset ns [new Simulator]#define different colors for data flows (for NAM)$ns color 1 Blue$ns color 2 Red#open a trace filesset file1 [open nout.tr w]set winfile [open WinFile w]set file2 [open nout.nam w]$ns namtrace-all $file2#define a 'finish' procedure proc finish {} {global ns file1$ns flush-trace close $file1exec nam nout.nam &exit 0}global lan node source n(0)set n1 [$ns node] set n2 [$ns node] set ma Channelset lan [$ns newLan "$n1 $n2" 1Mb 40ms LL Queue/DropTail MAC/CSMA/CD$ma]set tcp [new Agent/TCP/Newreno]$ns attach-agent $n1 $tcpset sink [new Agent/TCPSink/DelAck]$ns attach-agent $n2 $sink$ns connect $tcp $sink$tcp set fid_ 1$tcp set window_ 4096$tcp set packetSize_ 1024$ma set fid_ 2#setup a ftp over tcp connection set ftp [new Application/FTP]$ftp attach-agent $tcp$ftp set type_ FTP$ns at 1.0 "$ftp start"$ns at 5.0 "$ftp stop"$ns at 5.0 "finish"$ns runOutput:[student@localhost ~]$ ns macproto.tclResult:Ex. No:Date:CRIMPING OF NETWORK CABLE WITH RJ45 CONNECTORRequirements:Ethernet Cable - bulk Category (Cat) 5, 5e, 6, 6a or higher ethernet cableWire Cutters - to cut and strip the ethernet cable if necessaryFor Patch Cables:o8P8C Modular Connector Plugs ("RJ45")oModular Connector Crimper ("RJ45")For Fixed Wiring:o8P8C Modular Connector Jacks ("RJ45")o110 Punch Down ToolCable:You can find bulk supplies of ethernet cable at many computer stores or most electrical or home centers. You want UTP (Unshielded Twisted Pair) ethernet cable of at least Category 5 (Cat 5). Cat 5 is required for basic 10/100 functionality, you will want Cat 5e for gigabit (1000BaseT) operation and Cat 6 or higher gives you a measure of future proofing. You can also use STP (Shielded Twisted Pair) for extra resistance to external interference but I won't cover shielded connectors. Bulk ethernet cable comes in many types, there are 2 basic categories, solid and braided stranded cable. Stranded ethernet cable tends to work better in patch applications for desktop use. It is more flexible and resilient than solid ethernet cable and easier to work with, but really meant for shorter lengths. Solid ethernet cable is meant for longer runs in a fixed position.Internal Cable Structure and Color CodingInside the ethernet cable, there are 8 color coded wires. These wires are twisted into 4 pairs of wires, each pair has a common color theme. One wire in the pair being a solid or primarily solid colored wire and the other being a primarily white wire with a colored stripe (Sometimes ethernet cables won't have any color on the striped wire, the only way to tell which is which is to check which wire it is twisted around). Examples of the naming schemes used are: Orange (alternatively Orange/White) for the solid colored wire and White/Orange for the striped cable. The twists are extremely important. They are there to counteract noise and interference. It is important to wire according to a standard to get proper performance from the ethernet cable. The TIA/EIA-568-A specifies two wiring standards for an 8-position modular connector such as RJ45. The two wiring standards, T568A and T568B vary only in the arrangement of the colored pairs.Modular Connector Plugs and Jacks:The 8P8C modular connectors for Ethernet are often called RJ45 due to their physical ressemblance. The plug is an 8-position modular connector that looks like a large phone plug. There are a couple variations available. The primary variation you need to pay attention to is whether the connector is intended for braided or solid wire. For braided/stranded wires, the connector has sharp pointed contacts that actually pierce the wire. For solid wires, the connector has fingers which cut through the insulation and make contact with the wire by grasping it from both sides. The connector is the weak point in an ethernet cable, choosing the wrong one will often cause grief later. If you just walk into a computer store, it's nearly impossible to tell what type of plug it is. You may be able to determine what type it is by crimping one without a cable.Modular connector jacks come in a variety styles intended for several different mounting options. The choice is one of requirements and preference. Jacks are designed to work only with solid ethernet cable. Most jacks come labeled with color coded wiring diagrams for either T568A, T568B or both. Make sure you end up with the correct one.ModularConnectorPlugandJackPinOutEthernet Cable Pin Outs:There are two basic ethernet cable pin outs. A straight through ethernet cable, which is used to connect to a hub or switch, and a crossover ethernet cable used to operate in a peer-to-peer fashion without a hub/switch. Generally all fixed wiring should be run as straight through. Some ethernet interfaces can cross and un-cross a cable automatically as needed, a handy feature.+Note: The crossover ethernet cable layout is suitable for 1000Base-T operation, all 4 pairs are crossed.How to wire Ethernet Patch Cables:1. Strip off about 2 inches of the ethernet cable sheath.2. Untwist the pairs - don't untwist them beyond what you have exposed, the more untwisted cable you have the worse the problems you can run into.3. Align the colored wires according to the wiring diagrams above.4. Trim all the wires to the same length, about 1/2" to 3/4" left exposed from the sheath.5. Insert the wires into the RJ45 plug - make sure each wire is fully inserted to the front of the RJ45 plug and in the correct order. The sheath of the ethernet cable should extend into the plug by about 1/2" and will be held in place by the crimp.6. Crimp the RJ45 plug with the crimper tool.7. Verify the wires ended up the right order and that the wires extend to the front of the RJ45 plug and make good contact with the metal contacts in the RJ45 plug8. Cut the ethernet cable to length - make sure it is more than long enough for your needs.9. Repeat the above steps for the second RJ45 plug.How to wire fixed Ethernet Cables:1. Run the full length of ethernet cable in place, from endpoint to endpoint, making sure to leave excess.2. At one end, cut the wire to length leaving enough length to work, but not too much excess.3. Strip off about 2 inches of the ethernet cable sheath.4. Align each of the colored wires according to the layout of the jack.5. Use the punch down tool to insert each wire into the jack.6. Repeat the above steps for the second RJ45 jack.If an ethernet cable tester is available, use it to verify the proper connectivity of the cable. That should be it, if your ethernet cable doesn't turn out, look closely at each end and see if you can find the problem. Often a wire ended up in the wrong place or one of the wires is making no contact or poor contact. Also double check the color coding to verify it is correct. If you see a mistake or problem, cut the end off and start again. A ethernet cable tester is invaluable at identifying and highlighting these issues.When sizing ethernet cables remember that an end to end connection should not extend more than 100m (~328ft). Try to minimize the ethernet cable length, the longer the cable becomes, the more it may affect performance. This is usually noticeable as a gradual decrease in speed and increase in latency.Result: ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download