unix networking programming

67

Upload: rajat-joshi

Post on 18-Jan-2016

35 views

Category:

Documents


3 download

DESCRIPTION

This is the lab manual for 8th sem CSE (Rajasthan Technical University)

TRANSCRIPT

Page 1: Unix Networking Programming
Page 2: Unix Networking Programming

1

Table of ContentsSyllabus........................................................................................................................................................2

8CS5 UNIX NETWORK PROGRAMMING & SIMULATION LAB.......................................................................3

1. Introduction to Socket Programming..................................................................................................4

2. Java - Networking (Socket Programming)............................................................................................6

3. TCP Socket Example...........................................................................................................................16

4. UDP Socket Programming for Client_Hello and Server_Hello............................................................21

5. UDP Socket Programming for Echo_Client and Echo_Server.............................................................27

6. Sending Mail Using UDP Sockets.......................................................................................................32

7. Network Simulator 2..........................................................................................................................35

Page 3: Unix Networking Programming

2

Syllabus

Page 4: Unix Networking Programming

3

8CS5 UNIX NETWORK PROGRAMMING & SIMULATION LAB

S. No. Experiment Title

1. Introduction to Socket Programming

2.

Write two programs in C: hello_client and hello_server- The server listens for, and accepts, a single TCP connection; it reads all the data it can from that connection, and prints it to the screen; then it closes the connection The client connects to the server, sends the string“Hello, world!”, then closes the connection

3.Write an Echo_Client and Echo_server using TCP to estimate the round trip time from client to the server. The server should be such that it can accept multiple connections at any given time.

4. Repeat Exercises 1 for UDP.

5. Repeat Exercises 2 for UDP.

6. Repeat Exercise 2 with multiplexed I/O operations

7. Introduction to NS2

8. Simulate Bellman-Ford Routing algorithm in NS2

Page 5: Unix Networking Programming

4

1. Introduction to Socket ProgrammingA socket is one of the most fundamental technologies of computer networking. Sockets allow applications to communicate using standard mechanisms built into network hardware and operating systems. Although network software may seem to be a relatively new "Web" phenomenon, socket technology actually has been employed for roughly two decades.

Software applications that rely on the Internet and other computer networks continue to grow in popularity. Many of today's most popular software packages -- including Web browsers, instant messaging applications and peer to peer file sharing systems -- rely on sockets.

Point-to-Point Communication

In a nutshell, a socket represents a single connection between exactly two pieces of software. More than two pieces of software can communicate in client/server or distributed systems (for example, many Web browsers can simultaneously communicate with a single Web server) but multiple sockets are required to do this. Socket-based software usually runs on two separate computers on the network, but sockets can also be used to communicate locally (interprocess) on a single computer.

Sockets are bidirectional, meaning that either side of the connection is capable of both sending and receiving data. Sometimes the one application that initiates communication is termed the client and the other application the server, but this terminology leads to confusion in non-client/server systems and should generally be avoided.

Libraries

Programmers access sockets using code libraries packaged with the operating system. Several libraries that implement standard application programming interfaces (APIs) exist. The first mainstream package - the Berkeley Socket Library is still widely in use on UNIX® systems. Another very common API is the Windows Sockets (Winsock) library for Microsoft operating systems. Relative to other network programming technologies, socket APIs are quite mature: Winsock has been in use since 1993 and Berkeley sockets since 1982.

Interface Types

Socket interfaces can be divided into three categories. Perhaps the most commonly-used type, the stream socket, implements "connection-oriented" semantics. Essentially, a "stream" requires that the two communicating parties first establish a socket connection, after which any data passed through that connection will be guaranteed to arrive in the same order in which it was sent.

Datagram sockets offer "connection-less" semantics. With datagrams, connections are implicit rather than explicit as with streams. Either party simply sends datagrams as needed and waits for

Page 6: Unix Networking Programming

5

the other to respond; messages can be lost in transmission or received out of order, but it is the application's responsibility and not the socket's to deal with these problems. Implementing datagram sockets can give some applications a performance boost and additional flexibility compared to using stream sockets, justifying their use in some situations.

The third type of socket -- the so-called raw socket -- bypasses the library's built-in support for standard protocols like TCP and UDP. Raw sockets are used for custom low-level protocol development.

Addresses and Ports

Today, sockets are typically used in conjunction with the Internet protocols -- Internet Protocol, Transmission Control Protocol, and User Datagram Protocol (UDP). Libraries implementing sockets for Internet Protocol use TCP for streams, UDP for datagrams, and IP itself for raw sockets.

