Sie sind auf Seite 1von 60

TCP peer to peer

import java.net.*;
import java.io.*;

public class Server2


{ public static void main(String args[])throws Exception
{
System.out.println("IN server!");
ServerSocket ss=new ServerSocket(4777); //port no same as client
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
//converts bytes to any type
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop"))
{
str=din.readUTF();
System.out.println("Client says: "+str);
System.out.println("Server::Enter reply to client : ");
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
br.close();
dout.close();
din.close();
s.close();
ss.close();

import java.net.*;
import java.io.*;

class Client2
{
public static void main(String args[])throws Exception
{
System.out.println("IN client!");
Socket s=new Socket("192.168.0.13",4777); //local host address

DataInputStream din=new DataInputStream(s.getInputStream());


DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop"))
{
System.out.println("Client::Enter message for server : ");
str=br.readLine();

dout.writeUTF(str);

dout.flush();

str2=din.readUTF();
System.out.println("Server says: "+str2);
}
dout.close();
din.close();
s.close();
}
}
TCP MULTIUSER

// echo server
import java.io.*;
import java.net.*;

public class NetServer


{
public static void main(String args[]) throws IOException
{
ServerSocket ss2=new ServerSocket(4445);
System.out.println("Server Listening......");
while(true)
{ Socket s= ss2.accept();
System.out.println("connection Established");
ServerThread st=new ServerThread(s);
st.start();
}
}
}

class ServerThread extends Thread


{
String line=null;
BufferedReader br = null;
DataOutputStream dos=null;
DataInputStream dis=null;
Socket s=null;

public ServerThread(Socket s)
{
this.s=s; //invoke or initiate current class constructor
}

public void run()


{
try{
br= new BufferedReader(new InputStreamReader(System.in));
dos=new DataOutputStream(s.getOutputStream());
dis=new DataInputStream(s.getInputStream());

line="";
while(!line.equals("stop"))
{
line=dis.readUTF();
System.out.println("client says: "+line);
dos.flush();
}
}
catch(IOException ie)
{
System.out.println("Socket Close Error");
}
finally
{ try{
br.close();
dos.close();
dis.close();
s.close();
}
catch(IOException ie)
{
System.out.println("Socket Close Error");
}
} //finally
} //run()
} //class

-------------------------------------------------------------------------------------------------
// A simple Client Server Protocol .. Client for Echo Server
import java.io.*;
import java.net.*;

public class NetClient {

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


{
InetAddress address=InetAddress.getLocalHost(); //this class represents an IP address
using the methods getLocalHost,getByName,or getAllByName to create a new
InetAddress instance
Socket s1=null;
String line=null;
BufferedReader br=null;
BufferedReader br1=null;
DataOutputStream dos=null;
s1=new Socket("localhost", 4445);
br= new BufferedReader(new InputStreamReader(System.in));
br1=new BufferedReader(new InputStreamReader(s1.getInputStream()));
dos= new DataOutputStream(s1.getOutputStream());
System.out.println("Client Address : "+address);
System.out.println("Enter Data to echo Server ( Enter stop to end ):");
String response="";
try{ line=br.readLine();
while(!line.equals("stop"))
{
dos.writeUTF(line);
dos.flush();
System.out.println("Enter Data to echo Server (Enter stop to end):");
line=br.readLine();
}
}

catch(IOException ie){
System.out.println("Socket Close Error"); }
finally{ try{
br1.close();
dos.close();
br.close();
s1.close();
System.out.println("Connection Closed");
}
catch(IOException ie)
{
System.out.println("Socket Close Error"); }
}
}
DNS Lookup

//Print out DNS Record for an Internet Address


import javax.naming.directory.Attributes;
import javax.naming.directory.InitialDirContext;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class DNSLookup


{
public static void main(String args[])
{
// explain what program does and how to use it
if (args.length != 1)
{
System.err.println("Print out DNS Record for an Internet
Address");
System.err.println("USAGE: java DNSLookup
domainName|domainAddress");
System.exit(-1);
}
try
{
InetAddress inetAddress;
// if first character is a digit then assume is an address
if (Character.isDigit(args[0].charAt(0)))
{ // convert address from string representation to byte
array
byte[] b = new byte[4];
String[] bytes = args[0].split("[.]");
for (int i = 0; i < bytes.length; i++)
{
b[i] = new Integer(bytes[i]).byteValue();
}
// get Internet Address of this host address
inetAddress = InetAddress.getByAddress(b);
}
else
{ // get Internet Address of this host name
inetAddress = InetAddress.getByName(args[0]);
}
// show the Internet Address as name/address
System.out.println(inetAddress.getHostName() + "/" +
inetAddress.getHostAddress());
// get the default initial Directory Context
InitialDirContext iDirC = new InitialDirContext();
// get the DNS records for inetAddress
Attributes attributes = iDirC.getAttributes("dns:/" +
inetAddress.getHostName());
// get an enumeration of the attributes and print them out
NamingEnumeration attributeEnumeration =
attributes.getAll();
System.out.println("-- DNS INFORMATION --");
while (attributeEnumeration.hasMore())
{
System.out.println("" + attributeEnumeration.next());
}
attributeEnumeration.close();
}
catch (UnknownHostException exception)
{
System.err.println("ERROR: No Internet Address for '" +
args[0] + "'");
}
catch (NamingException exception)
{
System.err.println("ERROR: No DNS record for '" + args[0] +
"'");
}
}
}
TCP client and Server

import java.io.*;
import java.net.*;
import java.util.*;
public class TCPclient
{
public static void main(String args[]) throws Exception
{
Socket s = new Socket("localhost",1030);
DataInputStream din = new DataInputStream(s.getInputStream());
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
Scanner in=new Scanner(System.in);
System.out.print("Enter your name : ");
String name=in.nextLine();
dout.writeUTF(name);
System.out.println("Server : "+din.readUTF());
String str1="",str2="";

while(!str1.equalsIgnoreCase("Bye"))
{
str1 = in.nextLine();
dout.writeUTF(str1);
str2 = din.readUTF();
System.out.println("Server : "+str2);
}
dout.close();
s.close();
}
}

import java.io.*;
import java.net.*;
import java.util.*;
public class TCPserver
{
public static void main(String args[])
{
try
{
ServerSocket ss = new ServerSocket(1030);
Socket s[]=new Socket[100];
for(int i=0;i<100;i++)
{
s[i]=ss.accept();
Thread t=new Multiple(s[i]);
t.start();
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

class Multiple extends Thread


{
private Socket s;
public Multiple(Socket i)
{
s=i;
}
public void run()
{
try
{
DataInputStream din = new
DataInputStream(s.getInputStream());
DataOutputStream dout = new
DataOutputStream(s.getOutputStream());
Scanner in=new Scanner(System.in);
String name=din.readUTF();
dout.writeUTF("hello "+name);
String str1="",str2="";

while(!str2.equalsIgnoreCase("Bye"))
{
str2 = din.readUTF();
System.out.println(name+" : "+str2);
str1 = in.nextLine();
dout.writeUTF(str1);
}
dout.close();
s.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Subnetting

import java.util.*;
//204.17.5.0
public class subnet{
static int cnt=0;
static String append(String s){
int len=s.length();
for(int i=0;i<8-len;i++){

s='0'+s;

}
return s;

static int getNumber(int n){


double i=1;
double o=2;
int number;

while (true){
double ii=Math.pow(o,i);
cnt++;
i++;
if((int)ii>n){
number=(int)ii;
break;
}
}

return number;
}

public static void main(String[]args){


System.out.println("Enter the IP address :");
Scanner sc= new Scanner(System.in);
String ip= sc.next();

String [] bip= new String[4];


int [] intBIp= new int[4];
bip=ip.split("\\.");
for(int i=0;i<4;i++){
intBIp[i]=Integer.parseInt((bip[i]));
System.out.println(intBIp[i]);

}
String [] binaryIp= new String[4];
for(int i=0;i<4;i++){
binaryIp[i]=Integer.toBinaryString(intBIp[i]);
System.out.println(binaryIp[i]);
binaryIp[i]=append(binaryIp[i]);
System.out.println(binaryIp[i]);

}
System.out.println("Enter the number of subnets :");
int numberOfSubnets=sc.nextInt();
int num=(getNumber(numberOfSubnets));
System.out.println(8-cnt);

int jj=8-cnt;
double a=2;
double b=(double)(jj);
double ii=Math.pow(a,b);
int m=((int)ii);

for(int k=0;k<num;k++){
int [] aa=new int[8];
for(int i=0;i<4;i++){
//intBIp[i]=Integer.parseInt((bip[i]));
//System.out.println(intBIp[i]);

}
System.out.println(
intBIp[0]+"."+intBIp[1]+"."+intBIp[2]+"."+intBIp[3]);
intBIp[3]=intBIp[3]+m;

System.out.println(
intBIp[0]+"."+intBIp[1]+"."+intBIp[2]+"."+intBIp[3]);
System.out.println();
}}}
Assignment 10
#include<netinet/in.h>
#include<errno.h>
#include<netdb.h>
#include<stdio.h> //For standard things
#include<stdlib.h> //malloc
#include<string.h> //strlen
#include<netinet/udp.h> //Provides declarations for udp header
#include<netinet/tcp.h> //Provides declarations for tcp header
#include<netinet/ip.h> //Provides declarations for ip header
#include<netinet/if_ether.h> //For ETH_P_ALL
#include<net/ethernet.h> //For ether_header
#include<sys/socket.h>
#include<arpa/inet.h>
#include<sys/ioctl.h>
#include<sys/time.h>
#include<sys/types.h>
#include<unistd.h>

void ProcessPacket(unsigned char* , int);


void print_ip_header(unsigned char* , int);
void print_tcp_packet(unsigned char * , int );
void print_udp_packet(unsigned char * , int );

FILE *logfile;
struct sockaddr_in source,dest;
int tcp=0,udp=0,icmp=0,others=0,igmp=0,total=0,i,j;

int main()
{
int saddr_size , data_size;
struct sockaddr saddr;

unsigned char *buffer = (unsigned char *) malloc(65536);

logfile=fopen("log.txt","w");
if(logfile==NULL)
{
printf("Unable to create log.txt file.");
}
printf("Starting...\n");
int sock_raw = socket( AF_PACKET , SOCK_RAW , htons(ETH_P_ALL)) ;
;

if(sock_raw < 0)
{
//Print the error with proper message
perror("Socket Error");
return 1;
}
while(1)
{
saddr_size = sizeof saddr;
//Receive a packet
data_size = recvfrom(sock_raw , buffer , 65536 , 0 , &saddr ,
(socklen_t*)&saddr_size);
if(data_size <0 )
{
printf("Recvfrom error , failed to get packets\n");
return 1;
}
//Now process the packet
ProcessPacket(buffer , data_size);
}
close(sock_raw);
printf("Finished");
return 0;
}

void ProcessPacket(unsigned char* buffer, int size)


{
//Get the IP Header part of this packet , excluding the ethernet header
struct iphdr *iph = (struct iphdr*)(buffer + sizeof(struct ethhdr));
++total;
switch (iph->protocol) //Check the Protocol and do accordingly...
{
case 1: //ICMP Protocol
++icmp;
// print_icmp_packet( buffer , size);
break;

case 2: //IGMP Protocol


++igmp;
break;
case 6: //TCP Protocol
++tcp;
print_tcp_packet(buffer , size);
break;

case 17: //UDP Protocol


++udp;
print_udp_packet(buffer , size);
break;

default: //Some Other Protocol like ARP etc.


++others;
break;
}
printf("TCP : %d UDP : %d ICMP : %d IGMP : %d Others : %d
Total : %d\r", tcp , udp , icmp , igmp , others , total);
}

void print_ethernet_header(unsigned char* Buffer, int Size)


{
struct ethhdr *eth = (struct ethhdr *)Buffer;

fprintf(logfile , "\n");
fprintf(logfile , "Ethernet Header\n");

fprintf(logfile , " |-Destination Address : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X \n",


eth->h_dest[0] , eth->h_dest[1] , eth->h_dest[2] , eth->h_dest[3] , eth->h_dest[4] ,
eth->h_dest[5] );

fprintf(logfile , " |-Source Address : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X


\n", eth->h_source[0] , eth->h_source[1] , eth->h_source[2] , eth->h_source[3] ,
eth->h_source[4] , eth->h_source[5] );

fprintf(logfile , " |-Protocol : %u \n",(unsigned short)eth->h_proto);


}

void print_ip_header(unsigned char* Buffer, int Size)


{
print_ethernet_header(Buffer , Size);

unsigned short iphdrlen;


struct iphdr *iph = (struct iphdr *)(Buffer + sizeof(struct ethhdr) );
iphdrlen =iph->ihl*4;

memset(&source, 0, sizeof(source));
source.sin_addr.s_addr = iph->saddr;

memset(&dest, 0, sizeof(dest));
dest.sin_addr.s_addr = iph->daddr;

fprintf(logfile , "\n");
fprintf(logfile , "IP Header\n");
fprintf(logfile , " |-IP Version : %d\n",(unsigned int)iph->version);
fprintf(logfile , " |-IP Header Length : %d DWORDS or %d Bytes\n",(unsigned
int)iph->ihl,((unsigned int)(iph->ihl))*4);
fprintf(logfile , " |-Type Of Service : %d\n",(unsigned int)iph->tos);
fprintf(logfile , " |-IP Total Length : %d Bytes(Size of
Packet)\n",ntohs(iph->tot_len));
fprintf(logfile , " |-Identification : %d\n",ntohs(iph->id));
//fprintf(logfile , " |-Reserved ZERO Field : %d\n",(unsigned
int)iphdr->ip_reserved_zero);
//fprintf(logfile , " |-Dont Fragment Field : %d\n",(unsigned
int)iphdr->ip_dont_fragment);
//fprintf(logfile , " |-More Fragment Field : %d\n",(unsigned
int)iphdr->ip_more_fragment);
fprintf(logfile , " |-TTL : %d\n",(unsigned int)iph->ttl);
fprintf(logfile , " |-Protocol : %d\n",(unsigned int)iph->protocol);
fprintf(logfile , " |-Checksum : %d\n",ntohs(iph->check));
fprintf(logfile , " |-Source IP : %s\n",inet_ntoa(source.sin_addr));
fprintf(logfile , " |-Destination IP : %s\n",inet_ntoa(dest.sin_addr));
}

void print_tcp_packet(unsigned char* Buffer, int Size)


{
unsigned short iphdrlen;

struct iphdr *iph = (struct iphdr *)( Buffer + sizeof(struct ethhdr) );


iphdrlen = iph->ihl*4;

struct tcphdr *tcph=(struct tcphdr*)(Buffer + iphdrlen + sizeof(struct ethhdr));

int header_size = sizeof(struct ethhdr) + iphdrlen + tcph->doff*4;


fprintf(logfile , "\n\n***********************TCP
Packet*************************\n");

print_ip_header(Buffer,Size);

fprintf(logfile , "\n");
fprintf(logfile , "TCP Header\n");
fprintf(logfile , " |-Source Port : %u\n",ntohs(tcph->source));
fprintf(logfile , " |-Destination Port : %u\n",ntohs(tcph->dest));
fprintf(logfile , " |-Sequence Number : %u\n",ntohl(tcph->seq));
fprintf(logfile , " |-Acknowledge Number : %u\n",ntohl(tcph->ack_seq));
fprintf(logfile , " |-Header Length : %d DWORDS or %d
BYTES\n" ,(unsigned int)tcph->doff,(unsigned int)tcph->doff*4);
//fprintf(logfile , " |-CWR Flag : %d\n",(unsigned int)tcph->cwr);
//fprintf(logfile , " |-ECN Flag : %d\n",(unsigned int)tcph->ece);
fprintf(logfile , " |-Urgent Flag : %d\n",(unsigned int)tcph->urg);
fprintf(logfile , " |-Acknowledgement Flag : %d\n",(unsigned int)tcph->ack);
fprintf(logfile , " |-Push Flag : %d\n",(unsigned int)tcph->psh);
fprintf(logfile , " |-Reset Flag : %d\n",(unsigned int)tcph->rst);
fprintf(logfile , " |-Synchronise Flag : %d\n",(unsigned int)tcph->syn);
fprintf(logfile , " |-Finish Flag : %d\n",(unsigned int)tcph->fin);
fprintf(logfile , " |-Window : %d\n",ntohs(tcph->window));
fprintf(logfile , " |-Checksum : %d\n",ntohs(tcph->check));
fprintf(logfile , " |-Urgent Pointer : %d\n",tcph->urg_ptr);
fprintf(logfile , "\n");

// fprintf(logfile , "IP Header\n");


// fprintf(logfile , "TCP Header\n");
fprintf(logfile ,
"\n###########################################################");
}

void print_udp_packet(unsigned char *Buffer , int Size)


{

unsigned short iphdrlen;

struct iphdr *iph = (struct iphdr *)(Buffer + sizeof(struct ethhdr));


iphdrlen = iph->ihl*4;

struct udphdr *udph = (struct udphdr*)(Buffer + iphdrlen + sizeof(struct ethhdr));

int header_size = sizeof(struct ethhdr) + iphdrlen + sizeof udph;


fprintf(logfile , "\n\n***********************UDP
Packet*************************\n");

print_ip_header(Buffer,Size);

fprintf(logfile , "\nUDP Header\n");


fprintf(logfile , " |-Source Port : %d\n" , ntohs(udph->source));
fprintf(logfile , " |-Destination Port : %d\n" , ntohs(udph->dest));
fprintf(logfile , " |-UDP Length : %d\n" , ntohs(udph->len));
fprintf(logfile , " |-UDP Checksum : %d\n" , ntohs(udph->check));

fprintf(logfile , "\n");
//fprintf(logfile , "IP Header\n");

//fprintf(logfile , "UDP Header\n");

fprintf(logfile ,
"\n###########################################################");
}

//LOG.TXT FILE

***********************UDP Packet*************************

Ethernet Header
|-Destination Address : 80-2B-F9-4B-D6-3F
|-Source Address : 54-A6-5C-06-F6-40
|-Protocol :8

IP Header
|-IP Version :4
|-IP Header Length : 5 DWORDS or 20 Bytes
|-Type Of Service : 0
|-IP Total Length : 68 Bytes(Size of Packet)
|-Identification :0
|-TTL : 43
|-Protocol : 17
|-Checksum : 11194
|-Source IP : 74.125.24.189
|-Destination IP : 192.168.0.13

UDP Header
|-Source Port : 443
|-Destination Port : 41567
|-UDP Length : 48
|-UDP Checksum : 5570

###########################################################

***********************TCP Packet*************************

Ethernet Header
|-Destination Address : 80-2B-F9-4B-D6-3F
|-Source Address : 54-A6-5C-06-F6-40
|-Protocol :8

IP Header
|-IP Version :4
|-IP Header Length : 5 DWORDS or 20 Bytes
|-Type Of Service : 0
|-IP Total Length : 83 Bytes(Size of Packet)
|-Identification : 59098
|-TTL : 221
|-Protocol : 6
|-Checksum : 20405
|-Source IP : 52.22.114.73
|-Destination IP : 192.168.0.13

TCP Header
|-Source Port : 443
|-Destination Port : 54742
|-Sequence Number : 2268988278
|-Acknowledge Number : 455580952
|-Header Length : 8 DWORDS or 32 BYTES
|-Urgent Flag :0
|-Acknowledgement Flag : 1
|-Push Flag :1
|-Reset Flag :0
|-Synchronise Flag :0
|-Finish Flag :0
|-Window : 143
|-Checksum : 57027
|-Urgent Pointer : 0

###########################################################
UDP multiuser chat

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;

class udp_server1
{
public static void main(String args[]) throws IOException
{
DatagramSocket ds = new DatagramSocket(5542);
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
InetAddress ip = InetAddress.getLocalHost();
byte[] buffer2=new byte[10];
byte[] buffer1=new byte[10];
String str2="";
String str3="";
while(!str2.equals("bye"))
{
DatagramPacket dp = new DatagramPacket(buffer2, buffer2.length);
ds.receive(dp);
buffer2 = dp.getData();
String str = new String(buffer2 , StandardCharsets.UTF_8);
str2=str;
System.out.println("Client " + dp.getPort() + " :" + str2);

System.out.println("Send message to " + dp.getPort() );


str3=br.readLine();
buffer1=str3.getBytes();
DatagramPacket dp2 = new DatagramPacket(buffer1, buffer1.length, ip,
dp.getPort());
ds.send(dp2);
//String str1=br.readLine();
}}}

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;

class udp1
{
public static void main(String args[]) throws IOException
{
DatagramSocket ds = new DatagramSocket(5549);

InetAddress ip = InetAddress.getLocalHost();
byte[] buffer2=new byte[10];
byte[] buffer1=new byte[10];

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));
String str2="";
String str3="";
while(!str2.equals("bye"))
{
str3=br.readLine();
buffer1=str3.getBytes();

DatagramPacket dp2 = new DatagramPacket(buffer1, buffer1.length, ip,


5543);
ds.send(dp2);
DatagramPacket dp = new DatagramPacket(buffer2, buffer2.length);

ds.receive(dp);
buffer2 = dp.getData();
String str = new String(buffer2 , StandardCharsets.UTF_8);
str2=str;
System.out.println("Server: " + str2);
}
}
}

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;

class udp2
{
public static void main(String args[]) throws IOException
{
DatagramSocket ds = new DatagramSocket(5550);

InetAddress ip = InetAddress.getLocalHost();

byte[] buffer2=new byte[10];


byte[] buffer1=new byte[10];

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));
String str2="";
String str3="";
while(!str2.equals("bye"))
{
str3=br.readLine();
buffer1=str3.getBytes();

DatagramPacket dp2 = new DatagramPacket(buffer1, buffer1.length, ip,


5542);
ds.send(dp2);
DatagramPacket dp = new DatagramPacket(buffer2, buffer2.length);

ds.receive(dp);
buffer2 = dp.getData();
String str = new String(buffer2 , StandardCharsets.UTF_8);
str2=str;
System.out.println("Server: " + str2);
}
}
}
Client and server chat

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

void error(const char *msg)


{
perror(msg);
exit(0);
}

int main(int argc, char *argv[])


{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;

char buffer[256];
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr))
< 0)
error("ERROR connecting");
printf("Client: ");
while(1)
{
bzero(buffer,256);
fgets(buffer,255,stdin);
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0)
error("ERROR reading from socket");
printf("Server : %s\n",buffer);
int i = strncmp("Bye" , buffer , 3);
if(i == 0)
break;
}
close(sockfd);
return 0;
}

/* A simple server in the internet domain using TCP


The port number is passed as an argument */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

void error(const char *msg)


{
perror(msg);
exit(1);
}

int main(int argc, char *argv[])


{
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[255];
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc < 2) {
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd,
(struct sockaddr *) &cli_addr,
&clilen);
if (newsockfd < 0)
error("ERROR on accept");
while(1)
{
bzero(buffer,256);
n = read(newsockfd,buffer,255);
if (n < 0) error("ERROR reading from socket");
printf("Client: %s\n",buffer);
bzero(buffer,256);
fgets(buffer,255,stdin);
n = write(newsockfd,buffer,strlen(buffer));
if (n < 0) error("ERROR writing to socket");
int i=strncmp("Bye" , buffer, 3);
if(i == 0)
break;
}
close(newsockfd);
close(sockfd);
return 0;
}
Assignment 9

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<arpa/inet.h>
#include<sys/socket.h>

#define SERVER "127.0.0.1"


#define BUFLEN 503
#define PORT 8885

void error(char *s)


{
perror(s);
exit(1);
}
unsigned long fsize(char* file)
{
FILE * f = fopen(file, "r");
fseek(f, 0, SEEK_END);
unsigned long len = (unsigned long)ftell(f);
fclose(f);
return len;
}

int main(void)
{
struct sockaddr_in si_other;
int s, i, slen=sizeof(si_other);
char buf[BUFLEN];
char message[BUFLEN];

if ( (s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)


{
error("socket");
}

memset((char *) &si_other, 0, sizeof(si_other));


si_other.sin_family = AF_INET;
si_other.sin_port = htons(PORT);//converts the unsigned short
integer hostshort from host byte order to network byte order.

if (inet_aton(SERVER , &si_other.sin_addr) == 0) //converts the


specified string, in the Internet standard dot notation, to a network
address, and stores the address in the structure provided.
{
fprintf(stderr, "inet_aton() failed\n");
exit(1);
}

char fname[20];
printf("Enter Filename with extension: ");
scanf("%s",fname);
sendto(s, fname, 20 , 0 , (struct sockaddr *) &si_other, slen);

memset(message,0,503);

unsigned long siz = fsize(fname);


printf("File size is= %ld \n",(siz % 503));
char str[10];
sprintf(str, "%ld", siz);
sendto(s, str, 20 , 0 , (struct sockaddr *) &si_other, slen);

FILE *f;

f=fopen(fname,"rb");
memset(message,0,503);
fread(message, 503,1,f);

int itr =1;

fread(message, (siz % 503),1,f);


sendto(s, message, (siz % 503) , 0 , (struct sockaddr *) &si_other,
slen);

memset(message,0,503);
fclose(f);
close(s);

return 0;
}

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<arpa/inet.h>
#include<sys/socket.h>

#define BUFLEN 503


#define PORT 8885

void error(char *s)


{
perror(s);
exit(1);
}

int main(void)
{
struct sockaddr_in si_me, si_other;
int s, i,j, slen = sizeof(si_other) , recv_len;
char buf[BUFLEN];

if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)


{
error("socket");
}

memset((char *) &si_me, 0, sizeof(si_me));

si_me.sin_family = AF_INET;
si_me.sin_port = htons(PORT); //converts the unsigned short integer
hostshort from host byte order to network byte order.
si_me.sin_addr.s_addr = htonl(INADDR_ANY); //converts the unsigned
integer from host byte order to network byte order.

if( bind(s , (struct sockaddr*)&si_me, sizeof(si_me) ) == -1)


{
error("bind");
}

char fname[20];
FILE *fp;
recv_len = recvfrom(s, buf, 20, 0, (struct sockaddr *) &si_other,
&slen);

char fna[100];

strcpy(fna,buf);

memset(buf,0,503);
recv_len = recvfrom(s, buf, 20, 0, (struct sockaddr *) &si_other,
&slen);

int len= strlen(fna);

for(j=len-1;j>=0;j--)
{
if(fna[j]=='.')
{
fna[j-1]='1';
}
}
unsigned long mm = atoi(buf); // converts string data type to int
data type

fp=fopen(fna,"wb"); //open a file as a binary file


int itr=1;
memset(buf,0,503);

printf("File size is=%ld \n",(mm%503));


recv_len = recvfrom(s, buf, (mm%503), 0, (struct sockaddr *)
&si_other, &slen);

fwrite(buf,(mm%503), 1, fp);
memset(buf,0,503);
fclose(fp);
close(s);

return 0;
}
Selective repeat client and server

import java.net.*;
import java.io.*;
import java.util.*;
public class SelectiveRepeatClient
{
public static void main(String args[]) throws Exception
{
int i,c,n,d;
Socket s=new Socket("localhost",1060);
BufferedInputStream in=new
BufferedInputStream(s.getInputStream());
DataOutputStream out=new DataOutputStream(s.getOutputStream());
{

try{
c=in.read();
int v[]=new int[c];
for(i=0;i<c;i++)
{
v[i]=in.read();
}

v[5]=-1;
for(i=0;i<c;i++)
{
System.out.println("Received frame:"+v[i]);
}

for(i=0;i<c;i++)
{
if(v[i]==-1)
{
System.out.println("Retransmit frame no:"+i);
n=i;
out.write(n);
v[n] =in.read();

}
}

System.out.println("Received frame after retransmission");


for(i=0;i<c;i++)
{
System.out.println("Received frame:"+v[i]);
}

}catch(Exception e){}
}
}
}

import java.net.*;
import java.io.*;
import java.util.*;
public class SelectiveRepeatServer
{
public static void main(String args[])throws Exception
{
int b,i;
ServerSocket ss=new ServerSocket(1060);
Socket s=ss.accept();
BufferedInputStream in= new BufferedInputStream(s.getInputStream());
DataOutputStream out= new DataOutputStream(s.getOutputStream());
int a[]={10,20,30,40,50,60,70,80,90};
System.out.println("The no. of frames to be sent are:"+a.length);
b=a.length;
out.write(b);
for(i=0;i<b;i++)
{
out.write(a[i]);
System.out.println("Sending frame"+i);
}

int k=in.read();
System.out.println("Retransmitting frame no:"+k);
out.write(a[k]);
}
}
Go back client and server

import java.net.*;
import java.io.*;
import java.util.*;
public class Cli
{
public static void main(String args[]) throws Exception
{ Socket s=new Socket("localhost",1050);
BufferedInputStream in=new
BufferedInputStream(s.getInputStream());
DataOutputStream out=new DataOutputStream(s.getOutputStream());
int i,j,a,b;
Scanner sc = new Scanner(System.in);
System.out.println("Wnter no. of frames server should send:");
int c=sc.nextInt();
out.write(c);
System.out.println("0:NoError\n2:Error\n\n Enter your choice:");
int choice=sc.nextInt();
out.write(choice);
if(choice==0)
{
for(j=0;j<c;j++)
{
System.out.println("\nReceiving frame");
i=in.read();
System.out.println("\nSending Acknowledgment");
out.write(i);
//a=in.read();
}
}
else
{int check=0;
for(j=0;j<c;j++)
{

i=in.read();
if(i==check)
{
System.out.println("\nSending acknowledgment");
out.write(i);
check++;
}
else
{
j--;
System.out.println("\nRetransmit frame");
out.write(-1);
}
}
}
}}
TCP in C
File transfer
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <ctype.h>

void error(const char *msg)


{
perror(msg);
exit(1);
}

int main(int argc, char *argv[])


{
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[512];
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc < 2) {
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd,
(struct sockaddr *) &cli_addr,
&clilen);
if (newsockfd < 0)
error("ERROR on accept");

FILE *fp;
int ch = 0;
fp = fopen("glad_receive.txt","a");
int words;
read(newsockfd, &words, sizeof(int));
//printf("Passed integer is : %d\n" , words); //Ignore
, Line for Testing
while(ch != words)
{
read(newsockfd , buffer , 512);
fprintf(fp , " %s" , buffer);
//printf(" %s %d " , buffer , ch); //Line for Testing , Ignore
ch++;
}
printf("The file was received successfully\n");
printf("The new file created is gladreceive.txt");
close(newsockfd);
close(sockfd);
return 0;
}

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include<ctype.h>

void error(const char *msg)


{
perror(msg);
exit(0);
}

int main(int argc, char *argv[])


{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;

char buffer[512];
if (argc < 3)
{
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr))
< 0)
error("ERROR connecting");

bzero(buffer,512);

FILE *f;

int words = 0;
char c;
f=fopen("glad.txt","r");
while((c=getc(f))!=EOF) //Counting No of words in the file
{
fscanf(f , "%s" , buffer);
if(isspace(c)||c=='\t')
words++;
}
//printf("Words = %d \n" , words); //Ignore

write(sockfd, &words, sizeof(int));


rewind(f);

/* fseek(f, 0L, SEEK_END); // tells size of the


file. Not rquired for the functionality in code.
int sz = ftell(f); //Just written for
curiosity.
printf("Size is %d \n" , sz);
rewind(f);
*/

char ch ;
while(ch != EOF)
{

fscanf(f , "%s" , buffer);


//printf("%s\n" , buffer); //Ignore
write(sockfd,buffer,512);
ch = fgetc(f);
}
printf("The file was sent successfully");
close(sockfd);
return 0;
}

