Showing posts with label networking. Show all posts
Showing posts with label networking. Show all posts

Monday, November 5, 2012

NS-2 Simulation

Installing NS2 on Ubuntu 11.04
sudo apt-get install ns2 nam
Here I have used NS-2 to simulate a network with the topology as shown below.


I have written tcl scripts to create the above topology and to show,
  1. When two TCP flows compete for the bandwidth they fairly share the bandwidth
  2. When a TCP flow and a UDP flow compete for the bandwidth there is no fair sharing
Also I have plotted the throughput at the receivers against time using xgraph.

Installing xgraph on Ubuntu 11.04
sudo apt-get install xgraph
To start the simulation
ns XXX.tcl
How two TCP flows compete for the bandwidth

tcp_tcp.tcl

This script simulates two TCP flows; one between n0 and n4 and one between n1 and n5. Also the bandwidth of L2 has selected in such a way that it becomes the bottleneck link and the "record" procedure has used to measure the throughput at the receivers. .
#Create a simulator object
set ns [new Simulator]

#Define different colors for data flows (for NAM)
$ns color 1 Blue
$ns color 2 Red

#Open the trace files outX.tr for Xgraph and out.nam for nam
set f0 [open out_tcp0.tr w]
set f1 [open out_tcp1.tr w]

#Open the NAM trace file
set nf [open out.nam w]
$ns namtrace-all $nf

#Define a 'finish' procedure
proc finish {} {
 global ns nf f0 f1
 $ns flush-trace
#Close the NAM trace file
 close $nf
#Close the output files
 close $f0
 close $f1
#Execute xgraph to display the results
 exec xgraph out_tcp0.tr out_tcp1.tr -geometry 600x400 &
#Execute NAM on the trace file
 exec nam out.nam &
 exit 0
}

#Create five nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]

#Create links between the nodes
$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns duplex-link $n2 $n3 1.7Mb 20ms DropTail
$ns duplex-link $n3 $n4 2Mb 10ms DropTail
$ns duplex-link $n3 $n5 2Mb 10ms DropTail

#Set Queue Size of link (n2-n3) to 20
$ns queue-limit $n2 $n3 20

#Give node position (for NAM)
$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n2 $n3 orient right
$ns duplex-link-op $n3 $n4 orient right-up
$ns duplex-link-op $n3 $n5 orient right-down

#record procedure
proc record {} {
 global sink sink1 f0 f1
#Get an instance of the simulator
 set ns [Simulator instance]

#Set the time after which the procedure should be called again
 set time 0.5

#How many bytes have been received by the traffic sinks?
 set bw0 [$sink set bytes_]
 set bw1 [$sink1 set bytes_]

#Get the current time
 set now [$ns now]

#Calculate the bandwidth (in MBit/s) and write it to the files
 puts $f0 "$now [expr $bw0/$time*8/1000000]"
 puts $f1 "$now [expr $bw1/$time*8/1000000]"

#Reset the bytes_ values on the traffic sinks
 $sink set bytes_ 0
 $sink1 set bytes_ 0

#Re-schedule the procedure
 $ns at [expr $now+$time] "record"
}

#Setup a TCP connection
set tcp [new Agent/TCP]
$tcp set class_ 2
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n4 $sink
$ns connect $tcp $sink
$tcp set fid_ 1

#Setup a FTP over TCP connection
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ftp set type_ FTP

#Setup a TCP connection
set tcp1 [new Agent/TCP]
$tcp1 set class_ 2
$ns attach-agent $n1 $tcp1
set sink1 [new Agent/TCPSink]
$ns attach-agent $n5 $sink1
$ns connect $tcp1 $sink1
$tcp1 set fid_ 2

#Setup a FTP over TCP connection
set ftp1 [new Application/FTP]
$ftp1 attach-agent $tcp1
$ftp1 set type_ FTP

#Start logging the received bandwidth
$ns at 0.0 "record"

#Schedule events for the FTP agents
$ns at 0.1 "$ftp start"
$ns at 0.8 "$ftp1 start"
$ns at 4.0 "$ftp1 stop"
$ns at 4.8 "$ftp stop"