To communicate over the Internet, IP socket libraries use the IP address to identify specific computers. Many parts of the Internet work with naming services, so that the users and socket programmers can work with computers by name (e.g., "thiscomputer.compnetworking.about.com") instead of by address (e.g., 208.185.127.40). Stream and datagram sockets also use IP port numbers to distinguish multiple applications from each other. For example, Web browsers on the Internet know to use port 80 as the default for socket communications with Web servers.

Socket Programming and You

Traditionally, sockets have been of interest mainly to computer programmers. But as new networking applications emerge, end users are becoming increasingly network-savvy. Many Web surfers, for example, now know that some addresses in the browser look like

http://206.35.113.28:8080/

where 8080 is the port number being used by that socket.

The socket APIs are relatively small and simple. Many of the functions are similar to those used in file input/output routines such as read(), write(), and close(). The actual function calls to use depend on the programming language and socket library chosen.

Page 7: Unix Networking Programming

6

2. Java - Networking (Socket Programming)The term network programming refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network.

The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide the low-level communication details, allowing you to write programs that focus on solving the problem at hand.

The java.net package provides support for the two common network protocols:

TCP: TCP stands for Transmission Control Protocol, which allows for reliable communication between two applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP.

UDP: UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of data to be transmitted between applications.

This tutorial gives good understanding on the following two subjects:

Socket Programming: This is most widely used concept in Networking and it has been explained in very detail.

URL Processing: This would be covered separately. Click here to learn about URL Processing in Java language.

Socket Programming:

Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server.

When the connection is made, the server creates a socket object on its end of the communication. The client and server can now communicate by writing to and reading from the socket.

The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for the server program to listen for clients and establish connections with them.

The following steps occur when establishing a TCP connection between two computers using sockets:

i. The server instantiates a ServerSocket object, denoting which port number communication is to occur on.

ii. The server invokes the accept() method of the ServerSocket class. This method waits until a client connects to the server on the given port.

Page 8: Unix Networking Programming

7

iii. After the server is waiting, a client instantiates a Socket object, specifying the server name and port number to connect to.

iv. The constructor of the Socket class attempts to connect the client to the specified server and port number. If communication is established, the client now has a Socket object capable of communicating with the server.

v. On the server side, the accept() method returns a reference to a new socket on the server that is connected to the client's socket.

After the connections are established, communication can occur using I/O streams. Each socket has both an OutputStream and an InputStream. The client's OutputStream is connected to the server's InputStream, and the client's InputStream is connected to the server's OutputStream.

TCP is a two way communication protocol, so data can be sent across both streams at the same time. There are following usefull classes providing complete set of methods to implement sockets.

ServerSocket Class Methods:

The java.net.ServerSocket class is used by server applications to obtain a port and listen for client requests

The ServerSocket class has four constructors:

SN Methods with Description

1.public ServerSocket(int port) throws IOExceptionAttempts to create a server socket bound to the specified port. An exception occurs if the port is already bound by another application.

2.public ServerSocket(int port, int backlog) throws IOExceptionSimilar to the previous constructor, the backlog parameter specifies how many incoming clients to store in a wait queue.

3.

public ServerSocket(int port, int backlog, InetAddress address) throws IOExceptionSimilar to the previous constructor, the InetAddress parameter specifies the local IP address to bind to. The InetAddress is used for servers that may have multiple IP addresses, allowing the server to specify which of its IP addresses to accept client requests on

4.public ServerSocket() throws IOExceptionCreates an unbound server socket. When using this constructor, use the bind() method when you are ready to bind the server socket

If the ServerSocket constructor does not throw an exception, it means that your application has successfully bound to the specified port and is ready for client requests.

Page 9: Unix Networking Programming

8

Here are some of the common methods of the ServerSocket class:

SN Methods with Description

1.public int getLocalPort()Returns the port that the server socket is listening on. This method is useful if you passed in 0 as the port number in a constructor and let the server find a port for you.

2.

public Socket accept() throws IOExceptionWaits for an incoming client. This method blocks until either a client connects to the server on the specified port or the socket times out, assuming that the time-out value has been set using the setSoTimeout() method. Otherwise, this method blocks indefinitely

3.public void setSoTimeout(int timeout)Sets the time-out value for how long the server socket waits for a client during the accept().

4.public void bind(SocketAddress host, int backlog)Binds the socket to the specified server and port in the SocketAddress object. Use this method if you instantiated the ServerSocket using the no-argument constructor.

When the ServerSocket invokes accept(), the method does not return until a client connects. After a client does connect, the ServerSocket creates a new Socket on an unspecified port and returns a reference to this new Socket. A TCP connection now exists between the client and server, and communication can begin.