Calculator
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <ctype.h>

void error(const char *msg)


{
perror(msg);
exit(1);
}

int main(int argc, char *argv[])


{
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[1024];
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc < 2) {
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd,
(struct sockaddr *) &cli_addr,
&clilen);
if (newsockfd < 0)
error("ERROR on accept");
int num1 , num2 , ans , choice;
S: n = write(newsockfd,"Enter Number 1 : ",strlen("Enter Number 1"));
//Ask for Number 1
if (n < 0) error("ERROR writing to socket");
read(newsockfd, &num1, sizeof(int));
//Read No 1
printf("Client - Number 1 is : %d\n" , num1);

n = write(newsockfd,"Enter Number 2 : ",strlen("Enter Number 2"));


//Ask for Number 2
if (n < 0) error("ERROR writing to socket");
read(newsockfd, &num2, sizeof(int));
//Read Number 2
printf("Client - Number 2 is : %d\n" , num2);

n = write(newsockfd,"Enter your choice :


\n1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n5.Exit\n",s
trlen("Enter your choice :
\n1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n5.Exit\n"))
; //Ask for choice
if (n < 0) error("ERROR writing to socket");
read(newsockfd, &choice, sizeof(int));
//Read choice
printf("Client - Choice is : %d\n" , choice);

switch(choice)
{
case 1:
ans = num1 + num2;
break;
case 2:
ans = num1 -num2;
break;
case 3:
ans = num1*num2;
break;
case 4:
ans = num1/num2;
break;
case 5 :
goto Q;
break;
}

write(newsockfd , &ans , sizeof(int));


if(choice != 5)
goto S;
Q: close(newsockfd);
close(sockfd);
return 0;
}

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include<ctype.h>

void error(const char *msg)


{
perror(msg);
exit(0);
}

int main(int argc, char *argv[])


{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;

char buffer[1024];
if (argc < 3)
{
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr))
< 0)
error("ERROR connecting");
int num1 ;
int num2 ;
int ans;
int choice;