#Call the finish procedure after 5 seconds of simulation time
$ns at 5.0 "finish"

#Run the simulation
$ns run

Graph


Above graph visualization clearly shows how two TCP flows fairly share the bandwidth.

How a TCP flow and a UDP flow compete for the bandwidth

tcp_udp.tcl

This script simulates one TCP flow (between n0 and n4) and one UDP flow (between n1 and n5). Again the bandwidth of L2 has selected in such a way that it becomes the bottleneck link and the "record" procedure has used to measure the throughput at the receivers.
#Create a simulator object
set ns [new Simulator]

#Define different colors for data flows (for NAM)
$ns color 1 Blue
$ns color 2 Red

#Open the trace files outX.tr for Xgraph and out.nam for nam
set f0 [open out_tcp.tr w]
set f1 [open out_udp.tr w]

#Open the NAM trace file
set nf [open out_udptcp.nam w]
$ns namtrace-all $nf

#Define a 'finish' procedure
proc finish {} {
 global ns nf f0 f1
 $ns flush-trace
#Close the NAM trace file
 close $nf
#Close the output files
 close $f0
 close $f1
#Execute xgraph to display the results
 exec xgraph out_tcp.tr out_udp.tr -geometry 600x400 &
#Execute NAM on the trace file
 exec nam out_udptcp.nam &
 exit 0
}

#Create five nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]

#Create links between the nodes
$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns duplex-link $n2 $n3 1.7Mb 20ms DropTail
$ns duplex-link $n3 $n4 2Mb 10ms DropTail
$ns duplex-link $n3 $n5 2Mb 10ms DropTail

#Set Queue Size of link (n2-n3) to 20
$ns queue-limit $n2 $n3 20

#Give node position (for NAM)
$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n2 $n3 orient right
$ns duplex-link-op $n3 $n4 orient right-up
$ns duplex-link-op $n3 $n5 orient right-down

#record procedure
proc record {} {
 global sink sink1 f0 f1
#Get an instance of the simulator
 set ns [Simulator instance]

#Set the time after which the procedure should be called again
 set time 0.5

#How many bytes have been received by the traffic sinks?
 set bw0 [$sink set bytes_]
 set bw1 [$sink1 set bytes_]

#Get the current time
 set now [$ns now]

#Calculate the bandwidth (in MBit/s) and write it to the files
 puts $f0 "$now [expr $bw0/$time*8/1000000]"
 puts $f1 "$now [expr $bw1/$time*8/1000000]"

#Reset the bytes_ values on the traffic sinks
 $sink set bytes_ 0
 $sink1 set bytes_ 0

#Re-schedule the procedure
 $ns at [expr $now+$time] "record"
}

#Setup a TCP connection
set tcp [new Agent/TCP]
$tcp set class_ 2
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n4 $sink
$ns connect $tcp $sink
$tcp set fid_ 1

#Setup a FTP over TCP connection
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ftp set type_ FTP

#Setup a UDP connection
set udp [new Agent/UDP]
$ns attach-agent $n1 $udp
set sink1 [new Agent/LossMonitor]
$ns attach-agent $n5 $sink1
$ns connect $udp $sink1
$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_ 2mb
$cbr set random_ false

#Start logging the received bandwidth
$ns at 0.0 "record"

#Schedule events for the CBR and FTP agents
$ns at 0.1 "$cbr start"
$ns at 0.8 "$ftp start"
$ns at 4.0 "$ftp stop"
$ns at 4.8 "$cbr stop"

#Call the finish procedure after 5 seconds of simulation time
$ns at 5.0 "finish"

#Run the simulation
$ns run
Graph


Above graph visualization clearly shows, when it comes to a TCP flow and a UDP flow there is no fair sharing the bandwidth, UDP gets the most of it.

Thursday, February 24, 2011

Internet Control Message Protocol (ICMP)

Why ICMP is important