Socket Class Methods:

The java.net.Socket class represents the socket that both the client and server use to communicate with each other. The client obtains a Socket object by instantiating one, whereas the server obtains a Socket object from the return value of the accept() method.

The Socket class has five constructors that a client uses to connect to a server:

SN Methods with Description

1.

public Socket(String host, int port) throws UnknownHostException, IOException.This method attempts to connect to the specified server at the specified port. If this constructor does not throw an exception, the connection is successful and the client is connected to the server.

2. public Socket(InetAddress host, int port) throws IOExceptionThis method is identical to the previous constructor, except that the host is denoted by an

Page 10: Unix Networking Programming

9

InetAddress object.

3.

public Socket(String host, int port, InetAddress localAddress, int localPort) throws IOException.Connects to the specified host and port, creating a socket on the local host at the specified address and port.

4.

public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException.This method is identical to the previous constructor, except that the host is denoted by an InetAddress object instead of a String

5.public Socket()Creates an unconnected socket. Use the connect() method to connect this socket to a server.

When the Socket constructor returns, it does not simply instantiate a Socket object but it actually attempts to connect to the specified server and port.

Some methods of interest in the Socket class are listed here. Notice that both the client and server have a Socket object, so these methods can be invoked by both the client and server.

SN Methods with Description

1.public void connect(SocketAddress host, int timeout) throws IOExceptionThis method connects the socket to the specified host. This method is needed only when you instantiated the Socket using the no-argument constructor.

2.public InetAddress getInetAddress()This method returns the address of the other computer that this socket is connected to.

3.public int getPort()Returns the port the socket is bound to on the remote machine.

4.public int getLocalPort()Returns the port the socket is bound to on the local machine.

5.public SocketAddress getRemoteSocketAddress()Returns the address of the remote socket.

6.public InputStream getInputStream() throws IOExceptionReturns the input stream of the socket. The input stream is connected to the output stream of the remote socket.

Page 11: Unix Networking Programming

10

7.public OutputStream getOutputStream() throws IOExceptionReturns the output stream of the socket. The output stream is connected to the input stream of the remote socket

8.public void close() throws IOExceptionCloses the socket, which makes this Socket object no longer capable of connecting again to any server

InetAddress Class Methods:

This class represents an Internet Protocol (IP) address. Here are following usefull methods which you would need while doing socket programming:

SN Methods with Description

1.static InetAddress getByAddress(byte[] addr)Returns an InetAddress object given the raw IP address .

2.static InetAddress getByAddress(String host, byte[] addr)Create an InetAddress based on the provided host name and IP address.

3.static InetAddress getByName(String host)Determines the IP address of a host, given the host's name.

4.String getHostAddress() Returns the IP address string in textual presentation.

5.String getHostName() Gets the host name for this IP address.

6.static InetAddress InetAddress getLocalHost()Returns the local host.

7.String toString()Converts this IP address to a String.

Socket Client Example:

The following GreetingClient is a client program that connects to a server by using a socket and sends a greeting, and then waits for a response.

Page 12: Unix Networking Programming

11

// File Name GreetingClient.java

import java.net.*;

import java.io.*;

public class GreetingClient

{

public static void main(String [] args)

{

String serverName = args[0];

int port = Integer.parseInt(args[1]);

try

{

System.out.println("Connecting to " + serverName

+ " on port " + port);

Socket client = new Socket(serverName, port);

System.out.println("Just connected to "

+ client.getRemoteSocketAddress());

OutputStream outToServer = client.getOutputStream();

DataOutputStream out =

new DataOutputStream(outToServer);

out.writeUTF("Hello from "

+ client.getLocalSocketAddress());

InputStream inFromServer = client.getInputStream();

DataInputStream in =

new DataInputStream(inFromServer);

Page 13: Unix Networking Programming

12

System.out.println("Server says " + in.readUTF());

client.close();

}catch(IOException e)

{

e.printStackTrace();

}

}

}

Socket Server Example:

The following GreetingServer program is an example of a server application that uses the Socket class to listen for clients on a port number specified by a command-line argument:

// File Name GreetingServer.java

import java.net.*;

import java.io.*;

public class GreetingServer extends Thread