S:bzero(buffer,256);
n = read(sockfd,buffer,255); //Read Server String
if (n < 0)
error("ERROR reading from socket");
printf("Server - %s\n",buffer);
scanf("%d" , &num1); //Enter No 1
write(sockfd, &num1, sizeof(int)); //Send No 1 to
Server

bzero(buffer,256);
n = read(sockfd,buffer,255); //Read Server String
if (n < 0)
error("ERROR reading from socket");
printf("Server - %s\n",buffer);
scanf("%d" , &num2); //Enter No 2
write(sockfd, &num2, sizeof(int)); //Send No 2 to
Server

bzero(buffer,256);
n = read(sockfd,buffer,255); //Read Server String
if (n < 0)
error("ERROR reading from socket");
printf("Server - %s",buffer);
scanf("%d" , &choice); //Enter choice
write(sockfd, &choice, sizeof(int)); //Send
choice to Server

if (choice == 5)
goto Q;

read(sockfd , &ans , sizeof(int)); //Read Answer


from Server
printf("Server - The answer is : %d\n" , ans); //Get
Answer from server

if(choice != 5)
goto S;

Q: printf("You chose to exit, Thank You so much.");


close(sockfd);
return 0;
}
/*
Server side terminal:
jj@ubuntu:~/Desktop$ gcc Server.c -o Server
jj@ubuntu:~/Desktop$ ./Server 4562
Client - Number 1 is : 50
Client - Number 2 is : 110
Client - Choice is : 1
Client - Number 1 is : 50
Client - Number 2 is : 60
Client - Choice is : 2
Client - Number 1 is : 4
Client - Number 2 is : 8
Client - Choice is : 3
Client - Number 1 is : 66
Client - Number 2 is : 11
Client - Choice is : 4
Client - Number 1 is : 5
Client - Number 2 is : 7
Client - Choice is : 5
jj@ubuntu:~/Desktop$

Client side Terminal:

jj@ubuntu:~/Desktop$ gcc client.c -o client


jj@ubuntu:~/Desktop$ ./client 192.168.244.139 4562
Server - Enter Number 1
50
Server - Enter Number 2
110
Server - Enter your choice :
1.Addition
2.Subtraction
3.Multiplication
4.Division
5.Exit
1
Server - The answer is : 160
Server - Enter Number 1
50
Server - Enter Number 2
60
Server - Enter your choice :
1.Addition
2.Subtraction
3.Multiplication
4.Division
5.Exit
2
Server - The answer is : -10
Server - Enter Number 1
4
Server - Enter Number 2
8
Server - Enter your choice :
1.Addition
2.Subtraction
3.Multiplication
4.Division
5.Exit
3
Server - The answer is : 32
Server - Enter Number 1
66
Server - Enter Number 2
11
Server - Enter your choice :
1.Addition
2.Subtraction
3.Multiplication
4.Division
5.Exit
4
Server - The answer is : 6
Server - Enter Number 1
5
Server - Enter Number 2
7
Server - Enter your choice :
1.Addition
2.Subtraction
3.Multiplication
4.Division
5.Exit
5
You chose to exit, Thank You so much.jj@ubuntu:~/Desktop$

*/
Say hello

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