IP protocol lacks error reporting mechanism and hosting/managing queries. To compensate ICMP protocol comes to the role as a companion to IP protocol giving following two services.

  • Provides error reporting mechanism
  • Hosts and manages queries

Did you have any doubt

ICMP is a network layer protocol as IP is, so one would suspect whether ICMP messages are passed directly to the data link layer. The answer is no. ICMP messages are first encapsulated inside ip datagram and then passed to the below data link layer. Following image clearly shows you how it happens.


Talking about ICMP messages

  • Error reporting messages
  • ICMP acts as error reporting protocol it does not correct errors, error corrections are done by the higher level protocols. ICMP always sends the error messages to original source. There are five types of error messages as listed below.
    • Destination unreachable
    • Source quench
    • Time exeeded
    • Parameter problem
    • Redirection
  • Query messages
  • ICMP can also diagnose network problems through query messages. There are two pairs of query messages used for this purpose today.
    • Echo request or reply
    • Timestamp request or reply

Debugging tools that uses ICMP

ping

ping program can be used to find out whether a host is alive and responding. The source host sends an ICMP echo request message, if the destination host is alive it responds with ICMP echo reply messages.



traceroute

traceroute progam in unix or tracert in windows can be used to trace the route of a packet from source to destination.


Tuesday, December 21, 2010

Network multicasting with C#

What is multicasting?

IP multicasting allows an application to send a single packet to a selected subset of devices. The IP multicasting scheme uses a particular range of IP addresses to designate different multicast groups. Each multicast group consists of a group of devices listening to the same IP address. As packets are sent out destined for the multicast group address, each device listening to the address receives them. The IP address range 224.0.0.1 through 239.255.255.255 represents multicast groups


In C# the Socket class supports IP multicasting by using the SetSocketOption() method of the socket.

MultiRecv program

The MultiRecv program creates a UDP socket in the normal way, using the standard Socket class methods. After being added to the multicast group, the socket blocks on a ReceiveFrom() method call, waiting for data to arrive


MultiRecv.cs

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class MultiRecv
{
  public static void Main()
  {
   Socket sock = new Socket(AddressFamily.InterNetwork,
                SocketType.Dgram, ProtocolType.Udp);
   Console.WriteLine("Ready to receive…");
   IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
   EndPoint ep = (EndPoint)iep;
   sock.Bind(iep);
   sock.SetSocketOption(SocketOptionLevel.IP,SocketOptionName.AddMembership,newMulticastOption(IPAddress.Parse("224.100.0.1")));
   byte[] data = new byte[1024];
   int recv = sock.ReceiveFrom(data, ref ep);
   string stringData = Encoding.ASCII.GetString(data, 0, recv);
   Console.WriteLine("received: {0} from: {1}", stringData, ep.ToString());
   sock.Close();
  }
}


MultiSend program

MultiSend.cs program is created to send multicast packets across network boundaries. when the multicast packet is sent out, it has a TTL(Time To Live) value of 50, allowing it to traverse up to 50 hops before it is terminated. You can use the MultiRecv program to watch the multicast packet go out on the network.


MultiSend.cs

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class NewMultiSend
{
  public static void Main()
  {
   Socket server = new Socket(AddressFamily.InterNetwork,
                 SocketType.Dgram, ProtocolType.Udp);
   IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9051);
   IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("224.100.0.1"), 9050);
   server.Bind(iep);
   
   byte[] data = Encoding.ASCII.GetBytes("This is a test message");
   server.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership,
               new MulticastOption(IPAddress.Parse("224.100.0.1")));
   server.SetSocketOption(SocketOptionLevel.IP,
   SocketOptionName.MulticastTimeToLive, 50);
   server.SendTo(data, iep2);
   server.Close();
  }
}

Thursday, December 16, 2010

Network Broadcasting with C# further

This post is related to the previously written post Network Broadcasting with C#.

Consider the Broadcst.cs and RecvBroadcst.cs programs which were provided in Network Broadcasting with C#. In this post those two programs have slightly modified to achieve a special target described in the next paragraph.