{

private ServerSocket serverSocket;

public GreetingServer(int port) throws IOException

{

serverSocket = new ServerSocket(port);

serverSocket.setSoTimeout(10000);

}

public void run()

Page 14: Unix Networking Programming

13

{

while(true)

{

try

{

System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");

Socket server = serverSocket.accept();

System.out.println("Just connected to "

+ server.getRemoteSocketAddress());

DataInputStream in =

new DataInputStream(server.getInputStream());

System.out.println(in.readUTF());

DataOutputStream out =

new DataOutputStream(server.getOutputStream());

out.writeUTF("Thank you for connecting to "

+ server.getLocalSocketAddress() + "\nGoodbye!");

server.close();

}catch(SocketTimeoutException s)

{

System.out.println("Socket timed out!");

break;

}catch(IOException e)

{

e.printStackTrace();

break;

Page 15: Unix Networking Programming

14

}

}

}

public static void main(String [] args)

{

int port = Integer.parseInt(args[0]);

try

{

Thread t = new GreetingServer(port);

t.start();

}catch(IOException e)

{

e.printStackTrace();

}

}

}

Compile client and server and then start server as follows:

$ java GreetingServer 6066

Waiting for client on port 6066...

Check client program as follows:

$ java GreetingClient localhost 6066

Connecting to localhost on port 6066

Just connected to localhost/127.0.0.1:6066

Server says Thank you for connecting to /127.0.0.1:6066

Page 16: Unix Networking Programming

15

Goodbye!

Page 17: Unix Networking Programming

16

3. TCP Socket Example

TCP client/server communication flow:

Page 18: Unix Networking Programming

17

TCPClient.java communication model:

Page 19: Unix Networking Programming

18

TCPServer.java communication model (UDP figure):

TCP server code:

import java.io.*;

import java.net.*;

class TCPServer

Page 20: Unix Networking Programming

19

{

public static void main(String argv[]) throws Exception

{

String clientSentence;

String capitalizedSentence;

ServerSocket welcomeSocket = new ServerSocket(6789);

while(true)

{

Socket connectionSocket = welcomeSocket.accept();

BufferedReader inFromClient =

new BufferedReader(

new InputStreamReader(

connectionSocket.getInputStream()));

DataOutputStream outToClient =

new DataOutputStream(

connectionSocket.getOutputStream());

clientSentence = inFromClient.readLine();

capitalizedSentence = clientSentence.toUpperCase() + '\n';

outToClient.writeBytes(capitalizedSentence);

}

}

Page 21: Unix Networking Programming

20

}

TCP client code:

import java.io.*;

import java.net.*;

class TCPClient

{

public static void main(String argv[]) throws Exception

{

String sentence;

String modifiedSentence;

BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

Socket clientSocket = new Socket("localhost", 6789);

DataOutputStream outToServer =

new DataOutputStream(

clientSocket.getOutputStream());

BufferedReader inFromServer =

new BufferedReader(

new InputStreamReader(

clientSocket.getInputStream()));

Page 22: Unix Networking Programming

21

sentence = inFromUser.readLine();

outToServer.writeBytes(sentence + '\n');

modifiedSentence = inFromServer.readLine();

System.out.println("FROM SERVER: " + modifiedSentence);

clientSocket.close();

}

}

To Compile

javac TCPServer.java

javac TCPClient.java

To Run

Server:

java TCPServer

Client:

java TCPClient

hello how are you [Enter]

Page 23: Unix Networking Programming

22

4. UDP Socket Programming for Client_Hello and Server_Hello

UDP Socket Example

UDP client/server communication flow:

UDPClient.java communication model:

Page 24: Unix Networking Programming

23

UDPServer.java communication model:

UDP server code:

import java.io.*;

import java.net.*;

class UDPServer

{

public static void main(String args[]) throws Exception

{

DatagramSocket serverSocket =

new DatagramSocket(9876);

byte[] receiveData = new byte[1024];

byte[] sendData;

Page 25: Unix Networking Programming

24

while(true)

{

DatagramPacket receivePacket =

new DatagramPacket(receiveData, receiveData.length);

serverSocket.receive(receivePacket);

String sentence = new String(receivePacket.getData(),

0, receivePacket.getLength());

InetAddress IPAddress = receivePacket.getAddress();

int port = receivePacket.getPort();

String capitalizedSentence = sentence.toUpperCase();

sendData = capitalizedSentence.getBytes();

DatagramPacket sendPacket =

new DatagramPacket(sendData, sendData.length,

IPAddress, port);

serverSocket.send(sendPacket);

}

}

}

Page 26: Unix Networking Programming

25

UDP client code:

import java.io.*;

import java.net.*;

class UDPClient