void error(const char *msg)


{
perror(msg);
exit(1);
}

int main(int argc, char *argv[])


{
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[255];
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc < 2) {
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd,
(struct sockaddr *) &cli_addr,
&clilen);
if (newsockfd < 0)
error("ERROR on accept");
while(1)
{
bzero(buffer,256);
n = read(newsockfd,buffer,255);
if (n < 0) error("ERROR reading from socket");
printf("Client: %s\n",buffer);
bzero(buffer,256);
fgets(buffer,255,stdin);
n = write(newsockfd,buffer,strlen(buffer));
if (n < 0) error("ERROR writing to socket");
int i=strncmp("Bye" , buffer, 3);
if(i == 0)
break;
}
close(newsockfd);
close(sockfd);
return 0;
}

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

void error(const char *msg)


{
perror(msg);
exit(0);
}

int main(int argc, char *argv[])


{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;

char buffer[256];
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr))
< 0)
error("ERROR connecting");
printf("Client: ");
while(1)
{
bzero(buffer,256);
fgets(buffer,255,stdin);
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0)
error("ERROR reading from socket");
printf("Server : %s\n",buffer);
int i = strncmp("Bye" , buffer , 3);
if(i == 0)
break;
}
close(sockfd);
return 0;
}
ASSIGNMENT No. 6
AIM :
Group B: Lab Assignment on Unit IV and Unit V: (Mandatory Assignment)
Use network simulator NS2 to implement:
a. Monitoring traffic for the given topology
b. Analysis of CSMA and Ethernet protocols
c. Network Routing: Shortest path routing, AODV.
d. Analysis of congestion control (TCP and UDP).

