Computer Science And Engineering
From Pune Vidhyarthi Griha's College of Engineering, Nashik. 206, Dindori Road, Behind Reliance Petrol Pump, Near Meri, Mhasrul, Nasik - 422004. Maharashtra - INDIA
Friday, 28 August 2015
Thursday, 27 August 2015
Seminar and Workshop
1. Mozilla Firefox
Maker Party Event
You may also get it to involve in this
by clicking below
Mozilla Firefox
2.Android Workshop
Software Development kit of android workshop
3.
IBM Bluemix
ibm.biz/yukiblue
Bluemix !!
You
have this very talented student in your class who has made a mark with
his/her mesmerizing voice in various performances in your college
cultural functions and inter-college functions. What would you do next
for this student? If you had unlimited access to a state-of-the-art
music-recording studio, wont you get this student in there and audition
his/her voice and cut an audio track for a trial-release of music CD?
As faculty you are facilitators.
So
here is a platform for software development from IBM “Bluemix”. You
have such promising students who have a flair for software development?
Why don’t you point them to IBM Bluemix and experience convenience,
speed and simplicity. There is no installation to be done, there is no
environment to be prepared….just jump in put your code and bingo your
app is up and running!
Some
call it development in the cloud, others call it “platform as a service
– PaaS” – you can call it whatever you want…..but just get your
students to jump in and try this out in their next lab session or on
their laptops at home!! Creating apps is indeed child’s play, now, with
Bluemix.
What is Bluemix? You
are looking at IBM’s next generation open-standards cloud based
platform for building, managing, and running apps of all types (web,
mobile, big data, new smart devices). Leverage ready-to-use capabilities
like Java, mobile backend development, application monitoring, as well
as many more assets from ecosystem partners and open source – all
through an as-a-service model in the Cloud.
What’s
cool about this platform? The prebuilt dynamic models and services
that are available in Bluemix helps you to rapidly build applications
using instant services and APIs, and at the same time also provide you a
market place for more! Take your ideas and implement a cloud
application on Bluemix just in a matter of hours - and exploit the
latest workloads in social, mobile and big data.
Augmented Reality Training Program
Tuesday, 9 June 2015
SEM V STUDY MATERIAL
SEM V STUDY MATERIAL
Study Material
DBMS
Download learning material for DBMS
Click here to download
Sturctured query language
Sturctured query language download here
Theory Of Computation Hand-written Notes
DEAR T.E. COMP Friendzzz CLICK HERE TO DOWNLOAD OLD QUESTION PAPERS FOR THE SUBJECT :--- DATA BASE MANAGEMENT SYSTEM OF PUNE UNIVERSITY
OSD Notes
Reference E-Book
Click Hear to start download
Reference e-book 2
Saturday, 6 June 2015
TE-SEM6_PL-04 (Programming Laboratory IV)
TE-SEM6_PL-04
(Programming Laboratory IV)
------------------------------
Practicals List:
-----------------------------
1]. Implementation of Packet sniffer. Program should identify header of each protocol.Use multi-core programming.
2]. Consider the network id 192.168.4.0 or such relevant IP and create four subnets namely
A, B, C, D. Assign the subnet mask. Write a Python \ C++ program to Perform the
following operations (use overloading if applicable).
a) Ping the machine of same subnet.
b) Ping the machine in subnet A from machine of subnet B.
c) Analyze the output of the above sub assignments.
3]. Write C++ Program with GUI to capture using remotely placed camera and read
uncompressed TIFF Image to perform following functions (Menu Driven) Use of
Overloading and Morphism is expected. Image Frame1 is used for displaying Original Image
and Image Frame 2 is used for displaying the action performed.
4]. Write a C++ program to read the HTTP header and analyze the parameters
5]. Installing and configure DHCP server and write a program (C++\Python\Java) to install the software on remote machine.
6]. Design and Setup LAN with Star topology to access Storage Area Network (SAN). The SAN must have DSP data, Text Data, Multimedia Data available for the access.
Assignments Group B (Any Six Assignments, All assignments to be covered in the Batch)
(within 6 assignments atleast two assignments from DSP)
1]. Write a Python program to grab the image from Camera and apply the edge detection algorithm(overloaded with Sobel variants, Others) to find the edges use BBB / ARM Cortex A5/A9/M4 Mobile Boards . Store the Images in SAN (for BIGDATA analitics)
2]. Implementation of streaming video server and displaying video at client side using Java. Videos are stored using SAN (BIGDATA)
3]. Simulation of WAN (RIP) using packet tracer/Network Simulator 3 (NS3)or higher equivalent.
4]. Study and perform Linux networking commands emulation using Python or C++.
5]. Write FTP/Telnet program using socket programming for TCP using C++
6]. Write TFTP program using socket programming for UDP using C++
7]. Create TCP/IP packet using standard TCP/IP include files and send it to the server using c++.
8]. Implement any congestion control algorithm for TCP using Python
9]. Implementation of Concurrent Text Conferencing application using Python or Java
10]. Implementation of Concurrent Proxy server program using Python or Java
11]. Implementation of Multithreaded web server. Check the functionality of web server in LAN and through the ADSL router using NAT.
12]. Implement a program for remote print manager to print documents on remote printer. (IP based printer) using Python
13]. Implementation of sliding window protocol using C++.
14]. Implementation of distance vector routing algorithm using C++.
15]. Implementing video conferencing system. Use VoIP protocol. Use Python or Java.
16]. Configure and setup network with optical router.
17]. (Refer Assignment 3 of Group A) Write a C++/ Python program to generate a Sign wave of Programmable frequency and capture samples at programmable frequency (Max up as per Nyquist Sampling Theorem) and reconstruct the Sign wave using collected Samples using ARM Cortex A5/A9. Use oscilloscope to calculate signal frequency. Write your observations. Store a Data file in SAN (BIGDATA)
18]. (Refer Assignment 3 of Group A) Write a C++/ Python program to generate a Square wave of programmable frequency. Write a function to generate Pole-Zero Diagram using multicore programming.
19]. (Refer Assignment 3 of Group A) Write a C++/ Python program to capture signal using ARM Cortex A5/A9/M4 ADC and signal generator, generate/construct a Square/Sine wave of programmable frequency and voltage Draw Voltage (y-axis) and Time (x-axis) graph. Write a function to emulate simple RC filter with R being Trim-pot(GUI meter) of 10K and C = 0.1 microFarad. Write a program to generate a Voltage-Time response curve with reference to change in R. Draw the resultant outcome graph. Store the data in SAN (BIGDATA)
Assignment Group C: Advance Technology Assignments (Any One)
1]. To create a network with three nodes and establish a TCP connection between node 0 and node 1 such that node 0 will send TCP packet to node 2 via node 1 using NS3 or higher equivalent.
2]. To create scenario of different network topology used in LAN using TCP/UDP and analysis how FTP will run over it in NS3 or higher equivalent.
3]. Designing IPv6 network and/or configuration of Dual stack IPv6 and IPv4 network.
4]. Controlling presentation slides with hands by identifying movements through Camera.
5]. Installation and setup to control the remote machine.
6]. Network Boot operations through Programming.
======================
Grp A 1].
======================
******************************************************************************
Assignment no. : A-1
Title : Implementation of Packet sniffer. Program should identify header of each protocol.Use
multi-core programming.
Roll no. :
Batch :
******************************************************************************
import socket
from struct import *
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
i=0
while (i<500): # change this value for no of packets
pack = s.recvfrom(20000)
#Get the single element from the tuple
packet = pack[0]
#Extract the first 20 bytes
data = packet[0:20]
# Now we have to unpack each element from this raw data
ip_header_data = unpack('!BBHHHBBH4s4s', data)
#To the the ip version we have to shift
#the first element 4 bits right. Because in the first element
#is stored the ip version and the header lenght in this way
#first four bits are ip version and the last 4 bites are
#the header lenght
ip_version = ip_header_data[0] >> 4
#Now to get the header lenght we use "and" operation to make the
#Ip versional bits equal to zero, in order to the the desired data
IHL = ip_header_data[0] & 0x0F
#Diferentiated services doesn't need any magic opperations,
#so we jus grab it from the tuple
diff_services = ip_header_data[1]
#Total lenght is also easy to extract
total_length = ip_header_data[2]
#The same goes for identification
id_ = ip_header_data[3]
#The "Flags" and Fragment Offset are situated in a sinle
#element from the forth element of the tuple.
#Flag is 3 bits (Most significant), so we make "and" with 1110 0000 0000 0000(=0xE000)
#to leave 3 most significant bits and then shift them right 13 positions
flags = ip_header_data[4] & 0xE000 >> 13
#The next elements are easy to get
TTL = ip_header_data[5]
protocol = ip_header_data[6]
checksum = ip_header_data[7]
source = ip_header_data[8]
destinat = ip_header_data[9]
#and the rest data from the "packet" variable is the payload so we
#extract it also
payload = packet[20:]
print "___________NEW_PACKET__________________________"
print "Version: %s \n\rHeader lenght: %s" %(ip_version,IHL)
print "Diferentiated services: %s \n\rID: %s" %(diff_services, id_)
print "Flags: %s \n\rTTL: %s \n\rProtocol: %s" %(flags,TTL,protocol)
print "Checksum: %s \n\rSource: %s \n\rDestination: %s" %(checksum, socket.inet_ntoa(source),socket.inet_ntoa(destinat))
#print "Payload: %s" %(payload)
i = i + 1
===========================
OUTPUT
===========================
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$ python sniffer.py
___________NEW_PACKET__________________________
Version: 4
Header lenght: 5
Diferentiated services: 0
ID: 49742
Flags: 0
TTL: 64
Protocol: 6
Checksum: 37377
Source: 173.194.117.95
Destination: 192.168.2.182
___________NEW_PACKET__________________________
Version: 4
Header lenght: 5
Diferentiated services: 0
ID: 49743
Flags: 0
TTL: 64
Protocol: 6
Checksum: 37376
Source: 173.194.117.95
Destination: 192.168.2.182
___________NEW_PACKET__________________________
Version: 4
Header lenght: 5
Diferentiated services: 0
ID: 49744
Flags: 0
TTL: 64
Protocol: 6
Checksum: 37375
Source: 173.194.117.95
Destination: 192.168.2.182
======================
Grp A 2].
======================
******************************************************************************
Assignment no. : A-2
Title : Consider the network id 192.168.4.0 or such relevant IP and create four subnets namely
A, B, C, D. Assign the subnet mask. Write a Python \ C++ program to Perform the
following operations (use overloading if applicable).
a) Ping the machine of same subnet.
b) Ping the machine in subnet A from machine of subnet B.
c) Analyze the output of the above sub assignments.
Roll no. :
Batch :
******************************************************************************
import os, sys, socket, struct, select, time
# From /usr/include/linux/icmp.h; your milage may vary.
ICMP_ECHO_REQUEST = 8 # Seems to be the same on Solaris.
def checksum(source_string):
"""
I'm not too confident that this is right but testing seems
to suggest that it gives the same answers as in_cksum in ping.c
"""
sum = 0
countTo = (len(source_string)/2)*2
count = 0
while count<countTo:
thisVal = ord(source_string[count + 1])*256 + ord(source_string[count])
sum = sum + thisVal
sum = sum & 0xffffffff # Necessary?
count = count + 2
if countTo<len(source_string):
sum = sum + ord(source_string[len(source_string) - 1])
sum = sum & 0xffffffff # Necessary?
sum = (sum >> 16) + (sum & 0xffff)
sum = sum + (sum >> 16)
answer = ~sum
answer = answer & 0xffff
# Swap bytes. Bugger me if I know why.
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
def receive_one_ping(my_socket, ID, timeout):
"""
receive the ping from the socket.
"""
timeLeft = timeout
while True:
startedSelect = time.time()
whatReady = select.select([my_socket], [], [], timeLeft)
howLongInSelect = (time.time() - startedSelect)
if whatReady[0] == []: # Timeout
return
timeReceived = time.time()
recPacket, addr = my_socket.recvfrom(1024)
icmpHeader = recPacket[20:28]
type, code, checksum, packetID, sequence = struct.unpack(
"bbHHh", icmpHeader
)
if packetID == ID:
bytesInDouble = struct.calcsize("d")
timeSent = struct.unpack("d", recPacket[28:28 + bytesInDouble])[0]
return timeReceived - timeSent
timeLeft = timeLeft - howLongInSelect
if timeLeft <= 0:
return
def send_one_ping(my_socket, dest_addr, ID):
"""
Send one ping to the given >dest_addr<.
"""
dest_addr = socket.gethostbyname(dest_addr)
# Header is type (8), code (8), checksum (16), id (16), sequence (16)
my_checksum = 0
# Make a dummy heder with a 0 checksum.
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1)
bytesInDouble = struct.calcsize("d")
data = (192 - bytesInDouble) * "Q"
data = struct.pack("d", time.time()) + data
# Calculate the checksum on the data and the dummy header.
my_checksum = checksum(header + data)
# Now that we have the right checksum, we put that in. It's just easier
# to make up a new header than to stuff it into the dummy.
header = struct.pack(
"bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1
)
packet = header + data
my_socket.sendto(packet, (dest_addr, 1)) # Don't know about the 1
def do_one(dest_addr, timeout):
"""
Returns either the delay (in seconds) or none on timeout.
"""
icmp = socket.getprotobyname("icmp")
try:
my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
except socket.error, (errno, msg):
if errno == 1:
# Operation not permitted
msg = msg + (
" - Note that ICMP messages can only be sent from processes"
" running as root."
)
raise socket.error(msg)
raise # raise the original error
my_ID = os.getpid() & 0xFFFF
send_one_ping(my_socket, dest_addr, my_ID)
delay = receive_one_ping(my_socket, my_ID, timeout)
my_socket.close()
return delay
def verbose_ping(dest_addr, timeout = 2, count = 4):
"""
Send >count< ping to >dest_addr< with the given >timeout< and display
the result.
"""
for i in xrange(count):
print "ping %s..." % dest_addr,
try:
delay = do_one(dest_addr, timeout)
except socket.gaierror, e:
print "failed. (socket error: '%s')" % e[1]
break
if delay == None:
print "failed. (timeout within %ssec.)" % timeout
else:
delay = delay * 1000
print "get ping in %0.4fms" % delay
if __name__ == '__main__':
verbose_ping("heise.de")
verbose_ping("google.com")
verbose_ping("a-test-url-taht-is-not-available.com")
verbose_ping("192.168.2.183")
************** OUTPUT*******************
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$ python pi.py
ping heise.de... get ping in 394.4390ms
ping heise.de... get ping in 398.0720ms
ping heise.de... get ping in 345.6831ms
ping heise.de... get ping in 350.9300ms
ping google.com... get ping in 120.7960ms
ping google.com... get ping in 109.7860ms
ping google.com... get ping in 87.3210ms
ping google.com... get ping in 111.5770ms
ping a-test-url-taht-is-not-available.com... failed. (socket error: 'No address associated with hostname')
ping 192.168.2.183... get ping in 0.6080ms
ping 192.168.2.183... get ping in 0.6380ms
ping 192.168.2.183... get ping in 0.6349ms
ping 192.168.2.183... get ping in 0.5720ms
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$
======================
Grp A 3].
======================
//=======================================================
//Menu.cpp
//=======================================================
#include<iostream>
#include<stdio.h>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <opencv2\core\core.hpp>
using namespace std;
using namespace cv;
class m enu
{
public: void mstd();
};
void menu::mstd()
{
IplIm age *Image1= cvLoadIm age ("bett er.jpg",1);
CvScalar M eanScal ar;
CvScalar StandardDevi ationScal ar;
cvAvgSdv(Image1, &MeanScalar, &St andardDeviationScalar) ;
printf("Blue Channel Avg is : %.f\n",M eanScal ar. val[0]);
printf("Blue Channel Standard Deviation is :%. f\n",StandardDevi ationScalar. val[0]);
printf("Green Channel Avg is : %. f\n",MeanS calar. val [1]);
printf("Green Channel Standard Deviation is : %. f\n",StandardDeviationScalar. val[1]);
printf("R ed Channel Avg is : %. f\n",MeanScalar. val[2]);
printf("R ed Channel Standard Deviation is :%. f\n",StandardDeviationS calar. val[2]);
}
cvNamedWindow( "better", 1);
cvShowIm age( "bett er", Image1);
cvWaitKey(0) ;
int main()
{
menu m;
int a;
Mat imgOriginal = imread( "better.jpg", 1 );
do
{
cout<<" Please Select Your Choice\n 1. MEAN & STD DEVIATION\n 2. Histo\n 3.
Rotate\n 4. Contrast\n 5. Sharpen\n 6. Blur\n 7. Exit\nEnter Your Choice...!!!\n";
cin>> a;
swit ch(a)
{
cas e 1: m.mstd();
cas e 2:
{Mat src, dst;
/// Load image
src = imread( "better.jpg", 1 );;
i f( !src.data )
{ return -1; }
/// Separate the im age in 3 places ( B, G and R )
vector < Mat > bgr_planes;
split( src, bgr_planes );
/// Est ablish the number of bins
int histSize = 256;
/// Set the ranges ( for B,G,R) )
float range[] = { 0, 256 } ;
const fl oat* histRange = { range };
bool uni form = true; bool accumul ate = false;
Mat b_hist, g_hist, r_hist;
/// Compute the histograms:
calcHist( &bgr_planes[0], 1, 0, M at(), b_hist, 1, &histSi ze, &histRange, uniform, accumulate );
calcHist( &bgr_planes[1], 1, 0, M at(), g_hist, 1, &histSi ze, &histRange, uniform, accumulate );
calcHist( &bgr_planes[2], 1, 0, M at(), r_hist, 1, &histSize, &histRange, uni form, accumulat e );
// Draw the histograms for B, G and R
int hist_w = 512; int hist_h = 400;
int bin_w = cvRound( (double) hist_w/histSize );
Mat histImage( hist_h, hist_w, CV_8UC3, Scal ar( 0,0,0) );
/// Normalize the result to [ 0, histImage.rows ]
normalize(b_hist, b_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() );
normalize(g_hist, g_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() );
normalize(r_hist, r_hist, 0, hist Im age.rows, NORM_MINMAX, -1, M at () );
/// Draw for each channel
for( int i = 1; i < histSize; i++ )
{
line( hist Im age, Point( bin_w*(i -1), hist_h - cvRound(b_hist. at < float > (i-1)) ) ,
Point( bin_w*(i), hist_h - cvRound(b_hist.at < float > (i )) ),
Scalar( 255, 0, 0), 2, 8, 0 );
line( hist Im age, Point( bin_w*(i -1), hist_h - cvRound(g_hist. at < float > (i-1)) ) ,
Point( bin_w*(i), hist_h - cvRound(g_hist.at < float > (i )) ),
Scalar( 0, 255, 0), 2, 8, 0 );
line( hist Im age, Point( bin_w*(i -1), hist_h - cvRound(r_hist.at < float > (i -1)) ) ,
Point( bin_w*(i), hist_h - cvRound(r_hist.at < fl oat > (i)) ),
Scalar( 0, 0, 255), 2, 8, 0 );
}/// Display
nam edWindow("calcHist Demo", CV_WINDOW_AUTOSIZE );
imshow("calcHist Demo", histImage );
waitKey(0);
return 0;
}
case 3:
{
// Load the image
Mat imgOriginal = imread( "bett er.jpg", 1 );
//show the original image
const char* pzOriginalImage = "Original Image";
namedWindow( pzOriginalImage, CV_WINDOW_AUTOSIZE );;
imshow( pzOriginalImage, imgOriginal );
const char* pzRotatedIm age = "Rotated Image";
namedWindow( pzRotatedImage, CV_WINDOW_AUTOSIZE );
int iAngl e = 180;
createTrackbar("Angle", pzRotatedImage, &iAngle, 360);
int iImageHi eght = imgOriginal.rows / 2;
int iImageWidth = imgOriginal.cols / 2;
whil e (t rue)
{
M at matRotation = getRotationMatrix2D( Point(iIm ageWidth, iImageHieght), (iAngl e - 180), 1 );
// Rotate the image
Mat imgRotated;
warpAffine( imgOriginal, imgRotated, matRotation, imgOriginal.size() );
imshow( pzRotatedImage, imgRotated );
int iRet = waitKey(30);
i f ( iRet == 27 )
{
break;
}
}
ret urn 0;
}
case 4:
{
Mat img = imread("better.jpg", CV_LOAD_IM AGE_COLOR); //open and read the image
i f (img.empty())
{cout << "Image cannot be loaded..!!" << endl;
ret urn -1;
}
Mat imgH;
img.convertTo(imgH, -1, 2, 0); //increas e the contrast (doubl e)
Mat imgL;
img.convertTo(imgL, -1, 0.5, 0); //decreas e the contrast (halve)
//create windows
namedWindow("Original Image", CV_WINDOW_AUTOSIZE);
namedWindow("High Contrast", CV_WINDOW_AUTOSIZE);
namedWindow("Low Contrast", CV_WINDOW_AUTOSIZE);
//show the image
imshow("Original Image", img);
imshow("High Contrast", imgH);
imshow("Low Contrast", imgL);
waitKey(0); //wait for key press
destroyAllWindows(); //destroy all open windows
ret urn 0;
}
case 5:
{
Mat image,result;
try
{
image = imread("bett er.jpg");
i f(!im age.data)
{
throw 1;
}
}
catch(int i)
{
cout << "Image is unable to reae" << endl;
}
waitKey(0);
{
result.create(image.size(), image.type());
//For all rows except first and last
for(int i=1;i < im age.rows-1;i++)
{
const uchar *previous = image.ptr < const uchar > (i-1);
const uchar *next = image.ptr < const uchar > (i+1);
const uchar *current = image.ptr < const uchar >(i);
uchar *output = res ult.ptr < uchar > (i);//For all columns except first and last
for(int a=3;a < (image. cols -1)*3;a++)
{
output[a] = cv::saturat e_cast < uchar >(5*current[a]-current[a-1]-current[a+1]-previous [a]-next[a]);
}
}
result.row(0).s etTo(cv::Scal ar(0));
result.row(result.rows-1).setTo(cv::Scalar(0));
result.col(0).setTo(cv::Scalar(0));
result.col(result.cols-1).setTo(cv::Scal ar(0));
namedWindow("Original");
imshow("Original",image);
namedWindow("Duplicate");
imshow("Duplicat e",result);
}
}
case 6:
{
//create 2 empty windows
namedWindow( "Original Im age" , CV_WINDOW_AUTOSIZE );
namedWindow( "Smoothed Image" , CV_WINDOW_AUTOSIZE );
// Load an image from fi le
Mat src = imread( "better.jpg", 1 );
//show the loaded image
imshow( "Original Im age", src );
Mat dst;
char zBuffer[35];
for ( int i = 1; i < 31; i = i + 2 )
{
//copy the text to the "zBuffer"
_snprint f_s(zBu ffer, 35,"Kernel Size : %d x %d", i, i);
//smooth the image in the "src" and s ave it to "dst"
blur( src, dst, Size( i, i ) );
//put the text in the "zBuffer" to the "dst" image
putText( dst, zBuffer, Point( src.cols/4, src.rows/8), CV_FONT_HERSHEY_COMPLEX, 1,
Scalar(255, 255, 255) );
//show the blurred image with the text
imshow( "Smoothed Image", dst );//wait for 2 seconds
int c = wait Key(2000);
//if the "esc" key is pressed during the wait, return
i f (c == 27)
{
ret urn 0;
}
}
//make the "dst" image, black
dst = Mat::zeros( src.size(), src.type() );
//copy the text to the "zBuffer"
_snprint f_s(zBu ffer, 35,"Press Any Key to Exit");
//put the text in the "zBuffer" to the "dst" image
putText( dst, zBuffer, Point( src.cols/4, src.rows / 2), CV_FONT_HERSHEY_COMPLEX,
1, Scalar(255, 255, 255) );
//show the black image with the text
imshow( "Smoothed Image", dst );
//wait for a key press infinitely
waitKey(0);
ret urn 0;
}
case 7: exit (0);
}
}while(-1);
}
//=======================================================
//Mstd.cpp
//=======================================================
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
void main8888()
{
IplImage *Image1=cvLoadImage ("better.jpg",1);
CvScal ar MeanScalar;
CvScal ar StandardDeviationScalar;
cvAvgSdv(Im age1, &MeanScalar, &StandardDeviationScal ar) ;
print f("Blue Channel Avg is : %. f\n",MeanScalar. val[0]);
print f("Blue Channel Standard Deviation is : %. f\n",StandardDeviationScalar. val [0]);
print f("Green Channel Avg is : %.f\ n",MeanScalar. val[1]);print f("Green Channel Standard Devi ation is : %. f\n",StandardDeviationScalar. val [1]);
print f("Red Channel Avg is : %. f\n",MeanS calar. val [2]);
print f("Red Channel Standard Deviation is :%.f\n",StandardDeviationScalar. val[2]);
cvNam edWindow( "better", 1);
cvShowImage( "better", Im age1);
cvWaitKey(0) ;
}
//=======================================================
//histo.cpp
//=======================================================
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
using namespace std;
using namespace cv;
/**
* @function main
*/
int main7878789( int argc, char** argv )
{
M at src, dst;
/// Load image
s rc = imread( "better.jpg", 1 );;
i f( !src.data )
{ return -1; }
/// Separate the image in 3 places ( B, G and R )
vector < Mat > bgr_planes;
split( src, bgr_pl anes );
/// Establish the number of bins
int histSize = 256;
/// Set the ranges ( for B,G,R) )
float range[] = { 0, 256 } ;
const float* histRange = { range };
bool uniform = true; bool accumulate = false;
M at b_hist, g_hist, r_hist;
/// Compute the histograms:
calcHist( &bgr_planes[0], 1, 0, M at(), b_hist, 1, &histSi ze, &histRange, uniform, accumulate );
calcHist( &bgr_planes[1], 1, 0, M at(), g_hist, 1, &histSi ze, &histRange, uniform, accumulate );calcHist( &bgr_planes[2], 1, 0, M at(), r_hist, 1, &histSize, &histRange, uni form, accumulat e );
// Draw the histograms for B, G and R
int hist_w = 512; int hist_h = 400;
int bin_w = cvRound( (double) hist_w/histSize );
M at histImage( hist_h, hist_w, CV_8UC3, Scalar( 0,0,0) );
/// Normalize the result to [ 0, histImage.rows ]
normalize(b_hist, b_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() );
normalize(g_hist, g_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() );
normalize(r_hist, r_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() );
/// Draw for each channel
for( int i = 1; i < histSize; i++ )
{
line( histImage, Point( bin_w*(i-1), hist_h - cvRound(b_hist.at < float >(i-1)) ) ,
Point( bin_w*(i), hist_h - cvRound(b_hist.at < float >(i)) ),
Scalar( 255, 0, 0), 2, 8, 0 );
line( histImage, Point( bin_w*(i-1), hist_h - cvRound(g_hist.at < float >(i-1)) ) ,
Point( bin_w*(i), hist_h - cvRound(g_hist.at < float > (i )) ),
Scalar( 0, 255, 0), 2, 8, 0 );
line( histImage, Point( bin_w*(i-1), hist_h - cvRound(r_hist.at < fl oat > (i-1)) ) ,
Point( bin_w*(i), hist_h - cvRound(r_hist.at < fl oat > (i)) ),
Scalar( 0, 0, 255), 2, 8, 0 );
}
/// Display
namedWindow("calcHist Demo", CV_WINDOW_AUTOSIZE );
imshow("calcHist Demo", histImage );
waitKey(0);
return 0;
}
//=======================================================
//rotate. cpp
//=======================================================
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
using namespace cv;
int main7894( int argc, char** argv )
{
// Load the image
M at imgOriginal = imread( "bett er.jpg", 1 );
//show the original image
const char* pzOriginalImage = "Original Image";namedWindow( pzOriginalImage, CV_WINDOW_AUTOSIZE );;
imshow( pzOriginalImage, imgOriginal );
const char* pzRotatedIm age = "Rotated Image";
namedWindow( pzRotatedImage, CV_WINDOW_AUTOSIZE );
int iAngl e = 180;
createTrackbar("Angle", pzRotatedImage, &iAngle, 360);
int iIm ageHieght = imgOriginal.rows / 2;
int iIm ageWidth = imgOriginal.cols / 2;
whil e (true)
{
M at matRotation = getRotationMatrix2D( Point(iIm ageWidth, iImageHieght), (iAngl e - 180), 1 );
// Rotate the image
M at imgRotat ed;
warpA ffi ne( imgOriginal, imgRotat ed, matRotation, imgOriginal.si ze() );
imshow( pzRotatedImage, imgRotated );
int iRet = waitKey(30);
i f ( iRet == 27 )
{
break;
}
}
return 0;
}
//=======================================================
//contrast. cpp
//=======================================================
#include "opencv2/highgui/highgui.hpp"
using namespace cv;
using namespace std;
int main69( int argc, const char** argv )
{
M at img = imread("better.jpg", CV_LOAD_IMAGE_COLOR );
i f (img.empty())
{
cout << "Image cannot be loaded..!!" << endl;
return -1;
}
M at imgH;
img.convertTo(imgH, -1, 2, 0); //increase the contrast (double)
M at imgL;
img.convertTo(imgL, -1, 0.5, 0); //decrease the contrast (halve)//creat e windows
namedWindow("Original Im age", CV_WINDOW_AUTOSIZE);
namedWindow("High Contrast", CV_WINDOW_AUTOSIZE);
namedWindow("Low Contrast", CV_WINDOW_AUTOS IZE);
//show the image
imshow("Original Im age", img);
imshow("High Contrast", imgH);
imshow("Low Contrast", imgL);
waitKey(0); //wait for key press
destroyAllWindows(); //destroy all open windows
return 0;
}
//=======================================================
//sharp.cpp
//=======================================================
#include <iostream>
#include <opencv2\core\core.hpp>
#include <opencv2\highgui\highgui.hpp>
using namespace std;
using namespace cv;
void Sharpen(Mat &image,Mat& result)
{
result. create(image.size(), image.type());
//For all rows except first and last
for(int i=1; i < im age.rows-1;i++)
{
const uchar *previous = image.ptr < const uchar >(i-1);
const uchar *next = im age.pt r < const uchar > (i+1);
const uchar *current = image.ptr < const uchar > (i);
uchar *output = result.ptr < uchar > (i);
//For all columns except fi rst and l ast
for(int a=3; a < (image.cols -1)*3;a++)
{
output[a] = cv::saturat e_cast < uchar > (5*current[a]-current[a-1]-current [a+1]-previous[a]-next[a]);
}
}
result.row(0).setTo(cv::Scalar(0));
result.row(result.rows-1).s etTo(cv::Scal ar(0));
result. col (0).setTo(cv::Scalar(0));
result. col (result.cols-1).setTo(cv::Scalar(0));namedWindow("Original");
imshow("Original",image);
namedWindow("Dupli cate");
imshow("Dupli cate",result);
}
int main45655()
{
M at image,result;
t ry
{
image = imread("better.jpg");
i f(!image.dat a)
{
throw 1;
}
}
catch(int i)
{
cout << "Image is unable to reae" << endl;
}
Sharpen(image,result);
waitKey(0);
}
//=======================================================
//blur.cpp
//=======================================================
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace cv;
int main342( int argc, char** argv )
{
//creat e 2 empty windows
namedWindow( "Original Image" , CV_WINDOW_AUTOSIZE );
namedWindow( "Smoothed Image" , CV_WINDOW_AUTOSIZE );
// Load an image from file
M at src = imread( "better.jpg", 1 );
//show the loaded image
imshow( "Original Image", src );
M at dst;
char zBuffer[35];for ( int i = 1; i < 31; i = i + 2 )
{
//copy the text to the "zBuffer"
_snprint f_s (zBuffer, 35,"Kernel Size : %d x %d", i, i);
//smooth the im age in the "src" and save it to "dst"
blur( s rc, dst, Size( i, i ) );
//put the text in the "zBuffer" to the "dst" image
putText( dst, zBu ffer, Point( src.cols/4, src.rows/8), CV_FONT_HERSHEY_COMPLEX, 1,
Scalar(255, 255, 255) );
//show the blurred image with the text
imshow( "Smoothed Image", dst );
//wait for 2 s econds
int c = waitKey(2000);
//i f the "esc" key is press ed during the wait, return
i f (c == 27)
{
return 0;
}
}
//make the "dst" image, black
dst = Mat::zeros( src.size(), src.type() );
//copy the text to the "zBuffer"
_snprint f_s (zBuffer, 35,"Press Any Key to Exit");
//put the text in the "zBuffer" to the "dst" image
putText( dst, zBu ffer, Point( src.cols/4, src.rows / 2), CV_FONT_HERSHEY_C OMPLEX, 1,
Scalar(255, 255, 255) );
//show the black image with the t ext
imshow( "Smoothed Image", dst );
//wait for a key press infinit ely
waitKey(0);
return 0;
}
======================
Grp A 4].
======================
******************************************************************************
Assignment no. : A-4
Title : Write a C++ program to read the HTTP header and analyze the parameters
Roll no. :
Batch :
******************************************************************************
#include <winsock2.h>
#include <windows.h>
#include <iostream>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
int main (){
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
cout << "WSAStartup failed.\n";
system("pause");
return 1;
}
SOCKET Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
struct hostent *host;
host = gethostbyname("www.google.com");
SOCKADDR_IN SockAddr;
SockAddr.sin_port=htons(80);
SockAddr.sin_family=AF_INET;
SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
cout << "Connecting...\n";
if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0){
cout << "Could not connect";
system("pause");
return 1;
}
cout << "Connected.\n";
send(Socket,"GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n", strlen("GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n"),0);
char buffer[10000];
int nDataLength;
while ((nDataLength = recv(Socket,buffer,10000,0)) > 0){
int i = 0;
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
cout << buffer[i];
i += 1;
}
}
closesocket(Socket);
WSACleanup();
system("pause");
return 0;
}
/******* OUTPUT ********
D:\>bcc32 w.cpp
Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland
w.cpp:
Warning W8004 w.cpp 41: 'nDataLength' is assigned a value that is never used in
function main()
Turbo Incremental Link 5.00 Copyright (c) 1997, 2000 Borland
Fatal: Could not open w.exe (program still running?)
D:\>w
Connecting...
Connected.
HTTP/1.1 302 Found
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Location: http://www.google.co.in/?gfe_rd=cr&ei=xFimVOToFsGAvASbvIHICw
Content-Length: 261
Date: Fri, 02 Jan 2015 08:37:24 GMT
Server: GFE/2.0
Alternate-Protocol: 80:quic,p=0.02
Connection: close
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.google.co.in/?gfe_rd=cr&ei=xFimVOToFsGAvASbvIHICw">here<
/A>.
</BODY></HTML>
Press any key to continue . . .
*/
======================
Grp A 6].
======================
/*---------------------------------------------------------------------------------------------------------------------
Group:A
Assignment No: 6
Roll No:
Title:Design and Setup LAN with Star topology to access Storage Area Network (SAN). The SAN
must have DSP data, Text Data, Multimedia Data available for the access.
---------------------------------------------------------------------------------------------------------------------*/
Title:-
Design and Setup LAN with Star topology to access Storage Area Network (SAN). The SAN must have DSP data, Text Data, Multimedia Data available for the access.
Pre-requisites :-
Storage area network.
Star Topology.
Objective :-
To Configure SAN using Star Topology.
Index Terms :-
Network Topology
A network topology is the basic design of a computer network. It is very much like a map of a road. It details how key network components such as nodes and links are interconnected.
Star Topology:
All devices connected with a Star setup communicate through a central Hub by cable segments. Signals are transmitted and received through the Hub. It is the simplest and the oldest and all the telephone switches are based on this. In a star topology, each network device has a home run of cabling back to a network hub, giving each device a separate connection to the network. So, there can be multiple connections in parallel.
Advantages
Network administration and error detection is easier because problem is isolated to central node
Networks runs even if one host fails
Expansion becomes easier and scalability of the network increases
More suited for larger networks
Storage Area Network
The term SAN designates a new type of storage architecture in which the storage systems
are attached to a high speed network dedicated exclusively to storage. It involves a whole
new network totally distinct from existing communication networks, as is illustrated in
Figure1. The application servers (usually UNIX or Windows NT based) access the storage
resource through the SAN. Most of the local storage resources are off–loaded from the
applications servers, are managed separately from them, and are consolidated at the data
centre, site, or enterprise level.
The term SAN refers both to the high speed network infrastructure and thewhole storage architecture, including servers, storage subsystems and management software.
Fibre Channel is currently the preferred technology for implementing SAN architecture. The
technology is open, widely accepted, and is defined by ANSI standards. To simplify the
migration and integration of legacy equipment, SAN infrastructure based on Fibre Channel
technology supports multiple protocols. For example, the infrastructure can convey SCSI
protocols, widely used in UNIX and Intel based servers, ESCON for IBM mainframes, and IP
to offer networking capability. But the purpose of SAN is not to replace LANs. All these
protocols can simultaneously use the same cables.
Benefits Of SAN:
1. Cost reduction
2. Easy administration
3. High security andavailability
4. Improved performance
5. Quick evolution capability
SAN design using Star topology
Topology is usually described in terms of how the switches are interconnected, such as ring, core-edge, and edge-core-edge or fully meshed. At this point the focus is on switch topology with Sls.
Storage Switches
Storage switches are basic building blocks to storage network topology. Each switch consists of
several ports interconnected by a switch construct. The basic function of a storage switch is to
forward frames among the ports according to the protocol supported by the storage network. In a
Fibre Channel Network, the switch obeys the rules specified by the FC-SW standard to handle the
frames. In an iSCSI storage network, the switching is typically done at the Ethernet layer
according to the Ethernet bridging standards, such as 802.1D or the IP layer. Although the
specific protocols are different, the various types of storage switches share the common basic
structure. However, because of the difference in network protocols, different types of switches are
still required: Fibre Channel switches for FC SANs, the Ethernet switches or IP routers for iSCSI
network. New multiservice switches are being developed to help the convergence of heterogeneous storage networks running multiple network protocols.
The control unit, which is either attached directly to the switch fabric or attached via a
dedicated control interconnection network, and provides control plane and management plane functions to the rest of the system.
The service or interworking units that provide the processing power for complicated service
functions or interworking functions. The user traffic from the line interface units that require special processing is often groomed into the service/interworking units for further processing.
The service unit can operate in a one-arm fashion, or have its own external line interfaces.
One example is an iSCSI Ethernet service card on a Fibre Channel director switch. The iSCSI service card provides interworking between Fibre Channel and iSCSI as well as the Ethernet interface to the iSCSI network.
Lastly, the switch fabric is the central unit that ties all the units together and provides the
means for passing traffic among the units. Most popular switching fabric technologies
employed by recent storage switches include shared memory switches, digital crossbar
switches and analog crosspoint switches. There are examples of large storage switches that
are put together using smaller switch elements in a multistage fashion.
Methodology to Build SAN Configurations
Step 1 Collect the Data
Identify all the servers, applications, and data–sets
Get characteristics of each data–set
Step 2 :Size the Servers and Storage Systems
Create connectivity matrix and data–set maps
Configure each disk array
Identify hot–spots
Configure the libraries
Step 3: Design the SAN Topology
Start with an empty map
The following sequence is recommended in conjunction with the above template:
1. Group servers by location and function.
2. Group arrays and libraries by location and function.
3. Identify site boundaries, distance information, rooms, etc.
4. Draw existing SAN infrastructure (in the case of an upgrade).
5. Draw interconnection of arrays (e.g. Symmetrix and SRDF).
6. Identify servers with multipathing software.
Analyze the structure of the SAN to be designed
Interconnect hardware according to your connectivity matrix
Check performance constraints
Identify zones to be defined in the SAN
Determine whether there is a need for zoning:
• to simulate independent islands
• to isolate areas to meet customer’s requirements
• to share the infrastructure with servers and storage not approved by Bull.
Specify the LUN management tools
Document which LUN access control product will be used:
1. S@N.IT!
2. Volume Logix (Symmetrix)
3. Access Logix (DAS 4500)
4. A combination of all three
5. None (acceptable for 2–node clusters – otherwise risky).
Check multipathing risks
The interconnection of devices creates more connections than required in the connectivity
matrix. Check that these extra connections do not lead to operational problems.
If there are problems:
• use zoning or masking to resolve them
and/or
• modify LUN assignment to array ports
and/or
• modify cabling.
Check list:
• is LUN visible through multiple ports?
• are there multiple copies of the LUN (in the same array, or in other arrays)?
• are there servers with multiple HBA (with or without multipathing software)?
Consolidate all the information
Create a topology map with all the interconnections and zones.
Draw up a list of the required hardware to prepare ordering with NOEMIE (HBA, hubs,
switches, bridges, cables, etc.).
Draw up a consolidated definition of LUN visibility (bindings) to array ports.
Define zones and LUN masking for servers to ensure correct operation of servers.
Step 5 Determine a Management Policy
Draw the management infrastructure
List all the software to be installed and identify all the components to prepare NOEMIE
ordering. The list should include:
• array management
• library management
• SAN infrastructure device management
• backup management
• resource access control
• SAN management
• HA and clustering management
• an updated topology map.
Step 6 Write a Consolidated Report
Prepare a proposal for your customer that includes:
• an explanation of the proposed solution
• a list of hardware and software (derived from NOEMIE)
• the data–set distribution on the arrays
• a topology map
• all the sizing and performance data.
Make sure the following information is available for the installation phase:
• disk array configuration
• zoning and masking requirements
• software installation procedure.
Conclusion :-
Thus,we have studied how to configured and setup star topology in LAN to access SAN data.
======================
Grp B 1].
======================
import cv2
import numpy
cap = cv2.VideoCapture(0)
cap.set(3, 960)
cap.set(4, 544)
r, frame = cap.read()
img = cv2.GaussianBlur(frame,(3,3),0)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
scale = 1
delta = 0
ddepth = cv2.CV_16S
grad_x = cv2.Sobel(gray,ddepth,1,0,ksize = 3, scale = scale, delta = delta,borderType = cv2.BORDER_DEFAULT)
grad_y = cv2.Sobel(gray,ddepth,0,1,ksize = 3, scale = scale, delta = delta, borderType = cv2.BORDER_DEFAULT)
abs_grad_x = cv2.convertScaleAbs(grad_x)
abs_grad_y = cv2.convertScaleAbs(grad_y)
dst = cv2.addWeighted(abs_grad_x,0.5,abs_grad_y,0.5,0)
cv2.imwrite("123.jpg", dst)
cv2.imwrite("456.jpg", frame)
print("GoodBye...")
--------------------------------------------------------------------------------------------------------------------
Assignment :- B-3
Title :- Simulation of WAN (RIP) using packet tracer/Network Simulator 3
(NS3)or higher
equivalent.
Roll_No. :-
--------------------------------------------------------------------------------------------------------------------*/
Title:-
Configure and setup network with optical router.
Pre-requisites :-
·
RIP Protocol
·
WAN Network
·
NS3
Objective :-
To simulate WAN using Packet Tracer/NS3.
Index Terms :-
Routing Information
Protocol -
The Routing Information Protocol (RIP) is one of the oldest
distance-vector routing protocols, which employs the hop count as a routing
metric. It is an Open Standard Routing Protocol. RIP prevents routing loops by
implementing a limit on the number of hops allowed in a path from the source to
a destination. The maximum number of hops allowed for RIP is 15. This hop
limit, however, also limits the size of networks that RIP can support. A hop
count of 16 is considered an infinite distance, in other words the route is
considered unreachable. RIP implements the split horizon, route poisoning and
holddown mechanisms to prevent incorrect routing information from being
propagated.
Originally, each RIP router transmitted full updates every 30
seconds. In most current networking environments, RIP is not the preferred
choice for routing as its time to converge and scalability are poor compared to
EIGRP, OSPF, or IS-IS (the latter two being link-state routing protocols), and
a hop limit severely limits the size of network it can be used in. However, it
is easy to configure, because RIP does not require any parameters on a router
unlike other protocols.
RIP uses the User Datagram Protocol (UDP) as its transport
protocol, and is assigned the reserved port number 520. Rip has two versions-
RIPv1 and RIPv2, running on Ipv4 and RIPng running on Ipv6.
RIP version 1 (RIPv1) -
The original specification of RIP, defined in RFC 1058, was
published in 1988 and uses classful routing. The periodic routing updates do not
carry subnet information, lacking support for variable length subnet masks
(VLSM). This limitation makes it impossible to have different-sized subnets
inside of the same network class. In other words, all subnets in a network
class must have the same size. There is also no support for router
authentication, making RIP vulnerable to various attacks. RIPv1 uses Broadcast
IP 255.255.255.255 for communication.
RIP version 2 (RIPv2) -
Due to the deficiencies
of the original RIP specification, RIP version 2 (RIPv2) was developed in 1993
and last standardized in 1998. It included the ability to carry subnet
information, thus supporting Classless Inter-Domain Routing (CIDR). To maintain
backward compatibility, the hop count limit of 15 remained. RIPv2 has facilities
to fully interoperate with the earlier specification if all Must Be Zero
protocol fields in the RIPv1 messages are properly specified. In addition, a
compatibility switch feature allows fine-grained interoperability adjustments.
In an effort to avoid
unnecessary load on hosts that do not participate in routing, RIPv2 multicasts
the entire routing table to all adjacent routers at the address 224.0.0.9, as
opposed to RIPv1 which uses broadcast. Unicast addressing is still allowed for
special applications. (MD5) authentication for RIP was introduced in 1997.
RIPv2 is Internet Standard STD56 (which is RFC 2453). Route tags were also
added in RIP version 2. This functionality allows a distinction between routes
learned from the RIP protocol and routes learned from other protocols.
RIP next generation
(RIPng) -
RIPng (RIP next generation), defined in RFC 2080,[7] is an
extension of RIPv2 for support of IPv6, the next generation Internet Protocol.
The main differences between RIPv2 and RIPng are:
·
Support of IPv6 networking.
·
While RIPv2 supports RIPv1 updates authentication, RIPng does not.
IPv6 routers were, at the time, supposed to use IPsec for authentication.
·
RIPv2 encodes the next-hop into each route entry, RIPng requires
specific encoding of the next hop for a set of route entries.
RIPng sends updates on UDP port 521 using the multicast group
FF02::9.
For implementing RIP protocol between two routers, we can use any
of the network simulation tools available -
·
Packet Tracer
·
GNS
·
NFS
Packet Tracer -
Cisco Packet Tracer is a powerful network simulation program that
allows us to experiment with network behavior. Packet Tracer provides
simulation, visualization, authoring, assessment, and collaboration
capabilities and facilitates the teaching and learning of complex technology
concepts.
Packet Tracer supplements physical equipment by allowing us to
create a network with an almost unlimited number of devices, encouraging
practice, discovery, and troubleshooting.
Commands for implementing RIP between two routers
hostname – This command is used to change the name of a router.
interface – This command is used to assign IP address to an
interface.
router rip – This command enables a RIP routing
process, which places us in router configuration mode.
network – This command associates a network with a RIP routing
process.
Implementing RIP using Packet Tracer –
Configurations on Router 1 -
System Bootstrap, Version 12.3(8r)T8, RELEASE SOFTWARE (fc1) Cisco
1841 (revision 5.0) with 114688K/16384K bytes of memory.
Self decompressing the image :
##########################################################################
[OK]
Restricted Rights Legend
Use, duplication, or disclosure by the Government is subject to
restrictions as set forth in subparagraph (c) of the Commercial Computer
Software - Restricted Rights clause at FAR sec. 52.227-19 and subparagraph (c)
(1) (ii) of the Rights in Technical Data and Computer Software clause at DFARS
sec. 252.227-7013.
cisco Systems, Inc.
170 West Tasman Drive
San Jose, California 95134-1706
Cisco IOS Software, 1841 Software (C1841-ADVIPSERVICESK9-M),
Version 12.4(15)T1, RELEASE SOFTWARE (fc2)
Copyright (c) 1986-2007 by Cisco Systems, Inc.
Compiled Wed 18-Jul-07 04:52 by pt_team
Image text-base: 0x60080608, data-base: 0x6270CD50
This product contains cryptographic features and is subject to
United States and local country laws governing import, export, transfer and
use. Delivery of Cisco cryptographic products does not imply third-party
authority to import, export, distribute or use encryption. Importers,
exporters, distributors and users are responsible for compliance with U.S. and
local country laws. By using this product you agree to comply with applicable
laws and regulations. If you are unable to comply with U.S. and local laws,
return this product immediately.
A summary of U.S. laws governing Cisco cryptographic products may
be found at:
http://www.cisco.com/wwl/export/crypto/tool/stqrg.html
If you require further assistance please contact us by sending
email to export@cisco.com.
Cisco 1841 (revision 5.0) with 114688K/16384K bytes of memory.
Processor board ID FTX0947Z18E
M860 processor: part number 0, mask 49
2 FastEthernet/IEEE 802.3 interface(s)
191K bytes of NVRAM.
63488K bytes of ATA CompactFlash (Read/Write)
Cisco IOS Software, 1841 Software (C1841-ADVIPSERVICESK9-M),
Version 12.4(15)T1, RELEASE SOFTWARE (fc2)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2007 by Cisco Systems, Inc.
Compiled Wed 18-Jul-07 04:52 by pt_team
--- System Configuration Dialog ---
Continue with configuration dialog? [yes/no]: n
Press RETURN to get started!
Router>enable
Router#config terminal
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#interface fastEthernet 0/0
Router(config-if)#ip address 192.168.1.1 255.255.255.0
Router(config-if)#no shutdown
%LINK-5-CHANGED: Interface FastEthernet0/0, changed state to up
%LINEPROTO-5-UPDOWN: Line protocol on Interface FastEthernet0/0,
changed state to up
Router(config-if)#exit
Router(config)#interface fastEthernet 0/1
Router(config-if)#ip address 192.168.2.1 255.255.255.0
Router(config-if)#no shutdown
%LINK-5-CHANGED: Interface FastEthernet0/1, changed state to up
Router(config-if)#exit
Router(config)#interface Serial 0/0/0
Router(config-if)#ip address 192.168.3.1 255.255.255.0
Router(config-if)#no shutdown
%LINK-5-CHANGED: Interface Serial0/0/0, changed state to up
%LINEPROTO-5-UPDOWN: Line protocol on Interface Serial0/0/0,
changed state to up
Router(config-if)#exit
Router(config)#router rip
Router(config-router)#network 192.168.3.0
Router(config-router)#network 192.168.4.0
Router(config-router)#exit
Router(config)#exit
%SYS-5-CONFIG_I: Configured from console by console
Router#show ip protocols
Routing Protocol is "rip"
Sending updates every 30 seconds, next due in 5 seconds
Invalid after 180 seconds, hold down 180, flushed after 240
Outgoing update filter list for all interfaces is not set
Incoming update filter list for all interfaces is not set
Redistributing: rip
Default version control: send version 1, receive any version
Interface Send Recv Triggered RIP Key-chain
Serial0/0/0 1 2 1
Automatic network summarization is in effect
Maximum path: 4
Routing for Networks:
192.168.3.0
192.168.4.0
Passive Interface(s):
Routing Information Sources:
Gateway Distance Last Update
Distance: (default is 120)
Router#
Configurations on Router 2 -
System Bootstrap, Version 12.3(8r)T8, RELEASE SOFTWARE (fc1) Cisco
1841 (revision 5.0) with 114688K/16384K bytes of memory.
Self decompressing the image :
##########################################################################
[OK]
Restricted Rights Legend
Use, duplication, or disclosure by the Government is subject to
restrictions as set forth in subparagraph (c) of the Commercial Computer
Software - Restricted Rights clause at FAR sec. 52.227-19 and subparagraph (c)
(1) (ii) of the Rights in Technical Data and Computer Software clause at DFARS
sec. 252.227-7013.
cisco Systems, Inc.
170 West Tasman Drive
San Jose, California 95134-1706
Cisco IOS Software, 1841 Software (C1841-ADVIPSERVICESK9-M),
Version 12.4(15)T1, RELEASE SOFTWARE (fc2)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2007 by Cisco Systems, Inc.
Compiled Wed 18-Jul-07 04:52 by pt_team
Image text-base: 0x60080608, data-base: 0x6270CD50
This product contains cryptographic features and is subject to
United States and local country laws governing import, export, transfer and
use. Delivery of Cisco cryptographic products does not imply third-party
authority to import, export, distribute or use encryption. Importers,
exporters, distributors and users are responsible for compliance with U.S. and
local country laws. By using this product you agree to comply with applicable
laws and regulations. If you are unable to comply with U.S. and local laws,
return this product immediately.
A summary of U.S. laws governing Cisco cryptographic products may
be found at:
http://www.cisco.com/wwl/export/crypto/tool/stqrg.html
If you require further assistance please contact us by sending
email to
export@cisco.com.
Cisco 1841 (revision 5.0) with 114688K/16384K bytes of memory.
Processor board ID FTX0947Z18E
M860 processor: part number 0, mask 49
2 FastEthernet/IEEE 802.3 interface(s)
191K bytes of NVRAM.
63488K bytes of ATA CompactFlash (Read/Write)
Cisco IOS Software, 1841 Software (C1841-ADVIPSERVICESK9-M),
Version 12.4(15)T1, RELEASE SOFTWARE (fc2)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2007 by Cisco Systems, Inc.
Compiled Wed 18-Jul-07 04:52 by pt_team
--- System Configuration Dialog ---
Continue with configuration dialog? [yes/no]: n
Press RETURN to get started!
Router>enable
Router#config terminal
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#interface fastEthernet 0/1
Router(config-if)#ip address 192.168.2.1 255.255.255.0
Router(config-if)#no shutdown
%LINK-5-CHANGED: Interface FastEthernet0/1, changed state to up
Router(config-if)#exit
Router(config)#interface fastEthernet 0/0
Router(config-if)#ip address 192.168.1.1 255.255.255.0
Router(config-if)#no shutdown
%LINK-5-CHANGED: Interface FastEthernet0/0, changed state to up
%LINEPROTO-5-UPDOWN: Line protocol on Interface FastEthernet0/0,
changed state to up
Router(config-if)#exit
Router(config)#interface Serial 0/0/0
Router(config-if)#ip address 192.168.4.1 255.255.255.0
Router(config-if)#no shutdown
%LINK-5-CHANGED: Interface Serial0/0/0, changed state to up
%LINEPROTO-5-UPDOWN: Line protocol on Interface Serial0/0/0,
changed state to up
Router(config-if)#exit
Router(config)#router rip
Router(config-router)#network 192.168.3.0
Router(config-router)#network 192.168.4.0
Router(config-router)#exit
Router(config)#exit
Router#
%SYS-5-CONFIG_I: Configured from console by console
Router#show ip protocols
Routing Protocol is "rip"
Sending updates every 30 seconds, next due in 19 seconds
Invalid after 180 seconds, hold down 180, flushed after 240
Outgoing update filter list for all interfaces is not set
Incoming update filter list for all interfaces is not set
Redistributing: rip
Default version control: send version 1, receive any version
Interface Send Recv Triggered RIP Key-chain
Serial0/0/0 1 2 1
Automatic network summarization is in effect
Maximum path: 4
Routing for Networks:
192.168.3.0
192.168.4.0
Passive Interface(s):
Routing Information Sources:
Gateway Distance Last Update
Distance: (default is 120)
Router#
Conclusion :-
Thus, we have simulate the WAN(RIP) network using packet
tracer/NS3.
======================
Grp B 4].
======================
/*-------------------------------------------------------------------------------------------------------
Group : B
Assignment no : 4
Title : Study and perform Linux networking commands emulation using Python or C++.
Batch :
Roll No :
-----------------------------------------------------------------------------------------------------------*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main ()
{
int ch;
do{
cout<<endl<<"menu" << endl;
cout<<endl<<"1.hostname" <<endl;
cout<<endl<<"2.ifconfig" <<endl;
cout<<endl<<"3.traceroute" << endl;
cout<<endl<<"4.nslookup" << endl;
cout<<endl<<"5.ping" << endl;
cout<<endl<<"6.exit" << endl;
cin>>ch;
switch(ch)
{
case 1: cout<<"\n";
system("hostname"); // Give hostname of machine
break;
case 2 :
system(" ifconfig"); //This will simply list all information on all network devices currently up.
break;
case 3 :
system("traceroute www.google.com "); // displays each host that a packet travels
break; //through as it tries to reach its destination
case 4 : system(" nslookup 64.57.102.34 "); //nslookup will translate a an IP address to domain name
break;
case 5 : system(" ping 192.168.1.67"); // Way to see if a machine is up and connected to the network
break;
case 6 : cout << "exit" << endl;
break;
default :
cout << "Invalid choice" << endl;
}
}while( ch!=5);
return 0;
}
/*----------------------------------------output-----------------------------------
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$g++ netcmd.cpp -o netcmd
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$./netcmd
menu
1.hostname
2.ifconfig
3.traceroute
4.nslookup
5.ping
6.exit
1
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC
menu
1.hostname
2.ifconfig
3.traceroute
4.nslookup
5.ping
6.exit
2
eth0 Link encap:Ethernet HWaddr b8:ac:6f:bc:72:27
inet addr:192.168.1.66 Bcast:192.168.255.255 Mask:255.255.0.0
inet6 addr: fe80::baac:6fff:febc:7227/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:6034 errors:0 dropped:0 overruns:0 frame:0
TX packets:118 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:414448 (414.4 KB) TX bytes:15201 (15.2 KB)
Interrupt:18
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:161 errors:0 dropped:0 overruns:0 frame:0
TX packets:161 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:11399 (11.3 KB) TX bytes:11399 (11.3 KB)
vmnet1 Link encap:Ethernet HWaddr 00:50:56:c0:00:01
inet addr:172.16.170.1 Bcast:172.16.170.255 Mask:255.255.255.0
inet6 addr: fe80::250:56ff:fec0:1/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:90 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
vmnet8 Link encap:Ethernet HWaddr 00:50:56:c0:00:08
inet addr:172.16.201.1 Bcast:172.16.201.255 Mask:255.255.255.0
inet6 addr: fe80::250:56ff:fec0:8/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:88 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
menu
1.hostname
2.ifconfig
3.traceroute
4.nslookup
5.ping
6.exit
3
traceroute to www.google.com (216.58.220.36), 30 hops max, 60 byte packets
1 192.168.1.100 (192.168.1.100) 0.317 ms 0.314 ms 0.319 ms
2 * * *
3 10.81.252.78 (10.81.252.78) 2.749 ms 4.106 ms 4.103 ms
4 117.211.127.42 (117.211.127.42) 28.052 ms 28.056 ms 29.007 ms
5 218.248.181.22 (218.248.181.22) 30.000 ms 29.995 ms 28.721 ms
6 74.125.48.138 (74.125.48.138) 79.174 ms 77.384 ms 77.524 ms
7 209.85.241.52 (209.85.241.52) 42.569 ms 42.534 ms 42.550 ms
8 209.85.251.95 (209.85.251.95) 42.532 ms 42.511 ms 216.239.50.171 (216.239.50.171) 49.745 ms
9 209.85.255.43 (209.85.255.43) 49.714 ms 49.712 ms 50.172 ms
10 maa03s18-in-f4.1e100.net (216.58.220.36) 42.786 ms 46.926 ms 42.384 ms
menu
1.hostname
2.ifconfig
3.traceroute
4.nslookup
5.ping
6.exit
4
Server: 127.0.1.1
Address: 127.0.1.1#53
Non-authoritative answer:
34.102.57.64.in-addr.arpa name = slackware.com.
Authoritative answers can be found from:
menu
1.hostname
2.ifconfig
3.traceroute
4.nslookup
5.ping
6.exit
5
PING 192.168.1.67 (192.168.1.67) 56(84) bytes of data.
64 bytes from 192.168.1.67: icmp_seq=1 ttl=64 time=0.228 ms
64 bytes from 192.168.1.67: icmp_seq=2 ttl=64 time=0.128 ms
64 bytes from 192.168.1.67: icmp_seq=3 ttl=64 time=0.107 ms
64 bytes from 192.168.1.67: icmp_seq=4 ttl=64 time=0.140 ms
64 bytes from 192.168.1.67: icmp_seq=5 ttl=64 time=0.126 ms
64 bytes from 192.168.1.67: icmp_seq=6 ttl=64 time=0.130 ms
64 bytes from 192.168.1.67: icmp_seq=7 ttl=64 time=0.136 ms
64 bytes from 192.168.1.67: icmp_seq=8 ttl=64 time=0.134 ms
64 bytes from 192.168.1.67: icmp_seq=9 ttl=64 time=0.136 ms
64 bytes from 192.168.1.67: icmp_seq=10 ttl=64 time=0.124 ms
64 bytes from 192.168.1.67: icmp_seq=11 ttl=64 time=0.128 ms
64 bytes from 192.168.1.67: icmp_seq=12 ttl=64 time=0.105 ms
64 bytes from 192.168.1.67: icmp_seq=13 ttl=64 time=0.128 ms
^Z
[1]+ Stopped ./4
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$
*/
======================
Grp B 5].
======================
#---------------------------------------------------------------------------#
Group B
Assignment 05
Aim:Write FTP/Telnet program using socket programming for TCP using C++
Roll_No:
#--------------------------------------------------------------------------#
//FTPSERVER
import java.net.*;
import java.io.*;
import java.util.*;
public class FTPServer
{
public static void main(String args[]) throws Exception
{
ServerSocket soc=new ServerSocket(5217);
System.out.println("FTP Server Started on Port Number 5217");
while(true)
{
System.out.println("Waiting for Connection ...");
transferfile t=new transferfile(soc.accept());
}
}
}
class transferfile extends Thread
{
Socket ClientSoc;
DataInputStream din;
DataOutputStream dout;
transferfile(Socket soc)
{
try
{
ClientSoc=soc;
din=new DataInputStream(ClientSoc.getInputStream());
dout=new DataOutputStream(ClientSoc.getOutputStream());
System.out.println("FTP Client Connected ...");
start();
}
catch(Exception ex)
{
}
}
void SendFile() throws Exception
{
String filename=din.readUTF();
File f=new File(filename);
if(!f.exists())
{
dout.writeUTF("File Not Found");
return;
}
else
{
dout.writeUTF("READY");
FileInputStream fin=new FileInputStream(f);
int ch;
do
{
ch=fin.read();
dout.writeUTF(String.valueOf(ch));
}
while(ch!=-1);
fin.close();
dout.writeUTF("File Receive Successfully");
}
}
void ReceiveFile() throws Exception
{
String filename=din.readUTF();
if(filename.compareTo("File not found")==0)
{
return;
}
File f=new File(filename);
String option;
if(f.exists())
{
dout.writeUTF("File Already Exists");
option=din.readUTF();
}
else
{
dout.writeUTF("SendFile");
option="Y";
}
if(option.compareTo("Y")==0)
{
FileOutputStream fout=new FileOutputStream(f);
int ch;
String temp;
do
{
temp=din.readUTF();
ch=Integer.parseInt(temp);
if(ch!=-1)
{
fout.write(ch);
}
}while(ch!=-1);
fout.close();
dout.writeUTF("File Send Successfully");
}
else
{
return;
}
}
public void run()
{
while(true)
{
try
{
System.out.println("Waiting for Command ...");
String Command=din.readUTF();
if(Command.compareTo("GET")==0)
{
System.out.println("\tGET Command Received ...");
SendFile();
continue;
}
else if(Command.compareTo("SEND")==0)
{
System.out.println("\tSEND Command Receiced ...");
ReceiveFile();
continue;
}
else if(Command.compareTo("DISCONNECT")==0)
{
System.out.println("\tDisconnect Command Received ...");
System.exit(1);
}
}
catch(Exception ex)
{
}
}
}
}
___________________________________________________________________
OUTPUT
___________________________________________________________________
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$javac FTPServer.java
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$java FTPServer
FTP Server Started on Port Number 5217
Waiting for Connection ...
FTP Client Connected ...
Waiting for Connection ...
Waiting for Command ...
SEND Command Receiced ...
Waiting for Command ...
GET Command Received ...
Waiting for Command ...
Disconnect Command Received ...
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$
//FTPCLIENT
import java.net.*;
import java.io.*;
import java.util.*;
class FTPClient
{
public static void main(String args[]) throws Exception
{
Socket soc=new Socket("127.0.0.1",5217);
transferfileClient t=new transferfileClient(soc);
t.displayMenu();
}
}
class transferfileClient
{
Socket ClientSoc;
DataInputStream din;
DataOutputStream dout;
BufferedReader br;
transferfileClient(Socket soc)
{
try
{
ClientSoc=soc;
din=new DataInputStream(ClientSoc.getInputStream());
dout=new DataOutputStream(ClientSoc.getOutputStream());
br=new BufferedReader(new InputStreamReader(System.in));
}
catch(Exception ex)
{
}
}
void SendFile() throws Exception
{
String filename;
System.out.print("Enter File Name :");
filename=br.readLine();
File f=new File(filename);
if(!f.exists())
{
System.out.println("File not Exists...");
dout.writeUTF("File not found");
return;
}
dout.writeUTF(filename);
String msgFromServer=din.readUTF();
if(msgFromServer.compareTo("File Already Exists")==0)
{
String Option;
System.out.println("File Already Exists. Want to OverWrite (Y/N) ?");
Option=br.readLine();
if(Option=="Y")
{
dout.writeUTF("Y");
}
else
{
dout.writeUTF("N");
return;
}
}
System.out.println("Sending File ...");
FileInputStream fin=new FileInputStream(f);
int ch;
do
{
ch=fin.read();
dout.writeUTF(String.valueOf(ch));
}
while(ch!=-1);
fin.close();
System.out.println(din.readUTF());
}
void ReceiveFile() throws Exception
{
String fileName;
System.out.print("Enter File Name :");
fileName=br.readLine();
dout.writeUTF(fileName);
String msgFromServer=din.readUTF();
if(msgFromServer.compareTo("File Not Found")==0)
{
System.out.println("File not found on Server ...");
return;
}
else if(msgFromServer.compareTo("READY")==0)
{
System.out.println("Receiving File ...");
File f=new File(fileName);
if(f.exists())
{
String Option;
System.out.println("File Already Exists. Want to OverWrite (Y/N) ?");
Option=br.readLine();
if(Option=="N")
{
dout.flush();
return;
}
}
FileOutputStream fout=new FileOutputStream(f);
int ch;
String temp;
do
{
temp=din.readUTF();
ch=Integer.parseInt(temp);
if(ch!=-1)
{
fout.write(ch);
}
}while(ch!=-1);
fout.close();
System.out.println(din.readUTF());
}
}
public void displayMenu() throws Exception
{
while(true)
{
System.out.println("[ MENU ]");
System.out.println("1. Send File");
System.out.println("2. Receive File");
System.out.println("3. Exit");
System.out.print("\nEnter Choice :");
int choice;
choice=Integer.parseInt(br.readLine());
if(choice==1)
{
dout.writeUTF("SEND");
SendFile();
}
else if(choice==2)
{
dout.writeUTF("GET");
ReceiveFile();
}
else
{
dout.writeUTF("DISCONNECT");
System.exit(1);
}
}
}
}
___________________________________________________
OUTPUT
___________________________________________________
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$ javac FTPClient.java
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$ java FTPClient
[ MENU ]
1. Send File
2. Receive File
3. Exit
Enter Choice :1
Enter File Name :file1.txt
Sending File ...
File Send Successfully
[ MENU ]
1. Send File
2. Receive File
3. Exit
Enter Choice :2
Enter File Name :file2.txt
Receiving File ...
File Receive Successfully
[ MENU ]
1. Send File
2. Receive File
3. Exit
Enter Choice :3
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$
======================
Grp B 6].
======================
/*================================================================
Assignment No.B-6
Title :Write TFTP
program using socket
programming for UDP
using C++
Batch :
Roll no:-
=============================================================*/
//Server side
Input:
import java.io.*;
import java.net.*;
class TFTPServer
{
public static void main(String args[]) throws
Exception
{
DatagramSocket serverSocket = new
DatagramSocket(5000);
File toSend = new
File("toSend.txt");
byte[] sendData = new byte[1024];
byte[] receiveData = new
byte[1024];
FileInputStream fis = new
FileInputStream(toSend);
BufferedInputStream bis = new
BufferedInputStream(fis);
bis.read(sendData,0,(int)toSend.length());
while(true)
{
DatagramPacket receivePacket
=
new
DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
InetAddress IPAddress =
receivePacket.getAddress();
int port =
receivePacket.getPort();
DatagramPacket sendPacket =
new
DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
Input File:
toSend.txt
Contents of file:
Hello... PVGCOE...
OUTPUT:
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$
cd Desktop/server/
gescoe@gescoe-Vostro-230:~/Desktop/server$
javac
TFTPServer.java
gescoe@gescoe-Vostro-230:~/Desktop/server$
java
TFTPServer
//Client side
Input:
import java.io.*;
import java.net.*;
class TFTPClient
{
public static void main(String args[])
throws
Exception
{
File toReceive = new
File("received.txt");
FileOutputStream fos = new
FileOutputStream(toReceive);
BufferedOutputStream bos = new
BufferedOutputStream(fos);
DatagramSocket clientSocket = new
DatagramSocket();
InetAddress IPAddress =
InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
DatagramPacket sendPacket = new
DatagramPacket(sendData,
sendData.length, IPAddress, 5000);
DatagramPacket receivePacket = new
DatagramPacket(receiveData,
receiveData.length);
clientSocket.send(sendPacket);
clientSocket.receive(receivePacket);
receiveData =
receivePacket.getData();
String sent = new String(receiveData);
fos.write(receiveData,0,sent.length());
System.out.println("File received
from server, with the
contents:\n"+sent);
}
}
Outsput file:
received.txt
Contents of file:
Hello... PVGCOE...
Output:
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$
javac TFTPClient.java
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$
java TFTPClient
File received from
server, with the contents:
Hello... PVGCOE...
======================
Grp B 9].
======================
/*=======================================================================
Assignment :- B-9
Title :- Implementation of
Concurrent Text Conferencing application using Python or Java.
Roll No :-
=======================================================================*/
/* Server */
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.ArrayList;
public class Main
{
public static void main(String[] args) throws IOException
{
try
{
final int PORT = 5677; //SET NEW CONSTANT VARIABLE: PORT
ServerSocket server = new ServerSocket(PORT); //SET PORT NUMBER
System.out.println("Waiting for clients..."); //AT THE
START PRINT THIS
while (true)//WHILE THE PROGRAM IS RUNNING
{
Socket s = server.accept(); //ACCEPT SOCKETS(CLIENTS) TRYING TO
CONNECT
System.out.println("Client connected from " +
s.getLocalAddress()
.getHostName()); // TELL THEM THAT THE CLIENT CONNECTED
Client chat = new Client(s); //CREATE A NEW CLIENT OBJECT
Thread t = new Thread(chat); //MAKE A NEW THREAD
t.start(); //START THE THREAD
}
}
catch (Exception e)
{
System.out.println("An error occured."); //IF AN ERROR
OCCURED THEN PRINT IT
e.printStackTrace();
}
}
}
/* Client */
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class Client implements Runnable
{
private Socket socket; //SOCKET INSTANCE VARIABLE
public Client(Socket s)
{
socket = s; //INSTANTIATE THE SOCKET
}
@Override
public void run() //(IMPLEMENTED FROM THE RUNNABLE INTERFACE)
{
try //HAVE TO HAVE THIS FOR THE in AND out VARIABLES
{
Scanner in = new Scanner(socket.getInputStream());
//GET THE SOCKETS INPUT STREAM (THE STREAM THAT YOU
WILL GET WHAT THEY TYPE FROM)
PrintWriter out = new PrintWriter(socket.
getOutputStream());
//GET THE SOCKETS OUTPUT STREAM (THE STREAM YOU WILL SEND
INFORMATION TO THEM FROM)
while (true)//WHILE THE PROGRAM IS RUNNING
{
if (in.hasNext())
{
String input = in.nextLine();
//IF THERE IS INPUT THEN MAKE A NEW VARIABLE input AND READ WHAT
THEY TYPED
System.out.println("Client Said: " + input)
//PRINT IT OUT TO THE SCREEN
out.println("You Said: " + input);
//RESEND IT TO THE CLIENT
out.flush(); //FLUSH THE STREAM
}
}
}
catch (Exception e)
{
e.printStackTrace();
//MOST LIKELY THERE WONT BE AN ERROR BUT ITS GOOD TO CATCH
}
}
}
/* OUTPUT
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$javac Main.java
Client.java
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$java Main Client
Waiting for clients...
Client connected from localhost
Client Said: hii
hi
Client Said: hello
Client Said: assignment 3
*/
======================
Grp B 10].
======================
*================================================================
Assignment No.B(10)
Title :Implementation of
Concurrent Proxy server
program using
Python or Java.
Roll No. :
Batch :
=============================================================*/
import select
import socket
import sys
import os
import fcntl
import logging
USAGE = "usage:
python simpleproxy.py
proxyhost:proxyport
desthost:destport"
class
ProxyConnection(object):
# enable a buffer on connections with this
many bytes
MAX_BUFFER_SIZE = 1024
# ProxyConnection class forwards data
between a client and a
destination socket
def
__init__(self,proxyserver,listensock,servaddr):
self.proxyserver = proxyserver
self.servaddr = servaddr # the server
address
#
open client and server sockets
self.clisock, self.cliaddr =
listensock.accept() #
client socket and address
self.clisock.setblocking(0)
self.servsock =
socket.socket(socket.AF_INET,
socket.SOCK_STREAM) # server socket
self.servsock.setblocking(0)
# buffers for data recieved from a
socket
self.buffers = { self.clisock:bytes(),
self.servsock:bytes()
}
self.connected = False # is the
server socket connected
yet
# register sockets with server and
enable read operations
self.proxyserver.registerSocket(self.clisock,self)
self.proxyserver.registerSocket(self.servsock,self)
self.proxyserver.activateRead(self.clisock)
self.proxyserver.activateRead(self.servsock)
# return the socket on the "other
end"
of the connection
def other(self,socket):
if socket == self.clisock:
return self.servsock
else:
return self.clisock
# connect to the server connection
def connect(self):
# have to use socket's connect_ex
because the connect is
asynchronous and won't suceed immediately
self.servsock.connect_ex(self.servaddr)
# read data in from a socket
def readfrom(self,s):
# is the connection being opened by the
server responding to the
connect?
if s == self.servsock and not
self.connected:
self.proxyserver.connection_count
+=
1
logging.getLogger("simpleproxy")
\
.info("opened connection
from %s, connection
count now
%d"%(str(self.cliaddr),self.proxyserver.connection_count))
self.connected = True
return
# read from the socket
capacity =
ProxyConnection.MAX_BUFFER_SIZE
- len(self.buffers[s])
try:
data = s.recv(capacity)
except Exception as ex:
data = ""
# if the read failed, close the socket
(this happens when the
client or server closes the connection)
if len(data) == 0:
self.close()
return
# buffer the read data
self.buffers[s] += data
self.proxyserver.activateWrite(self.other(s))
# disable further reads if buffer is
full
capacity -= len(data)
if capacity <= 0:
self.proxyserver.deactivateRead(s)
# write data out to a socket
def writeto(self,s):
# get the buffer containing data to be
read
buf = self.buffers[self.other(s)]
# write it to the socket
written = s.send(buf)
# remove written data from the buffer
buf = buf[written:]
self.buffers[self.other(s)] = buf
# disable further writes if the buffer
is empty
if len(buf) == 0:
self.proxyserver.deactivateWrite(s)
# enable reads if data was written
if written:
self.proxyserver.activateRead(self.other(s))
# close the connection sockets
def close(self):
for sock in
[self.clisock,self.servsock]:
if sock:
self.proxyserver.deactivateRead(sock)
self.proxyserver.deactivateWrite(sock)
sock.close()
self.proxyserver.unregisterSocket(sock,self)
self.proxyserver.connection_count -= 1
logging.getLogger("simpleproxy")
\
.info("closed connection
from %s, connection
count now
%d"%(self.cliaddr,self.proxyserver.connection_count))
class
ProxyServer(object):
def
__init__(self,host,port,serverhost,serverport):
self.address = (host,port)
self.server = (serverhost,serverport)
self.listensock =
socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
self.listensock.setsockopt(socket.SOL_SOCKET,
socket.SO_REUSEADDR,
1)
self.listensock.bind(self.address)
self.listensock.listen(5)
self.connections = {} #
map from a socket to a
ProxyConnection
self.readsockets = [] #
all sockets which can be
read
self.writesockets = [] #
all sockets which can be
written
self.allsockets = [self.listensock] #
all opened sockets
self.connection_count = 0 #
count of all active
connections
def run(self):
loop = 0
while True:
# block until there is some
activity
on one of the sockets,
timeout every 60 seconds by default
r, w, e = select.select(
[self.listensock]+self.readsockets,
self.writesockets,
self.allsockets,
60)
loop += 1
# handle any reads
for s in r:
if s is self.listensock:
# open a new connection
self.open()
else:
if s in self.connections:
self.connections[s].readfrom(s)
# handle any writes
for s in w:
if s in self.connections:
self.connections[s].writeto(s)
# handle errors (close connections)
for s in e:
if s in self.connections:
self.connections[s].close()
self.sock.close()
self.sock = None
def activateRead(self,sock):
if not sock in self.readsockets:
self.readsockets.append(sock)
def deactivateRead(self,sock):
if sock in self.readsockets:
self.readsockets.remove(sock)
def activateWrite(self,sock):
if not sock in self.writesockets:
self.writesockets.append(sock)
def deactivateWrite(self,sock):
if sock in self.writesockets:
self.writesockets.remove(sock)
def registerSocket(self,sock,conn):
self.connections[sock] = conn
self.allsockets.append(sock)
def unregisterSocket(self,sock,conn):
del self.connections[sock]
self.allsockets.remove(sock)
# open a new proxy connection from the
listening socket
def open(self):
conn =
ProxyConnection(self,self.listensock,self.server)
conn.connect()
if __name__ ==
'__main__':
try:
proxy =
sys.argv[1].split(":")
dest = sys.argv[2].split(":")
proxyhost = proxy[0]
proxyport = int(proxy[1])
serverhost = dest[0]
serverport = int(dest[1])
except:
print(USAGE)
sys.exit(-1)
logger = logging.getLogger('simpleproxy')
logger.setLevel(logging.INFO)
hdlr = logging.StreamHandler()
hdlr.setLevel(logging.INFO)
hdlr.setFormatter(logging.Formatter('%(asctime)s
- %(name)s -
%(levelname)s -
%(message)s'))
logger.addHandler(hdlr)
server =
ProxyServer(proxyhost,proxyport,serverhost,serverport)
server.run()
OUTPUT:
Server:
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$python
simpleproxy.py
localhost:8080 localhost:23
2015-03-19 14:07:18,155
- simpleproxy - INFO -
opened connection from
('127.0.0.1', 44167), connection count now 1
2015-03-19 14:08:00,242
- simpleproxy - INFO -
closed connection from
('127.0.0.1', 44167), connection count now 0
Client:
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$
telnet localhost
8080
Trying 127.0.0.1...
Connected to localhost.
Escape character is
'^]'.
Ubuntu 14.04 LTS
gescoe-Vostro-230 login:
gescoe
Password:
Last login: Thu Mar 19
14:06:11 IST 2015 from
localhost on pts/23
Welcome to Ubuntu 14.04
LTS (GNU/Linux
3.13.0-24-generic
x86_64)
* Documentation: https://help.ubuntu.com/
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$
exit
logout
Connection closed by
foreign host.
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$
======================
Grp B 11].
======================
*================================================================
Assignment No.B(11)
Title :Implementation of
Multithreaded web server. Check the functionality of web server in
LAN and through the ADSL
router using NAT.
Roll No. :
Batch :
=============================================================*/
//Server2.java
import java.io.*;
import java.net.*;
public class Server2 {
public static void
main(String args[]) {
int port = 6789;
Server2 server = new
Server2( port );
server.startServer();
}
// declare a server
socket and a client socket for the server;
// declare the number of
connections
ServerSocket echoServer
= null;
Socket clientSocket =
null;
int numConnections = 0;
int port;
public Server2( int port
) {
this.port = port;
}
public void stopServer()
{
System.out.println(
"Server cleaning up." );
System.exit(0);
}
public void
startServer() {
// Try to open a server
socket on the given port
// Note that we can't
choose a port less than 1024 if we are not
// privileged users
(root)
try {
echoServer = new
ServerSocket(port);
}
catch (IOException e) {
System.out.println(e);
}
System.out.println(
"Server is started and is waiting for connections." );
System.out.println(
"With multi-threading, multiple connections are allowed." );
System.out.println(
"Any client can send -1 to stop the server." );
// Whenever a connection
is received, start a new thread to process the connection
// and wait for the next
connection.
while ( true ) {
try {
clientSocket =
echoServer.accept();
numConnections ++;
Server2Connection
oneconnection = new Server2Connection(clientSocket, numConnections, this);
new
Thread(oneconnection).start();
}
catch (IOException e) {
System.out.println(e);
}
}
}
}
class Server2Connection
implements Runnable {
BufferedReader is;
PrintStream os;
Socket clientSocket;
int id;
Server2 server;
public Server2Connection(Socket
clientSocket, int id, Server2 server) {
this.clientSocket =
clientSocket;
this.id = id;
this.server = server;
System.out.println(
"Connection " + id + " established with: " + clientSocket
);
try {
is = new
BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
os = new
PrintStream(clientSocket.getOutputStream());
} catch (IOException e)
{
System.out.println(e);
}
}
public void run() {
String line;
try {
boolean serverStop =
false;
while (true) {
line = is.readLine();
System.out.println(
"Received " + line + " from Connection " + id +
"." );
int n =
Integer.parseInt(line);
if ( n == -1 ) {
serverStop = true;
break;
}
if ( n == 0 ) break;
os.println(""
+ n*n );
}
System.out.println(
"Connection " + id + " closed." );
is.close();
os.close();
clientSocket.close();
if ( serverStop )
server.stopServer();
} catch (IOException e)
{
System.out.println(e);
}
}
}
//Client.java
import java.io.*;
import java.net.*;
public class Client {
public static void
main(String[] args) {
String hostname =
"192.168.1.81";
int port = 6789;
// declaration section:
// clientSocket: our
client socket
// os: output stream
// is: input stream
Socket clientSocket =
null;
DataOutputStream os =
null;
BufferedReader is =
null;
// Initialization
section:
// Try to open a socket
on the given port
// Try to open input and
output streams
try {
clientSocket = new
Socket(hostname, port);
os = new
DataOutputStream(clientSocket.getOutputStream());
is = new
BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch
(UnknownHostException e) {
System.err.println("Don't
know about host: " + hostname);
} catch (IOException e)
{
System.err.println("Couldn't
get I/O for the connection to: " + hostname);
}
// If everything has
been initialized then we want to write some data
// to the socket we have
opened a connection to on the given port
if (clientSocket == null
|| os == null || is == null) {
System.err.println(
"Something is wrong. One variable is null." );
return;
}
try {
while ( true ) {
System.out.print(
"Enter an integer (0 to stop connection, -1 to stop server): " );
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
String keyboardInput =
br.readLine();
os.writeBytes(
keyboardInput + "\n" );
int n =
Integer.parseInt( keyboardInput );
if ( n == 0 || n == -1 )
{
break;
}
String responseLine =
is.readLine();
System.out.println("Server
returns its square as: " + responseLine);
}
// clean up:
// close the output
stream
// close the input
stream
// close the socket
os.close();
is.close();
clientSocket.close();
} catch
(UnknownHostException e) {
System.err.println("Trying
to connect to unknown host: " + e);
} catch (IOException e)
{
System.err.println("IOException:
" + e);
}
}
}
OUTPUT:-
ON SERVER:
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$
cd Desktop/kd
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~/Desktop/kd$
javac Server2.java
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~/Desktop/kd$
java Server2
Server is started and is
waiting for connections.
With multi-threading,
multiple connections are allowed.
Any client can send -1
to stop the server.
Connection 1 established
with: Socket[addr=/192.168.1.80,port=43452,localport=6789]
Received 5 from
Connection 1.
Received 2 from
Connection 1.
Connection 2 established
with: Socket[addr=/192.168.1.74,port=33825,localport=6789]
Received 2 from Connection
2.
Connection 3 established
with: Socket[addr=/192.168.1.79,port=60690,localport=6789]
Received 654 from
Connection 3.
Received -1 from
Connection 1.
Connection 1 closed.
Server cleaning up.
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~/Desktop/kd$
Client 1
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$
cd Desktop/
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$javac
Client.java
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$java
Client
Enter an integer (0 to
stop connection, -1 to stop server): 5
Server returns its
square as: 25
Enter an integer (0 to
stop connection, -1 to stop server): 2
Server returns its
square as: 4
Enter an integer (0 to
stop connection, -1 to stop server): -1
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$
Client 2
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$
cd Desktop/
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$javac
Client.java
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$java
Client
Enter an integer (0 to
stop connection, -1 to stop server): 2
Server returns its
square as: 4
Enter an integer (0 to
stop connection, -1 to stop server): 9
Server returns its
square as: null
Enter an integer (0 to
stop connection, -1 to stop server):
Client 3
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$
cd Desktop/
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$
javac Client.java
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$
java Client
Enter an integer (0 to
stop connection, -1 to stop server): 654
Server returns its
square as: 427716
Enter an integer (0 to
stop connection, -1 to stop server): 5
Server returns its
square as: null
Enter an integer (0 to
stop connection, -1 to stop server):
======================
Grp B 12].
======================
*================================================================
Assignment No.B(12)
Title :Implement a
program for remote print manager to print documents on remote printer. (IP
based printer) using
Python
Roll No. :
Batch :
=============================================================*/
#manager demo.py
from multiprocessing
import Process, Queue, managers
from
multiprocessing.managers import SyncManager
import time
class MyObject():
def __init__( self, p, f
):
self.parameter = p
self.processor_function
= f
class MyServer():
def __init__(self,
server_info, obj):
print '=== Launching
Server ... ====='
(ip, port, pw) =
server_info
self.object = obj
#Parameters for task processing
#Define queues
self._process_queue =
Queue() #Queue of tasks to be processed
self._results_queue =
Queue() #Queue of processed tasks to be stored
#Set up IS_Manager class
and register server functions
class
IS_Manager(managers.BaseManager): pass
IS_Manager.register('get_processQ',
callable=self.get_process_queue)
IS_Manager.register('get_resultsQ',
callable=self.get_results_queue)
IS_Manager.register('get_object',
callable=self.get_object)
#Initialize manager and
server
self.manager =
IS_Manager(address=(ip, port), authkey=pw)
self.server =
self.manager.get_server()
self.server_process =
Process( target=self.server.serve_forever )
self.server_process.start()
def
get_process_queue(self): return self._process_queue
def
get_results_queue(self): return self._results_queue
def get_object(self):
return self.object
def runUntilDone(self,
task_list):
#Fill the initial queue
for t in task_list:
self._process_queue.put(t)
#Main loop
total_tasks =
len(task_list)
while not
self._results_queue.qsize()==total_tasks:
time.sleep(.5)
print
self._process_queue.qsize(), '\t', self._results_queue.qsize()
if not
self._results_queue.empty():
print '\t',
self._results_queue.get()
#Do stuff
pass
class MyClient():
def __init__(self,
server_info):
(ip, port, pw) =
server_info
print '=== Launching
Client ... ====='
class IS_Manager(managers.BaseManager):
pass
IS_Manager.register('get_processQ')
IS_Manager.register('get_resultsQ')
IS_Manager.register('get_object')
#Set up manager, pool
print '\tConnecting to
server...'
manager =
IS_Manager(address=(ip, port), authkey=pw)
manager.connect()
self._process_queue =
manager.get_processQ()
self._results_queue =
manager.get_resultsQ()
self.object =
manager.get_object()
print '\tConnected.'
def
runUntilDone(self):#, parameters):
print 'Starting client
main loop...'
#Main loop
while 1:
if self._process_queue.empty():
print 'I\'m bored here!'
time.sleep(.5)
else:
task =
self._process_queue.get()
print task, '\t',
self.object.processor_function( task, self.object.parameter )
print 'Client process is
quitting. Bye!'
self._clients_queue.get()
======================
Grp B 13].
======================
/*========================================================
Assignment No.B(13)
Title :Implementation of
sliding window protocol using C++.
Roll No. :
Batch :
=========================================================*/
#include<iostream>
using namespace std;
int main()
{
char sender[50],
receiver[50];
int i,winsize;
cout<<"\n
ENTER THE WINDOWS SIZE : ";
cin>> winsize;
cout<<"\n
SENDER WINDOW IS EXPANDED TO STORE MESSAGE OR
WINDOW";
cout<<"\n
ENTER THE DATA TO BE SENT: ";
cin>>sender;
for(i=0;i<winsize;i++)
receiver[i] = sender[i];
receiver[i] = NULL;
cout<<"\n
MESSAGE SEND BY THE SENDER:\n";
cout<<sender;
cout<<"\n
WINDOW SIZE OF RECEIVER IS EXPANDED\n";
cout<<"\n
ACKNOWLEDGEMENT FROM RECEIVER \n";
for(i=0;i<winsize;i++);
cout<<"\n
ACK:"<<i;
cout<<"\n
MESSAGE RECEIVED BY RECEIVER IS : ";
cout<<receiver;
cout<<"\n
WINDOW SIZE OF RECEIVER IS SHRINKED \n";
return 0;
}
output;-
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$
cd Desktop/
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$g++
p.cpp -o p
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$./p
ENTER THE WINDOWS SIZE :
3
SENDER WINDOW IS
EXPANDED TO STORE MESSAGE OR WINDOW
ENTER THE DATA TO BE
SENT: hello
MESSAGE SEND BY THE
SENDER:
hello
WINDOW SIZE OF RECEIVER
IS EXPANDED
ACKNOWLEDGEMENT FROM
RECEIVER
ACK:3
MESSAGE RECEIVED BY
RECEIVER IS : hel
WINDOW SIZE OF RECEIVER
IS SHRINKED
======================
Grp B 14].
======================
/*========================================================
Assignment No.B(14)
Title : Implementation
of distance vector routing algorithm using C++
Roll No. :
Batch :
=========================================================*/
#include<stdio.h>
struct node
{
unsigned dist[20];
unsigned from[20];
}rt[10];
int main()
{
int dmat[20][20];
int n,i,j,k,count=0;
printf("\nEnter the
number of nodes : ");
scanf("%d",&n);
printf("\nEnter the
cost matrix :\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
scanf("%d",&dmat[i][j]);
dmat[i][i]=0;
rt[i].dist[j]=dmat[i][j];
rt[i].from[j]=j;
}
do
{
count=0;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
for(k=0;k<n;k++)
if(rt[i].dist[j]>dmat[i][k]+rt[k].dist[j])
{
rt[i].dist[j]=rt[i].dist[k]+rt[k].dist[j];
rt[i].from[j]=k;
count++;
}
}while(count!=0);
for(i=0;i<n;i++)
{
printf("\n\nState
value for router %d is \n",i+1);
for(j=0;j<n;j++)
{
printf("\t\nnode %d
via %d Distance%d",j+1,rt[i].from[j]+1,rt[i].dist[j]);
}
}
printf("\n\n");
}
Output:-
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$
cd Desktop
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$g++
router.cpp -o router
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$./router
Enter the number of
nodes : 4
Enter the cost matrix :
3 7 4 9
1 5 2 7
6 7 3 7
1 5 3 2
State value for router 1
is
node 1 via 1 Distance0
node 2 via 2 Distance7
node 3 via 3 Distance4
node 4 via 4 Distance9
State value for router 2
is
node 1 via 1 Distance1
node 2 via 2 Distance0
node 3 via 3 Distance2
node 4 via 4 Distance7
State value for router 3
is
node 1 via 1 Distance6
node 2 via 2 Distance7
node 3 via 3 Distance0
node 4 via 4 Distance7
State value for router 4
is
node 1 via 1 Distance1
node 2 via 2 Distance5
node 3 via 3 Distance3
node 4 via 4 Distance0
======================
Grp B 16].
======================
\*----------------------------------------------------------------------------------------------------------------------
Assignment :- B-16
Title :- Configure and setup network with optical router.
Roll_No. :-
------------------------------------------------------------------------------------------------------------------------*/
Title :-
Configure and setup network
with optical router.
Pre-requisites :-
·
D-Link Router.
·
Lan Connectivity.
Objective :-
To Setting up the network with optical router.
Index Terms :-
Optical Router :-
Optical Routing is a novel method of creating transparent optical
connections between network nodes using a flow-based approach. An IP flow is a
collection of IP packets going from the same source to
the same destination: the exchange of IP packets is the mechanism that allows
the transport of information over the Internet.
Currently a packet has to traverse a certain number of routers,
before reaching its destination and the network routers must analyze each
packet and forward it towards the direction of the destination node. However
since a flow is defined as a sequence of packets going from the same source to
the same destination, if the router recognises the flow it could create a
short-cut by creating a “switched” connection allowing all the packets
belonging to the same IP flow to proceed directly towards the correct direction
without being analyzed one after the other. This general idea is known as IP
switching.
If the shortcut however occurs at an optical level, the process
becomes Optical IP Switching. The advantage of OIS comes from the fact that
today packets are transmitted optically between two points but at each routing
station they have
to be converted into electrical signal, routed and converted back
into optical to
continue their travel over the optical fiber. If instead the
router is able to recognise a flow, it could create a shortcut (“cut-through
connection”) directly at the optical level, and all the packets belonging to
the same flow could be directed to the right destination without the
optical-to-electrical conversion process. This would save time, energy, memory
and processing resources on the router.
A basic implementation of the OIS concept sees an optical router
that monitors IP traffic and if a flow appears with specific characteristics
the router establishes an optical cut-through path between its upstream and
downstream neighbours, requesting the upstream node to place all the packets
belonging to the flow into the new path. The newly generated trail bypasses the
IP layer of the router, as the packets transparently flow from the upstream to
the downstream neighbour. Following a similar procedure the path can then be
extended to more than three nodes, but this decision is always autonomously
taken by each router and depends on the traffic encountered and on the
resources locally available. Since an optical link however can carry several
gigabits of data per second, it may be difficult
to find a flow that alone can exploit the bandwidth offered by an
optical trail. For this reason, aggregating more IP flows into the same
dedicated path is essential for the performance of an OIS network. The
aggregation introduces a trade-off between the number of IP flows that can be
aggregated together and the length of the optical trail that accommodates them.
In order to achieve good performance only optical flows sharing a significant
amount of network hops should be aggregated into the same path. A core node
implementing optical IP switching must be endowed with electrical processing
and memory resources (as a standard IP router), a variable number of optical
transceivers and an optical switching element (usually a MEMS based device). An edge node instead
does not need an optical switching device because it could only function as
source or destination of the optical flow.
The control protocol nearest to OIS is probably GMPLS, which is being standardized by the IETF. GMPLS aims at creating end-to-end
connections after an explicit request from a customer or a network engineering
service. This constitutes the main difference with OIS where the optical trials
are automatically triggered by the encountered traffic; they are initially
generated between three adjacent nodes, and then extended following a
distributed decision.
Nowadays, wireless networks are widely applied in
workplace or at home. It does bring a lot of convenience in internet access.
However, it’s a little bit tricky to set up a wireless network, particularly
for someone who does this for the first time. This article provides
instructions on how to setup a wireless environment. This instruction is based
on D-Link that is a portable and stable wireless router.
Step :- 1
Get to know your router.
·
LAN ports (1-4): connect devices such as computers.
·
Internet port: connect cable or DSL modem.
·
USB: can be used to connect a USB flash drive.
·
Reset button: restore the router to its default settings.
·
Power receptor port: connect supplied power adapter.
Step :- 2
Get devices connected. Turn the power off on your router (D-Link) and modem (cable or DSL). Plug an Ethernet cable into the Internet port on the router, and plug the other end into the Ethernet port on your modem.Plug another Ethernet cable into one of the four LAN ports on the router, and plug the other end into the Ethernet port on your computer. Turn on the power on router and modem.
Step :- 3
Connect to configuration utility. Open
Internet Explorer and input the IP address of your router. In the login window,
select admin as user name and leave password blank by default. Press log in to
enter the web-based configuration utility.
Step :- 4
Configure internet connection. In
the configuration utility, click the SETUP menu on the top, and the INTERNET
menu on the left. Then click Internet Connection Setup Wizard to configure
internet connection for router.
Step :- 5
Following the wizard to configure the internet
connection.There will be 5 steps included in the wizard.
·
Set a new password for Admin user.
·
Select appropriate time zone for your location.
·
Select internet connection type. Here select DHCP
Connection (Dynamic IP Address).
·
Clone Your PC’s MAC Address.
·
Save settings and reboot the router.After rebooting, the router
should be able to access the internet.
Step :- 6
Launch wireless setting. Log
into configuration utility again.Click the SETUP menu on the top, and the
WIRELESS SETTING menu on the left,then click Manual Wireless Network Setup. The
wireless setting window will appear.
Step :- 7
Configure the wireless settings. After this step, the router will be ready for wireless
client to connect.
·
Wireless network name (SSID): enter a name for the wireless
network. This name will be used in wireless client to connect the router.
·
Security mode: select WPA-personal.
·
WPA mode: select Auto (WPA or WPA2).
·
Cipher type: select AES.
·
Pre-shared key: create a key for wireless client to connect the
router.
·
Leave other settings by default and click Save Settings.
Step :- 8
Access a wireless network. In the computer which needs to access internet by the
wireless network, create a wireless connection by scanning the name (SSID) of
the wireless network and setting its connection properties. For example, in Windows
7, select Start menu->Control Panel->Network and Internet->Network and
Sharing Center->Connect to a network.
·
Security type: select WPA2-Personal.
·
Encryption type: AES.
·
Network security key: enter the pre-shared key.
·
Click OK.
Conclusion :-
Thus , we have configured and setup the network using optical
router.
======================
Grp B 17].
======================
--------------------
sine wave
--------------------
#!/usr/bin/python
import sys
import os
import time
#================================================================
DAC_D0 = (1 * 32) + 12
DAC_D1 = (1 * 32) + 13
DAC_D2 = (1 * 32) + 14
DAC_D3 = (1 * 32) + 15
DAC_D4 = (1 * 32) + 16
DAC_D5 = (1 * 32) + 17
DAC_D6 = (1 * 32) + 18
DAC_D7 = (1 * 32) + 19
#================================================================
DACBits = [
DAC_D0,
DAC_D1,
DAC_D2,
DAC_D3,
DAC_D4,
DAC_D5,
DAC_D6,
DAC_D7
]
#================================================================
SYSFS_GPIO_DIR = "/sys/class/gpio"
#================================================================
# 100 Sample Values
DAC_Table = [
255, 255, 254, 253, 251, 249, 247, 243, 240, 236, 231, 226, 221,
215, 209, 203, 196, 189,182, 175, 167, 159, 151, 144, 136, 127,
119, 111, 104, 96, 88, 80, 73, 66, 59, 52, 46, 40, 34, 29, 24,
19, 15, 12, 8, 6, 4, 2, 1, 0, -1, 0, 1, 2, 4, 6, 8, 12, 15, 19,
24, 29, 34, 40, 46, 52, 59, 66, 73, 80, 88, 96, 104, 111, 119,
127, 136, 144, 151, 159, 167, 175, 182, 189, 196, 203, 209, 215,
221, 226, 231, 236, 240, 243, 247, 249, 251, 253, 254, 255 ]
#================================================================
def DACWriteBit(pin, val):
GPIO.setup(pin, GPIO.OUT)
if (val == "1"):
GPIO.output(pin, GPIO.HIGH)
else:
GPIO.output(pin, GPIO.LOW)
return
#================================================================
def DACWrite(val):
DACWriteBit(DAC_D0, val[7])
DACWriteBit(DAC_D1, val[6])
DACWriteBit(DAC_D2, val[5])
DACWriteBit(DAC_D3, val[4])
DACWriteBit(DAC_D4, val[3])
DACWriteBit(DAC_D5, val[2])
DACWriteBit(DAC_D6, val[1])
DACWriteBit(DAC_D7, val[0])
return
#================================================================
SYSFS_GPIO_DIR = "/sys/class/gpio"
#================================================================
def gpioExport (gpio):
try:
fo = open(SYSFS_GPIO_DIR + "/export","w")
fo.write(gpio)
fo.close()
return
except IOError:
return
#================================================================
def gpioUnexport (gpio):
try:
fo = open(SYSFS_GPIO_DIR + "/unexport","w")
fo.write(gpio)
fo.close()
return
except IOError:
return
#================================================================
def gpioSetDir (gpio, flag):
try:
fo = open(SYSFS_GPIO_DIR + "/gpio" + gpio + "/direction" ,"w")
fo.write(flag)
fo.close()
return
except IOError:
return
#================================================================
def gpioSetVal (gpio, val):
try:
fo = open(SYSFS_GPIO_DIR + "/gpio" + gpio + "/value" ,"w")
fo.write(val)
fo.close()
return
except IOError:
return
#================================================================
def DACSetAll (val):
f0 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D0) + "/value" ,"w")
f1 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D1) + "/value" ,"w")
f2 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D2) + "/value" ,"w")
f3 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D3) + "/value" ,"w")
f4 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D4) + "/value" ,"w")
f5 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D5) + "/value" ,"w")
f6 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D6) + "/value" ,"w")
f7 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D7) + "/value" ,"w")
f0.write(val[7])
f1.write(val[6])
f2.write(val[5])
f3.write(val[4])
f4.write(val[3])
f5.write(val[2])
f6.write(val[1])
f7.write(val[0])
f0.close()
f1.close()
f2.close()
f3.close()
f4.close()
f5.close()
f6.close()
return
#================================================================
def DACExit (gpio):
gpioUnexport(gpio)
return
#================================================================
def DACInit (gpio):
gpioExport(gpio)
gpioSetDir(gpio, flag="out")
return
#================================================================
def DACInitAll():
for i in range(0, 8):
DACInit(str(DACBits[i]))
return
#================================================================
def DACExitAll():
for i in range(0, 8):
DACExit(str(DACBits[i]))
return
#================================================================
print "\nPython Program to generate Sine Wave using DAC\n"
print "-----------------------------------------------\n"
DACInitAll()
while(True):
for val in DAC_Table:
#print "val = %s" %val
bin_val = str('{:08b}'.format(val))
DACSetAll(bin_val)
exit()
----------------------
square wave
---------------------
#!/usr/bin/python
import sys
import time
import select
#===============================================================================
DAC_D0 = (1 * 32) + 12
DAC_D1 = (1 * 32) + 13
DAC_D2 = (1 * 32) + 14
DAC_D3 = (1 * 32) + 15
DAC_D4 = (1 * 32) + 16
DAC_D5 = (1 * 32) + 17
DAC_D6 = (1 * 32) + 18
DAC_D7 = (1 * 32) + 19
#===============================================================================
DACBits = [
DAC_D0,
DAC_D1,
DAC_D2,
DAC_D3,
DAC_D4,
DAC_D5,
DAC_D6,
DAC_D7
]
#===============================================================================
SYSFS_GPIO_DIR = "/sys/class/gpio"
#===============================================================================
def gpioExport (gpio):
try:
fo = open(SYSFS_GPIO_DIR + "/export","w")
fo.write(gpio)
fo.close()
return
except IOError:
return
#===============================================================================
def gpioUnexport (gpio):
try:
fo = open(SYSFS_GPIO_DIR + "/unexport","w")
fo.write(gpio)
fo.close()
return
except IOError:
return
#===============================================================================
def gpioSetDir (gpio, flag):
try:
fo = open(SYSFS_GPIO_DIR + "/gpio" + gpio + "/direction" ,"w")
fo.write(flag)
fo.close()
return
except IOError:
return
#===============================================================================
def gpioSetVal (gpio, val):
try:
fo = open(SYSFS_GPIO_DIR + "/gpio" + gpio + "/value" ,"w")
fo.write(val)
fo.close()
return
except IOError:
return
#===============================================================================
def DACSetAll (val):
f0 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D0) + "/value" ,"w")
f1 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D1) + "/value" ,"w")
f2 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D2) + "/value" ,"w")
f3 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D3) + "/value" ,"w")
f4 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D4) + "/value" ,"w")
f5 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D5) + "/value" ,"w")
f6 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D6) + "/value" ,"w")
f7 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D7) + "/value" ,"w")
f0.write(val[7])
f1.write(val[6])
f2.write(val[5])
f3.write(val[4])
f4.write(val[3])
f5.write(val[2])
f6.write(val[1])
f7.write(val[0])
f0.close()
f1.close()
f2.close()
f3.close()
f4.close()
f5.close()
f6.close()
return
#===============================================================================
def DACExit (gpio):
gpioUnexport(gpio)
return
#===============================================================================
def DACInit (gpio):
gpioExport(gpio)
gpioSetDir(gpio, flag="out")
return
#===============================================================================
def DACOn (gpio):
gpioSetVal(gpio, val="1")
return
#===============================================================================
def DACOff (gpio):
gpioSetVal(gpio, val="0")
return
#===============================================================================
def DACInitAll():
for i in range(0, 8):
DACInit(str(DACBits[i]))
return
#===============================================================================
def DACExitAll():
for i in range(0, 8):
DACExit(str(DACBits[i]))
return
#===============================================================================
try:
print "\nPython Program to generate Square Wave using DAC\n"
print "-----------------------------------------------\n"
DACInitAll()
while(True):
bin_val = "00000000"
DACSetAll(bin_val)
bin_val = "11111111"
DACSetAll(bin_val)
exit()
except KeyboardInterrupt:
f0.close()
f1.close()
f2.close()
f3.close()
f4.close()
f5.close()
f6.close()
f7.close()
DACExitAll()
print "Program Exit due to CTRL-C"
exit()
sys.exit(0)
======================
Grp B 18].
======================
#include<iostream>
#include<omp.h>
#include<math.h>
using namespace std;
int neg1=0,neg2=0,a=-1,b=-1;
int main()
{
float A1,B1,C1;
float A2,B2,C2;
double pole1,zero1,pole2,zero2;
cout<<"\n Enter First Equation :";
cout<<"\n Enter 'a' :";
cin>>A1;
cout<<"\n Enter 'b' :";
cin>>B1;
cout<<"\n Enter 'c' :";
cin>>C1;
cout<<"\n Enter Second Equation :";
cout<<"\n Enter 'a' :";
cin>>A2;
cout<<"\n Enter 'b' :";
cin>>B2;
cout<<"\n Enter 'c' :";
cin>>C2;
float temp1,temp2,numerator1,numerator2;
#pragma omp parallel
{
int threads= omp_get_num_threads();
// Zero calculation
if(omp_get_thread_num()==0 && a<0)
{
a++;
cout<<"\n Thread A is Caculating Zero. (TID: "<<omp_get_thread_num()<<" )";
temp1=(B1*B1)-(4*A1*C1);
if(temp1<0)
{
neg1=1;
temp1=-temp1;
}
temp1=sqrt(temp1);
numerator1=temp1;
if(!neg1)
{
zero1=(-B1+ numerator1)/2*A1;
zero2=(-B1- numerator1)/2*A1;
}
else
{
temp1=2*A1;
}
}
// Pole calculation
if(omp_get_thread_num()==1 && b<0)
{
b++;
cout<<"\n Thread B is Caculating Pole. (TID: "<<omp_get_thread_num()<<" )";
temp2=(B2*B2)-(4*A2*C2);
if(temp2<0)
{
neg2=1;
temp2=-temp2;
}
temp2=sqrt(temp2);
numerator2=temp2;
if(!neg2)
{
pole1=(-B2+ numerator2)/2*A2;
pole2=(-B2- numerator2)/2*A2;
}
else
{
temp2=2*A2;
}
}
}
if(!neg1)
{
cout<<"\n Zero 1 is :"<<zero1;
cout<<"\n Zero 2 is :"<<zero2;
}
else
{
cout<<"\n Zero 1 is : "<<-B1/temp1<<" +i "<<numerator1/temp1;
cout<<"\n Zero 2 is : "<<-B1/temp1<<" -i "<<numerator1/temp1<<endl;
}
if(!neg2)
{
cout<<"\n Pole 1 is :"<<pole1;
cout<<"\n Pole 2 is :"<<pole2<<endl;
}
else
{
cout<<"\n Pole 1 is : "<<-B2/temp2<<" +i "<<numerator2/temp2;
cout<<"\n Pole 2 is : "<<-B2/temp2<<" -i "<<numerator2/temp2<<endl;
}
return 0;
}
***********************
output
**********************
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$ g++ -fopenmp polezero.cpp -o pz
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$ ./pz
Enter First Equation :
Enter 'a' :1
Enter 'b' :1.5
Enter 'c' :0.6
Enter Second Equation :
Enter 'a' :1
Enter 'b' :-1
Enter 'c' :0.5
Thread B is Caculating Pole. (TID:
Thread A is Caculating Zero. (TID: 0 )1 )
Zero 1 is : -0.75 +i 0.193649
Zero 2 is : -0.75 -i 0.193649
Pole 1 is : 0.5 +i 0.5
Pole 2 is : 0.5 -i 0.5
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$
======================
Grp B 19].
======================
ASSIGNME NT NO. B19
TITLE: Construct a Square wave of programmabl e frequency and draw voltage (y-axis) and
time (x-axis) graph.
PROBLEM STATEMENT:
Write a Python program to capture signal using ARM Cortex A5/A9/M4 ADC and signal
generat or, generat e/construct a Square/Sine wave of programmabl e frequency and voltage Draw
Voltage (y-axis) and Time (x-axis ) graph.
OBJECTIVE:
1. To learn the concept of signal generation.
2. To learn the basi c concept of ADC
3. To learn the basi c about BBB/ ARM Cortex A5/A9/M4.
PRIREQUISITES:
Software: Fedora/ Ubuntu.
Hardware: Signal generator, resisters, BBB et c.
THEORY:
Square waves: Like sine waves, square waves are described in terms of period, frequency and
amplitude
Peak am plitude, V p , and peak-to-peak amplitude, V pp , are measured as you might expect.
However, the rms amplitude, V rms , is greater than that of a sine wave. Rem ember that the rms
amplitude is the DC voltage which will deliver the sam e power as the signal. If a square wave
supply is connected across a lamp, the current flows fi rst one way and then the other. The current
switches di rection but its magnitude remains the sam e. In other words, the square wave delivers
its maximum power throughout the cycle so that V rms is equal to V p . (If this is confusing, don't
worry, the rms amplitude of a square wave is not something you need to think about very often.)
Although a square wave may change very rapidly from its minimum to maximum voltage, this
change cannot be instaneous. The rise time of the signal is defined as the time taken for the
voltage to change from 10% to 90% of its maximum value. Rise times are usually very short,with durations measured in nanoseconds (1 ns = 10 -9 s), or microseconds (1 μs = 10 -6 s), as
indicat ed in the graph.
Signal generators, also known variously as function generators, RF and microwave signal
generat ors, pitch generators, arbitrary waveform generators, digital pattern generators or
frequency generators are el ectronic devices that generate repeating or non-repeating electroni c
signals (in either the analog or digit al domains). They are generally us ed in designing, testing,
troubleshooting, and repairing el ectroni c or electro acoustic devices; though they often have
artistic uses as well.
There are many di fferent types of signal generators, with different purposes and applications
(and at varying levels of expense); in general, no device is suitable for all possible appli cations.
Traditionally, signal generators have been embedded hardware units, but since the age of
multimedia-PCs, flexible, programm able software tone generat ors have also been availabl e.
A function generator is a device which produces simpl e repetitive waveforms. Such devi ces
cont ain an electronic oscillator, a circuit that is capable of creating a repetitive waveform.
(Modern devices m ay use digital signal processing to synthesize waveforms, followed by a
digital to analog converter, or DAC, to produce an analog output ). The most common waveform
is a sine wave, but sawtooth, st ep (pulse), square, and triangul ar waveform oscillators are
commonly available as are arbitrary waveform generators (AWGs). If the oscillator operates
above the audio frequency range (>20 kHz), the generator will often include some sort of
modulation function such as amplitude modul ation (AM), frequency modulation (FM), or phase
modulation (PM) as well as a second os cillator that provides an audio frequency modulation
waveform.
Steps:
1.
2.
3.
4.
5.
6.
7.
Make the connections as shown in figure.
Give input as square wave from signal Generator. Also give input frequency.
Give the output of signal generator to P9 pin no 40 of BBB.
Access BBB through Minicom.
Run the python code in operating system of BBB.
Observe the value of volt age.
Draw tim e Vs voltage graphConclusion: - In this way we perform the construction of a Square wave of programm able
frequency using signal generator and drawn voltage (y-axis) and time (x-axis ) graph.Program:
#!/usr/bin/python
import sys
import time
import sel ect
import sys
import time
import sel ect
#===================================================
import Adafruit_BBIO.ADC as ADC
ADC_IN_1 = "P9_39"
ADC_IN_2 = "P9_40"
#===================================================
ADC_INP UT = ADC_IN_2
#===================================================
DAC_D0
=
(1 * 32) + 12
DAC_D1
=
(1 * 32) + 13
DAC_D2
=
(1 * 32) + 14
DAC_D3
=
(1 * 32) + 15
DAC_D4
=
(1 * 32) + 16
DAC_D5
=
(1 * 32) + 17
DAC_D6
=
(1 * 32) + 18
DAC_D7
=
(1 * 32) + 19
#===================================================
DACBits = [
DAC_D0,
DAC_D1,
DAC_D2,
DAC_D3,
DAC_D4,
DAC_D5,
DAC_D6,
DAC_D7
]
#===================================================
SYSFS_GPIO_DIR = "/sys/ cl ass/gpio"
#===================================================
def gpioExport (gpio):
try:
fo = open(SYSFS_GPIO_DIR + "/ export","w")
fo.write(gpio)
fo.close()
return
except IOError:
return
#===================================================
def gpioUnexport (gpio):
try:
fo = open(SYSFS_GPIO_DIR + "/unexport","w")
fo.write(gpio)fo.close()
return
except IOError:
return
#===================================================
def gpioSetDir (gpio, fl ag):
try:
fo = open(SYSFS_GPIO_DIR + "/gpio" + gpio + "/direction" ,"w")
fo.write(flag)
fo.close()
return
except IOError:
return
#===================================================
def gpioSetVal (gpio, val):
try:
fo = open(SYSFS_GPIO_DIR + "/gpio" + gpio + "/value" ,"w")
fo.write(val)
fo.close()
return
except IOError:
return
#===================================================
def DACSetAll (val):
f0 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D0) + "/value" ,"w")
f1 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D1) + "/value" ,"w")
f2 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D2) + "/value" ,"w")
f3 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D3) + "/value" ,"w")
f4 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D4) + "/value" ,"w")
f5 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D5) + "/value" ,"w")
f6 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D6) + "/value" ,"w")
f7 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D7) + "/value" ,"w")
f0.write(val[7])
f1.write(val[6])
f2.write(val[5])
f3.write(val[4])
f4.write(val[3])
f5.write(val[2])
f6.write(val[1])
f7.write(val[0])
f0.close()
f1.close()
f2.close()
f3.close()
f4.close()
f5.close()f6.close()
return
#===================================================
def DACExit (gpio):
gpioUnexport(gpio)
return
#===================================================
def DACInit (gpio):
gpioExport(gpio)
gpioSetDir(gpio, flag="out")
return
#===================================================
def DACInitAll():
for i in range(0, 8):
DACInit(str(DACBits[i]))
return
#===================================================
def DACExitAll():
for i in range(0, 8):
DACExit(str(DACBits[i]))
return
#===================================================
try:
print "\nPython Program to generate Sine Wave using DAC\n"
print "-----------------------------------------------\n"
ADC.setup()
DACInitAll()
while(True):
value = ADC.read_raw(ADC_INPUT)
value = int(value)
value = value >> 2
print "Adc val = [%d]" %value
bin_val = str('{:08b}'.format(value))
print "binary val = %s" %bin_val
DACSetAll(bin_val)
#time.sleep(1)
exit()
except KeyboardInt errupt:
DACExitAll()
print "Program Exit due to CTRL-C"
exit()
sys.exit(0)Output:-
Vol tage vs time wave form:-
1.2
1
0.8
0.6
0.4
0.2
0
import Adafruit_BBIO.ADC as ADC
ADC_IN_1 = "P9_39"
ADC_IN_2 = "P9_40"
#===================================================
ADC_INP UT = ADC_IN_2
#===================================================
DAC_D0
=
(1 * 32) + 12
DAC_D1
=
(1 * 32) + 13
DAC_D2
=
(1 * 32) + 14
DAC_D3
=
(1 * 32) + 15
DAC_D4
=
(1 * 32) + 16
DAC_D5
=
(1 * 32) + 17
DAC_D6
=
(1 * 32) + 18
DAC_D7
=
(1 * 32) + 19
#===================================================
DACBits = [
DAC_D0,
DAC_D1,
DAC_D2,
DAC_D3,
DAC_D4,
DAC_D5,
DAC_D6,
DAC_D7
]
#===================================================
SYSFS_GPIO_DIR = "/sys/ cl ass/gpio"
#===================================================
def gpioExport (gpio):
try:
fo = open(SYSFS_GPIO_DIR + "/ export","w")
fo.write(gpio)
fo.close()
return
except IOError:
return
#===================================================
def gpioUnexport (gpio):
try:
fo = open(SYSFS_GPIO_DIR + "/unexport","w")
fo.write(gpio)fo.close()
return
except IOError:
return
#===================================================
def gpioSetDir (gpio, fl ag):
try:
fo = open(SYSFS_GPIO_DIR + "/gpio" + gpio + "/direction" ,"w")
fo.write(flag)
fo.close()
return
except IOError:
return
#===================================================
def gpioSetVal (gpio, val):
try:
fo = open(SYSFS_GPIO_DIR + "/gpio" + gpio + "/value" ,"w")
fo.write(val)
fo.close()
return
except IOError:
return
#===================================================
def DACSetAll (val):
f0 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D0) + "/value" ,"w")
f1 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D1) + "/value" ,"w")
f2 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D2) + "/value" ,"w")
f3 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D3) + "/value" ,"w")
f4 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D4) + "/value" ,"w")
f5 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D5) + "/value" ,"w")
f6 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D6) + "/value" ,"w")
f7 = open(SYSFS_GPIO_DIR + "/gpio" + str(DAC_D7) + "/value" ,"w")
f0.write(val[7])
f1.write(val[6])
f2.write(val[5])
f3.write(val[4])
f4.write(val[3])
f5.write(val[2])
f6.write(val[1])
f7.write(val[0])
f0.close()
f1.close()
f2.close()
f3.close()
f4.close()
f5.close()f6.close()
return
#===================================================
def DACExit (gpio):
gpioUnexport(gpio)
return
#===================================================
def DACInit (gpio):
gpioExport(gpio)
gpioSetDir(gpio, flag="out")
return
#===================================================
def DACInitAll():
for i in range(0, 8):
DACInit(str(DACBits[i]))
return
#===================================================
def DACExitAll():
for i in range(0, 8):
DACExit(str(DACBits[i]))
return
#===================================================
try:
print "\nPython Program to generate Sine Wave using DAC\n"
print "-----------------------------------------------\n"
ADC.setup()
DACInitAll()
while(True):
value = ADC.read_raw(ADC_INPUT)
value = int(value)
value = value >> 2
print "Adc val = [%d]" %value
bin_val = str('{:08b}'.format(value))
print "binary val = %s" %bin_val
DACSetAll(bin_val)
#time.sleep(1)
exit()
except KeyboardInt errupt:
DACExitAll()
print "Program Exit due to CTRL-C"
exit()
sys.exit(0)Output:-
Vol tage vs time wave form:-
1.2
1
0.8
0.6
0.4
0.2
0
======================
Grp C 3].
======================
********************************************************************************
Group : c
Assignment No : 3
Title : Designing IPv6 network and/or configuration of
Dual stack IPv6 and IPv4 network.
Roll No:
********************************************************************
Pre-requisite :
1. IPV4
2. IPV6
3. Dual stack concept.
Index Terms :
IPV4 :
Internet Protocol
version 4 (IPv4) is the fourth version in the development of the Internet
Protocol (IP) Internet, and routes most traffic on the Internet.[1] However, a
successor protocol, IPv6, has been defined and is in various stages of
production deployment.IPv4 is a connectionless protocol for use on
packet-switched networks. It operates on a best effort delivery model, in that
it does not guarantee delivery, nor does it assure proper sequencing or
avoidance of duplicate delivery. These aspects, including data integrity, are
addressed by an upper layer transport protocol, such as the Transmission
Control Protocol (TCP).IPv4 uses 32-bit (four-byte) addresses, which limits the
address space to 4294967296 (232) addresses. As addresses were assigned to
users, the number of unassigned addresses decreased.This limitation of IPv4
stimulated the development of IPv6 in the 1990s, which has been in commercial
deployment since 2006.IPv4 reserves special address blocks for private networks
(~18 million addresses) and multicast addresses (~270 million addresses).
IPV4 ADDRESS
REPRESENTATION :
IPv4 addresses may be
written in any notation expressing a 32-bit integer value, but for human
convenience, they are most often written in the dot-decimal notation, which
consists of four octets of the address expressed individually in decimal and
separated by periods.An IP address followed by a slash(/) and a number (i.e.
127.0.0.1/8 ) indicates a block of addresses using a subnet mask.
Class A—The leading bit is set to 0, a 7-bit number,
and a 24-bit local host address. Up to 125 class A networks can be defined,
with up to 16,777,214 hosts per network.
Class B—The two highest-order bits are set to 1 and 0,
a 14-bit network number, and a 16-bit local host address. Up to 16,382 class B
networks can be defined, with up to 65,534 hosts per network.
Class C—The three leading bits are set to 1, 1, and 0, a
21-bit network number, and an 8-bit local host address. Up to 2,097,152 class C
networks can be defined, with up to 254 hosts per network.
Class D—The four highest-order bits are set to 1, 1, 1,
and 0. Class D is used as a multicast address.
Header
The IPv4 packet header
consists of 14 fields, of which 13 are required. The 14th field is optional
(red background in table) and aptly named: options. The fields in the header
are packed with the most significant byte first (big endian), and for the
diagram and discussion, the most significant bits are considered to come first
(MSB 0 bit numbering). The most significant bit is numbered 0, so the version
field is actually found in the four most significant bits of the first byte.
IPV6 :
Internet Protocol
version 6 (IPv6) is the most recent version of the Internet Protocol (IP), the
communications protocol that provides an identification and location system for
computers on networks and routes traffic across the Internet. IPv6 was
developed by the Internet Engineering Task Force (IETF) to deal with the
long-anticipated problem of IPv4 address exhaustion. IPv6 is intended to
replace IPv4.
Every device on the
Internet is assigned an IP address for identification and location definition.
With the rapid growth of the Internet after commercialization in the 1990s, it
became evident that far more addresses than the IPv4 address space has
available were necessary to connect new devices in the future. By 1998, the
Internet Engineering Task Force (IETF) had formalized the successor protocol.
IPv6 uses a 128-bit address, allowing 2128, or approximately 3.4×1038
addresses, or more than 7.9×1028 times as many as IPv4, which uses 32-bit
addresses and provides approximately 4.3 billion addresses. The two protocols
are not designed to be interoperable, complicating the transition to IPv6.
However, several IPv6 transition mechanisms have been devised to permit
communication between IPv4 and IPv6 hosts.
IPV6 ADDRESS
REPRESENTATION :
Packet Format :
An IPv6 packet has two
parts: a header and payload.
The header consists of a
fixed portion with minimal functionality required for all packets and may be
followed by optional extensions to implement special features.The fixed header
occupies the first 40 octets (320 bits) of the IPv6 packet. It contains the
source and destination addresses, traffic classification options, a hop
counter, and the type of the optional extension or payload which follows the
header. This Next Header field tells the receiver how to interpret the data
which follows the header. If the packet contains options, this field contains
the option type of the next option. The "Next Header" field of the
last option, points to the upper-layer protocol that is carried in the packet's
payload.
Dual stack:
Dual stack is a transition
technology in which IPv4 and IPv6 operate in tandem over shared or dedicated
links. In a dual-stack network, both IPv4 and IPv6 are fully deployed across
the infrastructure, so that configuration and routing protocols handle both
IPv4 and IPv6 addressing and adjacencies.
Although dual-stack may
appear to be an ideal solution, it presents two major deployment challenges to
enterprises and ISPs:
• It requires a current network infrastructure
that is capable of deploying IPv6. In many cases, however, the current network
may not be ready and may require hardware and software upgrades.
• IPv6 needs to be activated on almost all the
network elements. To meet this requirement, the existing network may need to be
redesigned, posing business continuity challenges.
Dual stack is the most
direct approach to making IPv6 nodes compatible with IPv4 nodes. The best way
for an IPv6 node to be compatible with an IPv4 node is to maintain a complete
IPv4 stack. A network node that supports both IPv4 and IPv6 is called a dual
stack node. A dual stack node configured with an IPv4 address and an IPv6
address can have both IPv4 and IPv6 packets transmitted.
For an upper layer
application supporting both IPv4 and IPv6, either TCP or UDP can be selected at
the transport layer, while IPv6 stack is preferred at the network layer.
Dual-stack:
In dual-stack
configuration, the device is configured for both IPv4 and IPv6 network stacks.
The dual-stack configuration can be implemented on a single interface or with
multiple interfaces. In this configuration, the device decides how to send the
traffic based on the destination address of the other device.
As of IOS 12.2(2), Cisco
is IPv6-ready. To support dual-stack routing on a single interface, you need to
configure IPv6 on your routing device.
The following commands
allow for forwarding of IPv6 data packets:
Router1> enable
Router1# configure
terminal
Router1(config)# ipv6
unicast-routing
Router1(config)#
interface ethernet0
Router1(config-if)# ip
address 192.168.75.1 255.255.255.0
Router1(config-if)# ipv6
address 2123:AFFF::192:168:75:1/120
Router1(config-if)# exit
Router1(config)# exit
Router1# copy
running-config startup-config
Tunneling:
Tunneling refers to
passing IPv6 data over an IPv4 network by placing the IPv6 packet into the data
section of an IPv4 packet, as shown in Figure 4-2. The four main types of
tunneling are
Manual IPv6-to-IPv4
tunneling encapsulates an IPv6 packet in an IPv4 packet. So as to not fragment
the packet from adding the IPv4 header to it, the data packet needs to be
reduced by 20 bytes if the IPv4 has an optional protocol field, or 20 octets if
it does not, as well as require routers support both IP stacks.
Dynamic 6-to-4 tunneling
routes data between is lands of IPv6 routers across your network.
Intra-Site Automatic
Tunnel Addressing Protocol (ISATAP) tunneling uses the existing IPv4 network as
the link layer of the IPv6 network and routes the data between the IP networks
via routers supporting both IP stacks.
Teredo tunneling
performs the tunneling work at the dual-stacked host on either end of the
connection rather than at a gateway router.
Subscribe to:
Posts
(
Atom
)