{

public static void main(String args[]) throws Exception

{

BufferedReader inFromUser =

new BufferedReader(

new InputStreamReader(System.in));

DatagramSocket clientSocket = new DatagramSocket();

// Replace hostname with the FQDN of the server.

InetAddress IPAddress = InetAddress.getByName("localhost");

byte[] sendData;

byte[] receiveData = new byte[1024];

String sentence = inFromUser.readLine();

sendData = sentence.getBytes();

Page 27: Unix Networking Programming

26

DatagramPacket sendPacket =

new DatagramPacket(sendData, sendData.length,

IPAddress, 9876);

clientSocket.send(sendPacket);

DatagramPacket receivePacket =

new DatagramPacket(receiveData, receiveData.length);

clientSocket.receive(receivePacket);

String modifiedSentence = new String(receivePacket.getData(),

0, receivePacket.getLength());

System.out.println("FROM SERVER: " + modifiedSentence);

clientSocket.close();

}

}

Running the Server and Client

To Compile

javac UDPServer.java

javac UDPClient.java

To Run

Server:

Page 28: Unix Networking Programming

27

java UDPServer

Client:

java UDPClient

hello how are you [Enter]

Page 29: Unix Networking Programming

28

5. UDP Socket Programming for Echo_Client and Echo_ServerUDP client/server communication flow:

UDPClient.java communication model:

Page 30: Unix Networking Programming

29

UDPServer.java communication model:

UDP server code:

import java.io.*;

import java.net.*;

class UDPServer

{

public static void main(String args[]) throws Exception

{

DatagramSocket serverSocket =

new DatagramSocket(9876);

byte[] receiveData = new byte[1024];

byte[] sendData;

Page 31: Unix Networking Programming

30

while(true)

{

DatagramPacket receivePacket =

new DatagramPacket(receiveData, receiveData.length);

serverSocket.receive(receivePacket);

String sentence = new String(receivePacket.getData(),

0, receivePacket.getLength());

InetAddress IPAddress = receivePacket.getAddress();

int port = receivePacket.getPort();

String capitalizedSentence = sentence.toUpperCase();

sendData = capitalizedSentence.getBytes();

DatagramPacket sendPacket =

new DatagramPacket(sendData, sendData.length,

IPAddress, port);

serverSocket.send(sendPacket);

}

}

Page 32: Unix Networking Programming

31

}

UDP client code:

import java.io.*;

import java.net.*;

class UDPClient

{

public static void main(String args[]) throws Exception

{

BufferedReader inFromUser =

new BufferedReader(

new InputStreamReader(System.in));

DatagramSocket clientSocket = new DatagramSocket();

// Replace hostname with the FQDN of the server.

InetAddress IPAddress = InetAddress.getByName("hostname");

byte[] sendData;

byte[] receiveData = new byte[1024];

String sentence = inFromUser.readLine();

Page 33: Unix Networking Programming

32

sendData = sentence.getBytes();

DatagramPacket sendPacket =

new DatagramPacket(sendData, sendData.length,

IPAddress, 9876);

clientSocket.send(sendPacket);

DatagramPacket receivePacket =

new DatagramPacket(receiveData, receiveData.length);

clientSocket.receive(receivePacket);

String modifiedSentence = new String(receivePacket.getData(),

0, receivePacket.getLength());

System.out.println("FROM SERVER: " + modifiedSentence);

clientSocket.close();

}

}

Page 34: Unix Networking Programming

33

6. Sending Mail Using UDP Sockets

import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.io.PrintWriter;import java.net.InetAddress;import java.net.Socket;import java.net.UnknownHostException;

public class SMTPDemo {

  public static void main(String args[]) throws IOException,      UnknownHostException {    String msgFile = "file.txt";    String from = "[email protected]";    String to = "[email protected]";    String mailHost = "yourHost";    SMTP mail = new SMTP(mailHost);    if (mail != null) {      if (mail.send(new FileReader(msgFile), from, to)) {        System.out.println("Mail sent.");      } else {        System.out.println("Connect to SMTP server failed!");      }    }    System.out.println("Done.");  }

  static class SMTP {    private final static int SMTP_PORT = 25;

    InetAddress mailHost;

Page 35: Unix Networking Programming

34

    InetAddress localhost;

    BufferedReader in;

    PrintWriter out;

    public SMTP(String host) throws UnknownHostException {      mailHost = InetAddress.getByName(host);      localhost = InetAddress.getLocalHost();      System.out.println("mailhost = " + mailHost);      System.out.println("localhost= " + localhost);      System.out.println("SMTP constructor done\n");    }