OBJECTIVE :
 To install NS2.
 To write program in NS2
OUTCOME :
* Students will be able to NS2 installation
steps. * Students will be able to write
program in NS2.

THEORY:

Introduction to NS2

How to write script in NS2:


In general, an NS script starts with making a Simulator object instance.

set ns [new Simulator]: generates an NS simulator object instance, and assigns it to


variable ns ( italics is used for variables and values in this section ).
The "Simulator" object has member functions that do the following:

$ns color fid color: is to set color of the packets for a flow specified by the flow id (fid). This
member function of "Simulator" object is for the NAM display, and has no effect on the actual
simulation.

$ns namtrace-all file-descriptor: This member function tells the simulator to record simulation
traces in NAM input format. It also gives the file name that the trace will be written to later by
the command $ns flush-trace. Similarly, the member function trace-all is for recording the
simulation trace in a general format. proc finish {}: is called after this simulation is over by the
command $ns at 5.0 "finish". In this function, post-simulation processes are specified.
set n0 [$ns node]: The member function node creates a node. A node in NS is compound object
made of address and port classifiers (described in a later section). Users can create a node by
separately creating an address and a port classifier objects and connecting them together.
However, this member function of Simulator object makes the job easier.
$ns duplex-link node1 node2 bandwidth delay queue-type: creates two simplex links of
specified bandwidth and delay, and connects the two specified nodes. In NS, the output queue
of a node is implemented as a part of a link, therefore users should specify the queue-type
when creating links. In the above simulation script, DropTail queue is used.
$ns queue-limit node1 node2 number: This line sets the queue limit of the two simplex links
that connect node1 and node2 to the number specified.
$ns duplex-link-op node1 node2 ...: The next couple of lines are used for the NAM display. To
see the effects of these lines, users can comment these lines out and try the simulation.