Suppose a peer to peer environment. When a peer connected with the network it continually listens to one specific port and as well sends a broadcasting message in every 5 seconds to the same specific port to inform it is connected. That broadcasting message will be listened through the modified RecvBroadcst.cs program and it will also store the ip of the sender in an Arraylist.Broadcast message is sent through modified Broadcst.cs program. Program.cs is used to run the two threads.


RecvBroadcst.cs

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Collections;

class RecvBroadcst
{
    public void init()
    {

        while (true)
        {
            Socket sock = new Socket(AddressFamily.InterNetwork,
                    SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
            sock.Bind(iep);
            EndPoint ep = (EndPoint)iep;
            Console.WriteLine("Ready to receive…");
            byte[] data = new byte[1024];
            int recv = sock.ReceiveFrom(data, ref ep);
            string stringData = Encoding.ASCII.GetString(data, 0, recv);
            Console.WriteLine("received: {0} from: {1}", stringData, ep.ToString());

            string ip = ep.ToString();

            string[] array = ip.Split(':');

            ArrayList list = new ArrayList();

            Console.WriteLine("sender ip {0} is added to the table!", array[0]);

            list.Add(array[0]);

            sock.Close();

        }
    }
}

Broadcst.cs

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

class Broadcst
{
    public void init()
    {

        while (true)
        {
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
                         ProtocolType.Udp);
            IPEndPoint iep1 = new IPEndPoint(IPAddress.Broadcast, 9050);
            string hostname = Dns.GetHostName();
            byte[] data = Encoding.ASCII.GetBytes(hostname);
            sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
            sock.SendTo(data, iep1);
                       
            sock.Close();
            Thread.Sleep(5000);
            
        }
    }
}



Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Threading;


    public class Program
    {
        static void Main(string[] args)
        {
           
            Thread RecvBraodcast = new Thread(new RecvBroadcst().init);
            Thread Broadcst = new Thread(new Broadcst().init);

            RecvBraodcast.Start();
            Broadcst.Start();
      
            

        }
    }

           

           


Run these codes in visual studio.

output

Tuesday, December 14, 2010

Network Broadcasting with C#

What Is Broadcasting?

IP broadcasting is used by network devices to send a single packet of information that can be accessible by every device on the network. Because TCP communication requires that two devices have a dedicated connection, it is not possible to send broadcast messages in a strictly TCP environment. Instead, UDP packets must be used because that protocol has the capability of sending messages without a specific connection being defined.

Broadcst.cs

The Broadcst program creates two separate IPEndPoint objects, one using the IPAddress.Broadcast address and one using a local broadcast address 192.168.1.255. Next, the local hostname of the device is determined using the standard Dns GetHostName() method, and it is sent out in two separate broadcast messages.

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class Broadcst
{
  public static void Main()
  {
   Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
                ProtocolType.Udp);
   IPEndPoint iep1 = new IPEndPoint(IPAddress.Broadcast, 9050);
   IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("192.168.1.255"), 9050);
   string hostname = Dns.GetHostName();
   byte[] data = Encoding.ASCII.GetBytes(hostname);
   sock.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.Broadcast, 1);
   sock.SendTo(data, iep1);
   sock.SendTo(data, iep2);
   sock.Close();
  }
}


RecvBroadcst.cs

The RecvBroadcst program is a simple UDP program that creates a socket and binds it to all network interfaces on the device, using port 9050, the same port that the Broadcst program uses to send its broadcast messages. After binding the socket to the UDP port, the program attempts to receive two messages sent to the port and displays the message and the sending host address information.

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class RecvBroadcst
{
  public static void Main()
  {
   Socket sock = new Socket(AddressFamily.InterNetwork,
           SocketType.Dgram, ProtocolType.Udp);
   IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
   sock.Bind(iep);
   EndPoint ep = (EndPoint)iep;
   Console.WriteLine("Ready to receive…");
   byte[] data = new byte[1024];
   int recv = sock.ReceiveFrom(data, ref ep);
   string stringData = Encoding.ASCII.GetString(data, 0, recv);
   Console.WriteLine("received: {0} from: {1}",stringData, ep.ToString());
   data = new byte[1024];
   recv = sock.ReceiveFrom(data, ref ep);
   stringData = Encoding.ASCII.GetString(data, 0, recv);
   Console.WriteLine("received: {0} from: {1}",stringData, ep.ToString());
   sock.Close();
  }
}