    public boolean send(FileReader msgFileReader, String from, String to)        throws IOException {      Socket smtpPipe;      InputStream inn;      OutputStream outt;      BufferedReader msg;      msg = new BufferedReader(msgFileReader);      smtpPipe = new Socket(mailHost, SMTP_PORT);      if (smtpPipe == null) {        return false;      }      inn = smtpPipe.getInputStream();      outt = smtpPipe.getOutputStream();      in = new BufferedReader(new InputStreamReader(inn));      out = new PrintWriter(new OutputStreamWriter(outt), true);      if (inn == null || outt == null) {        System.out.println("Failed to open streams to socket.");        return false;      }      String initialID = in.readLine();      System.out.println(initialID);      System.out.println("HELO " + localhost.getHostName());      out.println("HELO " + localhost.getHostName());      String welcome = in.readLine();      System.out.println(welcome);      System.out.println("MAIL From:<" + from + ">");

Page 36: Unix Networking Programming

35

      out.println("MAIL From:<" + from + ">");      String senderOK = in.readLine();      System.out.println(senderOK);      System.out.println("RCPT TO:<" + to + ">");      out.println("RCPT TO:<" + to + ">");      String recipientOK = in.readLine();      System.out.println(recipientOK);      System.out.println("DATA");      out.println("DATA");      String line;      while ((line = msg.readLine()) != null) {        out.println(line);      }      System.out.println(".");      out.println(".");      String acceptedOK = in.readLine();      System.out.println(acceptedOK);      System.out.println("QUIT");      out.println("QUIT");      return true;    }  }}

Page 37: Unix Networking Programming

36

7. Network Simulator 2About Simulator and NS-2

Fundamentally, there are various techniques available to analyze the behavior of wired and wireless networks, primarily these techniques are Analytical Modeling, Real Time Physical Measurements and Computer Simulations etc..

A. Analytical Modeling: Analytical models are mathematical models that have a closed form solution, i.e. the solution to the equations used to describe changes in a system can be expressed as a mathematical analytic function. Mathematical models can help students understand and explore the meaning of equations or functional relationships. After developing a conceptual model of a physical system it is natural to develop a mathematical model that will allow one to estimate the quantitative behavior of the system. It is very tedious. Statistical Models: Statistical models can be used to characterize numerical output from mathematical models to help understand the model behavior and to assess the model's ability to simulate important features of the natural system (model validation). Feeding this information back into the model development process will enhance model performance. Statiscal model is used to estimate probabilistic future behavior of a system based on past statistical information, a statistical prediction model. The goal of developing an analytical model is to predict the performance of an application given a new machine specified by some hardware parameters.

B. Real Time Physical Measurements: Time is an essential part of the measuring system used to sequence events, to compare the durations of events and the intervals between them, and to quantify the motions of objects. It is the state of things as they actually exist, rather than as they may appear or may be thought to be. It may not be possible all the time.

C. Computer Simulations: Computer Simulations is a practical approach to the quantitative analysis of a network. Simulation is usually a software package that runs on a computer for the purpose of simulating some sort of system, in order to get a better idea how the system functions. During the last decade simulation has become a very powerful and an important tool for planning, designing and controlling complex system. Nowadays an error in real life costs a lot of money.

A network simulator is a software program that imitates the working of a computer network. In simulators, the computer network is typically modelled with devices, traffic etc and the performance is analysed. Typically, users can then customize the simulator to fulfill their specific analysis needs. Simulators typically come with support for the most popular protocols in use today.

Page 38: Unix Networking Programming

37

Network simulators serve a variety of needs. Compared to the cost and time involved in setting up an entire test bed containing multiple networked computers, routers and data links, network simulators are relatively fast and inexpensive. They allow researcher/engineers to test scenarios that might be particularly difficult or expensive to emulate using real hardware- for instance, simulating the effects of a sudden burst in traffic or a DoS attack on a network service.

NS-2 Network Simulator is very popular and its is freely available for academic research purpose, some other notable simulation software for wireless networks are (1) Global Mobile Network Simulator (GloMoSim) (2) OPNET (3) OMNET (4) NetSim etc.

NS-2 started as a variant of the REAL network simulator in 1989 and has since been supported by the Virtual InterNetwork Testbed (VINT) project that is a DARPA-funded research project whose aim is to build a network simulator. The first version of NS was for wired networks but the demand to support wireless networking made the Monarch Group to create new version NS-2.

NS-2 allows for the simulation of various protocols, applications, routing, queue types etc. A graphical front end has been developed for use with NS known as Network Animator (NAM). Alternatively trace files can be created for analysis, which can be displayed using Gnuplot, tracegraph orXgraph even Microsoft Excel can also be used for this purpose.