set tcp [new Agent/TCP]: This line shows how to create a TCP agent. But in general, users
can create any agent or traffic sources in this way. Agents and traffic sources are in fact basic
objects ( not compound objects), mostly implemented in C++ and linked to OTcl. Therefore,
there are no specific Simulator object member functions that create these object instances. To
create agents or traffic sources, a user should know the class names these objects (Agent/TCP,
Agnet/TCPSink, Application/FTP and so on). This information can be found in the NS
documentation or partly in this documentation. But one shortcut is to look at the
"ns-2/tcl/libs/ns-default.tcl" file. This file contains the default configurable parameter value
settings for available network objects.

$ns attach-agent node agent: The attach-agent member function attaches an agent object
created to a node object. Actually, what this function does is call the attach member function of
specified node, which attaches the given agent to itself. Therefore, a user can do the same thing
by, for example, $n0 attach $tcp. Similarly, each agent object has a member function
attach-agent that attaches a traffic source object to itself.

$ns connect agent1 agent2: After two agents that will communicate with each other are
created, the next thing is to establish a logical network connection between them. This line
establishes a network connection by setting the destination address to each others' network
and port address pair.

Assuming that all the network configuration is done, the next thing to do is write a simulation
scenario (i.e. simulation scheduling). The Simulator object has many scheduling member
functions. However, the one that is mostly used is the following:

$ns at time "string": This member function of a Simulator object makes the scheduler (
scheduler_ is the variable that points the scheduler object created by [new Scheduler]
command at the beginning of the script) to schedule the execution of the specified string at
given simulation time. For example, $ns at 0.1 "$cbr start" will make the scheduler call a start
member function of the CBR traffic source object, which starts the CBR to transmit data. In NS,
usually a traffic source does not transmit actual data, but it notifies the underlying agent that it
has some amount of data to transmit, and the agent, just knowing how much of the data to
transfer, creates packets and sends them.
After all network configuration, scheduling and post-simulation procedure specifications are
done, the only thing left is to run the simulation. This is done by $ns run.

INSTALLATION STEPS NS2:

1) sudo apt-get install ns 2

Install NAM
1) sudo apt-get purge nam
2) wget --user-agent="Mozilla/5.0 (Windows NT 5.2; rv:2.0.1)
Gecko/20100101 Firefox/4.0.1"
"http://technobytz.com/wpcontent/uploads/2015/11/nam_1.14_
amd64.zip"
3) unzip nam_1.14_amd64.zip
4) sudo dpkg -i nam_1.14_amd64.deb
5) sudo apt-mark hold nam
The First Tcl
How to start
WE can write your Tcl scripts in any text editor like joe or emacs.
'example1.tcl'.

