Beruflich Dokumente
Kultur Dokumente
import java.net.*;
import java.io.*;
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
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 ServerThread(Socket s)
{
this.s=s; //invoke or initiate current class constructor
}
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.*;
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
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);
}
}
}
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;
while (true){
double ii=Math.pow(o,i);
cnt++;
i++;
if((int)ii>n){
number=(int)ii;
break;
}
}
return number;
}
}
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>
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;
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;
}
fprintf(logfile , "\n");
fprintf(logfile , "Ethernet Header\n");
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));
}
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");
print_ip_header(Buffer,Size);
fprintf(logfile , "\n");
//fprintf(logfile , "IP 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);
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];
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();
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>
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;
}
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<arpa/inet.h>
#include<sys/socket.h>
int main(void)
{
struct sockaddr_in si_other;
int s, i, slen=sizeof(si_other);
char buf[BUFLEN];
char message[BUFLEN];
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);
FILE *f;
f=fopen(fname,"rb");
memset(message,0,503);
fread(message, 503,1,f);
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>
int main(void)
{
struct sockaddr_in si_me, si_other;
int s, i,j, slen = sizeof(si_other) , recv_len;
char buf[BUFLEN];
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.
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);
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
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();
}
}
}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>
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>
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
char ch ;
while(ch != EOF)
{
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>
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;
}
#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>
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;
if(choice != 5)
goto S;
*/
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>
#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>
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
$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.
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
Now we open a file for writing that is going to be used for the nam trace data.
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 run
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.
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.
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.
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"'.