Network Simulator - 2 (NS-2) is an event driven, discrete object oriented and packet level simulator developed at UC Berkeley is used by networking researcher to simulate and analyze the performance of wired, wireless and satellite networks. NS-2 is an open source network simulator which is use to build different network prototype. Ns2 support simulation of different network protocols as TCP,UDP, traffic sources FTP, web, CBRand routing and multicast protocols over wired and wireless (802.11 for wireless) networks.

The core engine is used C++ code and OTcl for configuration and simulation the scripts in NS-2.

NS-2 Background and Overview

A. Node Type: Node uses to symbolize a host or a router in NS2. Anodes function in NS2 is to send or receive data packets. An NS2 simulation scenario ismade up of a collection of nodes and between these nodes you have a set of links. Node can have Unicastor Multicasttraffic. In Unicast– If, a node is sending data only one destination then it’s a unicast node. Normally all the nodes are unicast in ns. These made of an address and a port classifier. These classifiers circulate the incoming data to specific agent or outer link, whereas In Multicast–multicast nodes is used for multicast simulations (one node is sending data to many destinations). It must be specified as multicast when it declares and it has a switch for get the incoming data. A multicast node, in addition, has a classifier thatclassify multicast packets from unicast packets and a multicast classifier that

Page 39: Unix Networking Programming

38

performs multicast routing. To create Multicast nodes the user must notify in the input OTcl script. The following table shows the node types that are used in NS.

B. Network Protocols: A protocol is a set of rules use to talk to each other. Network protocol is a group of technologies' rules to communication to each computer or device. NS-2 supports almost all different versions of TCP, multicast, wired networking, routing and wireless protocols. The following table shows the some examples of protocols. Protocols Description Internet Protocol (IP) It is a transmission mechanism used by the TCP/IP. This is a unreliable, connectionless and a data-oriented protocol that communicates data across a network which is used by both source and host. It comes in two versions IPV4 and IPV6.

Page 40: Unix Networking Programming

39

Page 41: Unix Networking Programming

40

C. Constant Bit Rate (CBR) data transfer: CBR is a bandwidth-allocation service that requiresthe user to determine the bandwidth at the time the connection is set up. CBR reservesa constant amount of bandwidth at the time of connection set up so that the data can be sent in a steady stream. This form of data transfer is often used when transmitting uncompressed voice and video which require jitter (small time variations) over a network as it keeps the video streaming at a constant rate. The source may send at a negotiated or lower rate at any time and for any duration. The connection in Ns would normally be set up with a UDP agent and the traffic source would be CBR.

Page 42: Unix Networking Programming

41

D. Traffic Generator Function: Traffic Generator is a tool for generating artificial traffic for a network simulation. It use for measurement and testing the network. A traffic generator function has two parts; the source is the agent which is the originator of the packets sent down the network. The packets are sent along the network and end up in the sink which has a Null agent attached; the sink is the destination for the packets. Currently, there are four C++ classes built into NS-2 which provide traffic generator functions are all derived from the base class TrafficGenerator. These traffic generator functions are shown in following table.

NS2 Programming

Here we are providing a 'providing a 'providing a 'providing a 'template' that we can use it for all tcl scripts. We will introduce basics of how to create event scheduler, create a simple pair of nodes and make communication between the two nodes. Then we will introduce a standard template for all tcl scripts with simple examples.

In this page we are going to introduce the concepts of:

Part of introduction to TCP/IP model Where can you write scripts? Basic ns2 programming steps Template Golden rules Simple examples

CBR over UDP CBR over TCP FTP over TCP

Page 43: Unix Networking Programming

42

Part of Introduction to TCP/IP model

Application Layer : CBR,FTP,telnet..

Transport layer : TCP,UDP

Network layer : rtproto

Data link Layer: Transmission mode, Simplex mode, Duplex mode

Physical layer

TCP/IP model

Application Layer: Applications agents are Telnet, FTP, Rlogin, CBR

Transport Layer: The transport uses two protocols, UDP and TCP. UDP which stands for User Datagram Protocol does not guarantee packet delivery and applications which use this must provide their own means of verifying delivery. TCP does guarantee delivery of packets to the applications which use it.

Network Layer: The network layer is concerned with packet routing and used low level protocols such as ICMP, IP, and IGMP. Here Network protocols are omitted for simple examples

Link Layer: The link layer is concerned with the actual transmittal of packets as well as IP to Ethernet address translation. Data transfer in two modes i.e. simplex mode and in duplex mode.

All the links are created at data link layer. Network layer next is to data link layer.