First of all, WE need to create a simulator object. This is done with the

command set ns [new Simulator]

Now we open a file for writing that is going to be used for the nam trace data.

set nf [open out.nam w]


$ns namtrace-all $nf

The first line opens the file 'out.nam' for writing and gives it the file handle 'nf'. In the second
line we tell the simulator object that we created above to write all simulation data that is going
to be relevant for nam into this file.

The next step is to add a 'finish' procedure that closes the trace file and starts nam.
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam out.nam &
exit 0
}

You don't really have to understand all of the above code yet. It will get clearer to you once you
see what the code does.

The next line tells the simulator object to execute the 'finish' procedure after 5.0 seconds of
simulation time.

$ns at 5.0 "finish"

The last line finally starts the simulation.

$ns run

Two nodes, one link


In this section we are going to define a very simple topology with two nodes that are connected
by a link. The following two lines define the two nodes. (Note: You have to insert the code in
this section before the line '$ns run', or even better, before the line '$ns at 5.0 "finish"').

set n0 [$ns
node] set n1
[$ns node]

A new node object is created with the command '$ns node'. The above code creates two nodes
and assigns them to the handles 'n0' and 'n1'.
The next line connects the two nodes.

$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.

Now you can save your file and start the script with 'ns example1.tcl'. nam will be started
automatically and you should see an output that resembles the picture below.

Sending data
We can only look at the topology, but nothing actually happens, so the next step is to send
some data from node n0 to node n1. In ns, data is always being sent from one 'agent' to
another. So the next step is to create an agent object that sends data from node n0, and
another agent object that receives the data on node n1.

#Create a TCP agent and attach it to node n0


set tcp0 [new Agent/TCP]
$ns attach-agent $n0
$tcp0

# 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 $tcp0

These lines create a TCP agent and attach it to the node n0, then attach a CBR traffic generatot
to the TCP agent. CBR stands for 'constant bit rate'. Line 7 and 8 should be self-explaining. The
packetSize is being set to 500 bytes and a packet will be sent every 0.005 seconds (i.e. 200
packets per second). You can find the relevant parameters for each agent type in the ns manual
page

The next lines create a Null agent which acts as traffic sink and attach it to node n1.

set null0 [new Agent/Null]


$ns attach-agent $n1 $null0

Now the two agents have to be connected with each other.

$ns connect $TCP0 $null0

And now we have to tell the CBR agent when to send data and when to stop sending. Note: It's
probably best to put the following lines just before the line '$ns at 5.0 "finish"'.

$ns at 0.5 "$cbr0 start"


$ns at 4.5 "$cbr0 stop"

This code should be self-explaining again.


Now you can save the file and start the simulation again. When you click on the 'play' button in
the nam window, you will see that after 0.5 simulation seconds, node 0 starts sending data
packets to node 1.

Das könnte Ihnen auch gefallen