For compilation either can use visual studio or visual studio command prompt. Here have used visual studio command prompt. Open up two Visual Studio Command prompts, one for the RecvBroadcst.cs and other one for the Broadcst.cs

Compile and run:

Broadcst

csc Broadcst.cs
Broadcst.exe

RecvBroadcst

csc RecvBroadcst.cs
RecvBroadcst.exe

output

Saturday, November 27, 2010

Sockets

Sockets

  • Socket is one end of a two way communication link between two programs running on a network.
  • Data can be passed between different processes by connecting the two sockets together

Basic socket types

  • Stream Socket
    • Connection oriented sockets
    • Consists of a stream of bytes that can be bi-directional
    • Usage of stream sockets is a more reliable method than the usage of datagram sockets
  • Datagram sockets
    • AKA Connectionless sockets, no explicit connection is established
    • A message is sent to a specified socket and can be received appropriately from the specified socket
    • Usage of datagram sockets is reducing the overhead incurred by establishing an explicit connection

Row sockets

  • Generalized form of sockets called row sockets
  • Packet is passed directly to the application that needs it bypassing the mechanism by which the computer handles TCP/IP

Ports

  • Defined to solve the problem of communicating with multiple operations simultaneously

Sockets composed of
  • IP address of the machine
  • Port no used by TCP application

Socket numbers are unique across the entire internet as IP address is unique across the internet and the port no is unique on the individual machine. This enables process to communicate with another process across network based entirely on socket number.

Client Server applications uses sockets

  • Server waits for the connection from the client
  • Client initiates the connection with the server
  • Server should be already running before client tries to connect
  • Client must know the target address and the port no, tries to establish a connection with the server
  • Server accepts the connection
  • Server application creates a new socket to deal specifically with the connected client
  • Server and client communicate by reading from and writing to their respective sockets

Tuesday, November 23, 2010

IP Header


• Version (Specifies the format of the IP packet header): 4 bits.

• IHL, Internet Header Length (Specifies the length of the IP packet header in 32 bit words. The minimum value for a valid header is 5): 4 bits.

• Differentiated Services (This field is defined in RFC 2474 and obsoletes the TOS field): 8 bits.

• Total length (Contains the length of the datagram). 16 bits.

• Identification (Used to identify the fragments of one datagram from those of another. The originating protocol module of an internet datagram sets the identification field to a value that must be unique for that source-destination pair and protocol for the time the datagram will be active in the internet system. The originating protocol module of a complete datagram clears the MF bit to zero and the Fragment Offset field to zero): 16 bits.

• Flags: 3 bits.

• Fragment Offset (Used to direct the reassembly of a fragmented datagram): 13 bits.

• TTL, Time to Live (A timer field used to track the lifetime of the datagram. When the TTL field is decremented down to zero, the datagram is discarded): 8 bits.

• Protocol (This field specifies the next encapsulated protocol): 8 bits.

• Header checksum (A 16 bit one's complement checksum of the IP header and IP options): 16 bits.

• Source IP address (IP address of the sender): 32 bits.

• Destination IP address (IP address of the intended receiver): 32 bits.

ARP

ARP (address resolution protocol) is used to translate protocol addresses to hardware interface addresses(mac).

ARP Header





• Hardware type: 16 bits.

• Protocol type: 16 bits.

• Hardware address length (Length of the hardware address in bytes.): 8 bits.

• Protocol address length (Length of the protocol address in bytes.): 8 bits.

• Opcode: 16 bits.

• Source hardware address: Variable length.

• Source protocol (mac) address: Variable length.

• Destination hardware (mac) address.: Variable length.

• Destination protocol address: Variable length.