Where can you write Scripts?;

After login into terminal, follow step given below

1) vi filename.tcl

It will open page, there you can write tcl scripts.

2) save file

Press esc-> colon (shift + semicolon) ->wq (save and quit)

It save the file

3) To run tcl script

ns filename.tcl

Page 44: Unix Networking Programming

43

Basically NS 2 programming contains the following steps.

1) Create the event scheduler2) Turn on tracing3) Creating network

a. Computing setup routing - rtprotob. Creating transport connection-Agentsc. Creating traffic-Applications

4) Monitoringa. Visualization using nam

Note: every tcl script must write in small letters only except protocol agents i.e. TCP, FTP

Template

Every ns2 script starts with creating simulator object set ns [new Simulator]

How to create node

Creation of Nodes

set n0 [$ns node]

set n1 [$ns node]

Creating link

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

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

How to use Trace?

We use simulator to see results. How is it achieved? Using trace

Page 45: Unix Networking Programming

44

Two types of trace

1) generic trace

for use with xgraph, and other things

2) nam trace

for use with visualization

# open trace file

set tracefile [open out.tr w]

$ns trace-all $tracefile

#Open the nam trace file

set nf [open out.nam w]

$ns namtrace-all $nf

Since we have started tracing, we should end also. For this we use finish procedure.

#Define a 'finish' procedure

proc finish {}

{

global ns tracefile nf

$ns flush-trace

close $nf

close $tracefile # close tracefile

exec nam out.nam & #Execute nam on the trace file

exit 0

}

Finish procedure is forced to be called at the end with the line

$ns at 5.0 “finish”

Page 46: Unix Networking Programming

45

Every tcl script must contain following statement

$ns run

Golden rules

Follow the template tcl like Bible.

All communication between 2 agents.

Upper layer to lower layer, we attach agents.

Same layer in two nodes, we connect agents.

Agents are tcp, udp, telnet, cbr…etc

UDP communication

In UDP communication, data is flows from UDP agent to Null agent.

#Create a UDP agent and attach it to node n0

set udp0 [new Agent/UDP]

$ns attach-agent $n0 $udp0

# create a null agent which act as traffic sink and attach it to node n1

set null0 [new Agent/Null]

$ns attach-agent $n1 $null0

# connect two agents with each other

$ns connect $udp0 $null0

TCP Communication

In TCP communication, data is flows from TCP agent to TCPsink agent.

Page 47: Unix Networking Programming

46

# create Tcp agent and attach it to node no

set tcp0 [new Agent/TCP]

$ns attach-agent $n0 $tcp0

# create a tcpsink agent which act as traffic sink and attach it to node n1

set tcpsink0 [new Agent/TCPSink]

$ns attach-agent $n1 $tcpsink0

# connect two agents with each other

$ns connect $tcp0 $tcpsink0

Traffic generator

For actual data to flow, we need traffic generators.They simulate some application traffic.

Simple example using CBR

# creating CBR agent

set cbr0 [new Application/Traffic/CBR]

# Attach the CBR agent to some udp/tcp agent

$cbr0 attach-agent $udp0

Scheduling the events

Here “at” place major role.

$ns at 1.0 “$cbr0 start”

$ns at 5.0 “finish"

cbr0 will start at a time of 1.0 ms and whole process will stops at 5.0ms.we can also stop each and traffic generator. for example

$ns at 4.0 ”$cbr0 stop”

Page 48: Unix Networking Programming

47

Traffic generator cbr0 will stops at 4.0

Simple Examples

So far we are not talking about data flow. Here we will explain with CBR protocol.

Page 49: Unix Networking Programming

48

Result

Before 1.0ms

After 1.0ms

Page 50: Unix Networking Programming

49

Example 2:(CBR over TCP)

Result:

Page 51: Unix Networking Programming

50

Before 1.0ms

After 1.0ms

Page 52: Unix Networking Programming

51

Example3:(FTP over TCP)

Result:

Here we are using FTP Application agent as a traffic generator instead of CBR. The difference is CBR traffic generator will produce constant bit rate where as FTP traffic generator produces maximum available bit rate.

We are writing code

set ftp0 [new Application/FTP]

$ftp0 attach-agent $tcp0

and Similarly for telnet also

set telneto [new Application/TELNET]

$ftp0 attach-agent $telnet0

Page 53: Unix Networking Programming

52

Instead of CBR

set cbr0 [new Application/Traffic/CBR]

$cbr0 attach-agent $tcp0

Before 1.0ms

After 1.0ms

Page 54: Unix Networking Programming