Essential Networking Commands Explained
Essential Networking Commands Explained
[1] ipconfig:- ipconfig is a commmand line utility available on all versions of Microsoft windows
starting with Windows NT. ipconfig is designed to be run from the Windows command
prompt. This utility allows you to get the IP address information of a Windows
computer. It also allows some control over active TCP/IP connections. ipconfig is an
alternative to the older 'winipcfg' utility.
ipconfig Usage:-From the command prompt, type 'ipconfig' to run the utility with default options.
The output of the default command contains the IP address, network mask and
gateway for all physical and virtual network adapters.
[2] getmac:- Returns the media access control (MAC) address and list of network protocols
associated with each address for all network cards in each computer, either locally or across a
network.
Syntax:-
getmac[.exe] [/s Computer [/u Domain\User [/p Password]]] [/fo {TABLE|LIST|CSV}] [/
nh] [/v]
Parameters:-
/s Computer : Specifies the name or IP address of a remote computer (do not use backslashes).
The default is the local computer.
/u Domain \ User : Runs the command with the account permissions of the user specified
by User or Domain\User. The default is the permissions of the current logged on user on the
computer issuing the command.
/p Password : Specifies the password of the user account that is specified in the /u parameter.
/fo { TABLE | LIST | CSV } : Specifies the format to use for the query output. Valid values
are TABLE, LIST, and CSV. The default format for output is TABLE.
/nh : Suppresses column header in output. Valid when the /fo parameter is set
to TABLE or CSV.
/v : Specifies that the output display verbose information.
/? : Displays help at the command prompt.
[3] nslookup:- Displays information that you can use to diagnose Domain Name System
(DNS)
infrastructure. Before using this tool, you should be familiar with how DNS
works.
The Nslookup command-line tool is available only if you have installed the
TCP/IP
protocol.
Syntax:-
nslookup [-SubCommand ...] [{ComputerToFind| [-Server]}]
Parameters:-
- SubCommand ... : Specifies one or more nslookup subcommands as a command-line
option. For a list of subcommands, see Related Topics.
ComputerToFind : Looks up information for ComputerToFind using the current default
DNS name server, if no other server is specified. To look up a computer not in the current
DNS domain, append a period to the name.
- Server : Specifies to use this server as the DNS name server. If you omit -Server, the
default DNS name server is used.
{ help | ? } : Displays a short summary of nslookup subcommands.
[4] Ping:- Pinging is a command which tells you if the connection between your computer
and a particular domain is working correctly.
In Windows, select Start > Programs > Accessories > Command Prompt. This will give you
a window like the one below.
Enter the word ping, followed by a space, then the domain name.
If the results show a series of replies, the connection is working. The time shows you how fast
the connection is. If you see a "timed out" error instead of a reply, there is a breakdown
somewhere between your computer and the domain. In this case the next step is to perform
a traceroute.
[5] Tracert:- Traceroute is a command which can show you the path a packet of information
takes from your computer to one you specify. It will list all the routers it passes through until
it reaches its destination, or fails to and is discarded. In addition to this, it will tell you how
long each 'hop' from router to router takes.
In Windows, select Start > Programs > Accessories > Command Prompt. This will give you
a window like the one below.
Enter the word tracert, followed by a space, then the domain name.
Next it gives information about each router it passes through on the way to its destination.
1 is the internet gateway on the network this traceroute was done from (an ADSL modem in
thiscase)
2 is the ISP the origin computer is connected to ([Link])
3 is also in the xtra network
4 timed out
5 - 9 are all routers on the [Link] network (the domain that is the internet
gateway out of New Zealand)
10 - 14 are all [Link] in the USA (a telecom supplier in the USA)
15 - 17 are on the nac network (Net Access Corporation, an ISP in the New York area)
18 is a router on the network [Link] is hosted on
and finally, line 19 is the computer [Link] is hosted on ([Link])
Each of the 3 columns are a response from that router, and how long it took (each hop is tested
3 times). For example, in line 2, the first try took 240ms (240 milliseconds), the second took
421 ms, and the third took 70ms.
You will notice that line 4 'timed out', that is, there was no response from the router, so
another one was tried ([Link]) which was successful.
You will also notice that the time it took quadrupled while passing through the global-gateway
network.
This is extremely useful when trying to find out why a website is unreachable, as you will be
able to see where the connection fails. If you have a website hosted somewhere, it would be a
good idea to do a traceroute to it when it is working, so that when it fails, you can do another
traceroute to it (which will probably time out if the website is unreachable) and compare them.
Be aware though, that it will probably take a different route each time, but the networks it
passes through will generally be very similar.
If the example above had continued to time out after line 9, you could suspect that global-
[Link] was the problem, and not [Link].
If it timed out after line 1, you would know there was a problem connecting to your ISP (in
this case you would not be able to access anything on the internet).
It is generally recommended that if you have a website that is unreachable, you should use
both the traceroute and ping commands before you contact your ISP to complain. More often
that not, there will be nothing to your ISP or hosting company can do about it.
Specifically, the netstat command can show details about individual network connections,
overall and protocol-specific networking statistics, and much more, all of which could help
troubleshoot certain kinds of networking issues.
netstat [-a] [-b] [-e] [-f] [-n] [-o] [-p protocol] [-r] [-s] [-t] [-x] [-y] [time_interval] [/?]
Practical-No.2.
Theory: Windows XP/2000 command list these commands are intended for administrating a
network.
Prerequisite: DLL Framing Protocols ref- computer n/w 4th edition, A.S. Tanenbaum.
Theory:
The Data Link Layer is the second layer in the OSI model, above the Physical Layer, which ensures
that the error free data is transferred between the adjacent nodes in the network. It breaks the
datagrams passed down by above layers and convert them into frames ready for transfer. This
is called Framing. It provides two main functionalities
Since the physical layer merely accepts and transmits a stream of bits without any regard to meaning
or structure, it is upto the data link layer to create and recognize frame boundaries. This can be
accomplished by attaching special bit patterns to the beginning and end of the frame. If these
bit patterns can accidentally occur in data, special care must be taken to make sure these
patterns are not incorrectly interpreted as frame delimiters. The four framing methods that are
widely used are
Character count
Starting and ending characters, with character stuffing
Starting and ending flags, with bit stuffing
Physical layer coding violations
Bit stuffing
The third method allows data frames to contain an arbitrary number of bits and allows character codes
with an arbitrary number of bits per character. At the start and end of each frame is a flag byte
consisting of the special bit pattern 01111110 . Whenever the sender's data link layer
encounters five consecutive 1s in the data, it automatically stuffs a zero bit into the outgoing
bit stream. This technique is called bit stuffing. When the receiver sees five consecutive 1s in
the incoming data stream, followed by a zero bit, it automatically destuffs the 0 bit. The
boundary between two frames can be determined by locating the flag pattern.
Procedure:
ALGORITHM:
[Link] the number of frames.
[Link] the binary data for each frame.
[Link] the flag.
[Link] Stuffing:If there is five consecutive 1’s after zero ,add one zero as sixth bit.
[Link] the data.
[Link]:If there is zero after the five consecutive 1’s ,remove that zero in the data.
[Link] the data.
#include<stdio.h>
main()
{ char a[10];
int count=0,i=0,j,l,k=0;
printf("Enter the input string");
scanf("%s",a);
L=strlen(a);
for(i=0;i<l;i++)
if(a[i]=='1')
{ k=i;
count=0;
while(a[k]=='1')
{ count+=1;
k++;
if(count==5)
{ for(j=l+1;j>k;j--)
{ a[j]=a[j-1];
} a[k]='0';
l++;
break;
}
i=k;
}
}
printf("\n The bitstuffed string is %s",a);
//getch();
k=0;
for(i=0;i<=l;i++)
{ if(a[i]=='1')
{
k=i;
count=0;
while(a[k]=='1')
{ count+=1;
k++;
if(count==5)
{
for(j=k;j<l+1;j++)
{
a[j]=a[j+1];
} l--;
a[l+1]='0';
break;
}}
i=k-1;
}}
printf("String after unstuffing %s\n",a);
}
Output:
Skills Developed: how to detect multiple bit errors and how to implement.
Prerequisite: Error Detection codes Ref-Data comm.. & Networking 3rd edition chapter 10 B.A.
Forouzan.
Theory:
The cyclic redundancy check, or CRC, is a technique for detecting errors in digital data, but
not for making corrections when errors are detected. It is used primarily in data transmission.
In the CRC method, a certain number of check bits, often called a checksum, are appended to
the message being transmitted. The receiver can determine whether or not the check bits agree
with the data, to ascertain with a certain degree of probability whether or not an error occurred
in transmission. If an error occurred, the receiver sends a “negative acknowledgement” (NAK)
back to the sender, requesting that the message be retransmitted. The technique is also
sometimes applied to data storage devices, such as a disk drive. In this situation each block on
the disk would have check bits, and the hardware might automatically initiate a reread of the
block when an error is detected, or it might report the error to software. The material that
follows speaks in terms of a “sender” and a “receiver” of a “message,” but it should be
understood that it applies to storage writing and reading as well.
Procedure:
• The data unit with the appended CRC (remainder) is send to the receiver
• The receiver divides the received data by the same divisor.
• If the remainder is zero then the data is passed (no errors)
• Otherwise an error occurs
CRC
Binary Division
Program:
#include< stdlib.h>
#include< conio.h>
#include< stdio.h>
void main()
{
int i,j,n,g,a,arr[20],gen[20],b[20],q[20],s;
clrscr();
printf("Transmitter side:");
printf("\nEnter no. of data bits:");
scanf("%d",&n);
printf("Enter data:");
for(i=0;i< n;i++)
scanf("%d",&arr[i]);
}
while(gen[0]!=1);
printf("\n\tThe generator matrix:");
for(j=0;j< g;j++)
printf("%d",gen[j]);
a=n+(g-1);
printf("\n\tThe appended matrix is:");
for(i=0;i< j;++i)
arr[n+i]=0;
for(i=0;i< a;++i)
printf("%d",arr[i]);
for(i=0;i< n;++i)
q[i]= arr[i];
for(i=0;i< n;++i)
{
if(arr[i]==0)
{
for(j=i;j< g+i;++j)
arr[j] = arr[j]^0;
}
else
{
arr[i] = arr[i]^gen[0];
arr[i+1]=arr[i+1]^gen[1];
arr[i+2]=arr[i+2]^gen[2];
arr[i+3]=arr[i+3]^gen[3];
}
}
printf("\n\tThe CRC is :");
for(i=n;i < a;++i)
printf("%d",arr[i]);
s=n+a;
for(i=n;i< s;i++)
q[i]=arr[i];
printf("\n");
for(i=0;i< a;i++)
printf("%d",q[i]);
getch();
}
Output:
Transmitter side:
Enter no. of data bits:8
Enter data:1 0 1 0 0 0 0 1
Enter size of generator:4
Enter generator:1 0 0 1
Objective: to understand the latest configuration recently used their weaknesses and advantages
over other technologies
Skills Developed: students shall be able to understand about network devices, cables, topologies
and their configuration.
Theory: Network topology is the physical interconnections of the elements (links, nodes, etc.) of a
computer network.A local area network (LAN) is one example of a network that exhibits both
a physical topology and a logical topology. Any given node in the LAN has one or more links
to one or more other nodes in the network and the mapping of these links and nodes in a graph
results in a geometrical shape that may be used to describe the physical topology of the
network.
Computer networking devices are units that mediate data in a computer network. Computer
networking devices are also called network equipment, Intermediate Systems (IS) or
InterWorking Unit (IWU). Units which are the last receiver or generate data are called hosts
or data terminal equipment.
Gateway: device sitting at a network node for interfacing with another network that
uses different protocols. Works on OSI layers 4 to 7.
Router: a specialized network device that determines the next network point to which
to forward a data packet toward its destination. Unlike a gateway, it cannot interface
different protocols. Works on OSI layer 3.
Bridge: a device that connects multiple network segments along the data link layer.
Works on OSI layer 2.
Switch: a device that allocates traffic from one network segment to certain lines
(intended destination(s)) which connect the segment to another network segment. So
unlike a hub a switch splits the network traffic and sends it to different destinations
rather than to all systems on the network. Works on OSI layer 2.
Hub: connects multiple Ethernet segments together making them act as a single
segment. When using a hub, every attached device shares the same broadcast domain
and the same collision domain. Therefore, only one computer connected to the hub is
able to transmit at a time. Depending on the network topology, the hub provides a
basic level 1 OSI model connection among the network objects (workstations, servers,
etc). It provides bandwidth which is shared among all the objects, compared to
switches, which provide a dedicated connection between individual nodes. Works on
OSI layer 1.
Repeater: device to amplify or regenerate digital signals received while setting them
from one part of a network into another. Works on OSI layer 1.
Hardware or software components that typically sit on the connection point of different networks, e.g.
between an internal network and an external network:
Proxy: computer network service which allows clients to make indirect network
connections to other network services
Firewall: a piece of hardware or software put on the network to prevent some
communications forbidden by the network policy
Network Address Translator: network service provide as hardware or software that
converts internal to external network addresses and vice versa
Multiplexer: device that combines several electrical signals into a single signal
Network Card: a piece of computer hardware to allow the attached computer to
communicate by network
Modem: device that modulates an analog "carrier" signal (such as sound), to encode
digital information, and that also demodulates such a carrier signal to decode the
transmitted information, as a computer communicating with another computer over the
telephone network
ISDN terminal adapter (TA): a specialized gateway for ISDN
Line Driver: a device to increase transmission distance by amplifying the signal. Base-
band networks only.
Network Media Types
Network media is the actual path over which an electrical signal travels as it moves from one
component to another. This chapter describes the common types of network media, including
twisted-pair cable, coaxial cable, fiber-optic cable, and wireless.
Twisted-Pair Cable
Twisted-pair cable is a type of cabling that is used for telephone communications and most modern
Ethernet networks. A pair of wires forms a circuit that can transmit data. The pairs are twisted
to provide protection against crosstalk, the noise generated by adjacent pairs. When electrical
current flows through a wire, it creates a small, circular magnetic field around the wire. When
two wires in an electrical circuit are placed close together, their magnetic fields are the exact
opposite of each other. Thus, the two magnetic fields cancel each other out. They also cancel
out any outside magnetic fields. Twisting the wires can enhance this cancellation effect. Using
cancellation together with twisting the wires, cable designers can effectively provide self-
shielding for wire pairs within the network media.
Two basic types of twisted-pair cable exist: unshielded twisted pair (UTP) and shielded twisted pair
(STP). The following sections discuss UTP and STP cable in more detail.
UTP Cable
UTP cable is a medium that is composed of pairs of wires UTP cable is used in a variety of networks.
Each of the eight individual copper wires in UTP cable \is covered by an insulating material.
In addition, the wires in each pair are twisted around each other.
UTP cable relies solely on the cancellation effect produced by the twisted wire pairs to limit signal
degradation caused by electromagnetic interference (EMI) and radio
frequency interference (RFI). To further reduce crosstalk between the pairs in
UTP cable, the number of twists in the wire pairs varies. UTP cable must
follow precise specifications governing how many twists or braids are
permitted per meter (3.28 feet) of cable.
UTP cable often is installed using a Registered Jack 45 (RJ-45) connector). The RJ-45 is an eight-wire
connector used commonly to connect computers onto a local-area network (LAN), especially
Ethernets.
RJ-45 Connectors
When used as a networking medium, UTP cable has four pairs of either 22- or 24-gauge copper wire.
UTP used as a networking medium has an impedance of 100 ohms; this differentiates it from
other types of twisted-pair wiring such as that used for telephone wiring, which has
impedance of 600 ohms.
UTP cable offers many advantages. Because UTP has an external diameter of approximately 0.43 cm
(0.17 inches), its small size can be advantageous during installation. Because it has such a
small external diameter, UTP does not fill up wiring ducts as rapidly as other types of cable.
This can be an extremely important factor to consider, particularly when installing a network
in an older building. UTP cable is easy to install and is less expensive than other types of
networking media. In fact, UTP costs less per meter than any other type of LAN cabling. And
because UTP can be used with most of the major networking architectures, it continues to
grow in popularity.
Disadvantages also are involved in using twisted-pair cabling, however. UTP cable is more prone to
electrical noise and interference than other types of networking media, and the distance
between signal boosts is shorter for UTP than it is for coaxial and fiber-optic cables.
Although UTP was once considered to be slower at transmitting data than other types of cable, this is
no longer true. In fact, UTP is considered the fastest copper-based medium today. The
following summarizes the features of UTP cable:
Category 1—Used for telephone communications. Not suitable for transmitting data.
Category 2—Capable of transmitting data at speeds up to 4 megabits per second
(Mbps).
Category 3—Used in 10BASE-T networks. Can transmit data at speeds up to 10
Mbps.
Category 4—Used in Token Ring networks. Can transmit data at speeds up to 16
Mbps.
Category 5—Can transmit data at speeds up to 100 Mbps.
Category 5e —Used in networks running at speeds up to 1000 Mbps (1 gigabit per
second [Gbps]).
Category 6—Typically, Category 6 cable consists of four pairs of 24 American Wire
Gauge (AWG) copper wires. Category 6 cable is currently the fastest standard for
UTP.
Shielded twisted-pair (STP) cable combines the techniques of shielding, cancellation, and wire
twisting. Each pair of wires is wrapped in a metallic foil .The four pairs of wires then are
wrapped in an overall metallic braid or foil, usually 150-ohm cable. As specified for use in
Ethernet network installations, STP reduces electrical noise both within the cable (pair-to-pair
coupling, or crosstalk) and from outside the cable (EMI and RFI). STP usually is installed
with STP data connector, which is created especially for the STP cable. However, STP
cabling also can use the same RJ connectors that UTP uses.
Although STP prevents interference better than UTP, it is more expensive and difficult to install. In
addition, the metallic shielding must be grounded at both ends. If it is improperly grounded,
the shield acts like an antenna and picks up unwanted signals. Because of its cost and
difficulty with termination, STP is rarely used in Ethernet networks. STP is primarily used in
Europe.
When comparing UTP and STP, keep the following points in mind:
The speed of both types of cable is usually satisfactory for local-area distances.
These are the least-expensive media for data communication. UTP is less expensive
than STP.
Because most buildings are already wired with UTP, many transmission standards are
adapted to use it, to avoid costly rewiring with an alternative cable type.
Procedure:
Step-1 Network topology used and discuss advantage & disadvantage of this topology
and comparison with other.
Step-2: Type of Physical media used (Coaxial cable, twisted pair, Fiber Optics) and
discuss its characteristics and compare it with other medias.
Step-4 Type of Network devices are used. Explain functioning of these devices.
Practical No. 6
Objective: Establish Virtual private network for secure communication between two devices/LAN’s
Theory: A VPN is a private network created over a public one. It’s done with encryption, this way,
your data is encapsulated and secure in transit – this creates the ‘virtual’ tunnel. A VPN is a
method of connecting to a private network by a public network like the Internet. An internet
connection in a company is common. An Internet connection in a Home is common too. With
both of these, you could create an encrypted tunnel between them and pass traffic, safely -
securely.
If you want to create a VPN connection you will have to use encryption to make sure that
others cannot intercept the data in transit while traversing the Internet. Windows XP provides
a certain level of security by using Point-to-Point Tunneling Protocol (PPTP) or Layer Two
Tunneling Protocol (L2TP). They are both considered tunneling protocols – simply because
they create that virtual tunnel just discussed, by applying encryption.
Procedure:
Windows XP makes it possible to natively manage small virtual private networks; this feature
is particularly suitable for small business or family networks (called SOHO, for Small
Office/Home Office). To set up a virtual private network, you simply need to install a remote
access server (VPN server) on your local area network that can be accessed from the Internet
and configure each client to enable it to connect.
In our example we will assume that the machine to be used as VPN server on the local area
network has two interfaces - one to the local area network (a network card for example) and
one to the Internet (an ADSL connection or a cable connection for example). It will be via its
Internet-connected interface that VPN clients will connect to the local area network.
To make it possible for this machine to manage virtual private networks, simply open Network
Connections in the Control panel. In the now open window, double-click New connection
wizard:
Then click Next:
Out of the three choices offered in the window, select "Set up an advanced connection":
A list of the system's users appears; simply select or add users authorized to connect to the VPN
server:
Then select the list of protocols authorized via the VPN:
Click the Properties button associated with the TCP/IP protocol to define the IP addresses the server
assigns to the client for the entire session. If the local area network the server is on does not
have specific addressing you can let the server automatically determine an IP address.
However, if the network has a specific addressing plan, you can define the range of addresses
to be assigned:
Configuration of the VPN server is now complete; you can click the Finish button:
Installing a VPN client in Windows XP
To let a client connect to your VPN server, you need to define all the connection settings (server
address, protocols to be used, etc.) The new connection wizard available from the Network
connections icon in the control panel enables this configuration:
Then enter a name that best describes the name of the virtual private network you want to connect to:
The next screen lets you determine whether a connection needs to be established before connecting to
the virtual private network. Most of the time (if you are on a permanent connection or ADSL
or cable access), it will not be necessary to establish the connection since the computer is
already connected to the Internet; if this is not the case select the connection to be established
from the list:
To access the remote access server (VPN server or host), you must specify its address (IP address or
host name). If it does not have an IP address, you will need to equip it with a dynamic naming
system (DynDNS) capable of assigning it a domain name and specify this name in the
following field:
Once you have finished defining the VPN connection, a connection window opens asking you for a
login and password:
Before connecting, you need to define some settings by clicking the Properties button at the bottom of
the window. A window featuring a certain number of tabs then lets you more narrowly
configure the connection. In the Network management tab, select the PPTP protocol from the
scrollable list; select the (TCP/IP) Internet protocol and click Properties:
The window that appears lets you define the IP address the client machine will have when connecting
to the remote access server. This lets you have addressing that is consistent with the remote
addressing. As such, the VPN server is capable of acting as a DHCP server, that is, of
automatically providing the VPN client with a valid address. To do so, simply select the
"Obtain an address automatically" option:
In the event that the client uses the DHCP, if the server assigns an internal IP address, the client will
be connected to the workplace network and will benefit from its services but will no longer
have Internet access via the interface used since the IP address is not routable. In order to let
the client be connected to the VPN and still have Internet access via this connection, the VPN
server must be configured such that it shares its connection! The Advanced button lets the
client use the VPN server's gateway in the event that the latter shares it connection:
Practical No. 7
This example introduces you to Java socket programming. The server listens for a connection.
When a connection is established by a client. The client can send data. In the current example
the client sends the message "Hi my server". To terminate the connection, the client sends the
message "bye". Then the server sends the message "bye" too. Finally the connection is ended
and the server waits for an other connection. The two programs should be runned in the same
machine. however if you want to run them in two different machines, you may simply change
the adress "localhost" by the IP adress of the machine where you will run the server.
The server
import [Link].*;
import [Link].*;
public class Provider{
ServerSocket providerSocket;
Socket connection = null;
ObjectOutputStream out;
ObjectInputStream in;
String message;
Provider(){}
void run()
{
try{
//1. creating a server socket
providerSocket = new ServerSocket(2004, 10);
//2. Wait for connection
[Link]("Waiting for connection");
connection = [Link]();
[Link]("Connection received from " +
[Link]().getHostName());
//3. get Input and Output streams
out = new ObjectOutputStream([Link]());
[Link]();
in = new ObjectInputStream([Link]());
sendMessage("Connection successful");
//4. The two parts communicate via the input and output
streams
do{
try{
message = (String)[Link]();
[Link]("client>" + message);
if ([Link]("bye"))
sendMessage("bye");
}
catch(ClassNotFoundException classnot){
[Link]("Data received in unknown
format");
}
}while();
}
catch(IOException ioException){
[Link]();
}
finally{
//4: Closing connection
try{
[Link]();
[Link]();
[Link]();
}
catch(IOException ioException){
[Link]();
}
}
}
void sendMessage(String msg)
{
try{
[Link](msg);
[Link]();
[Link]("server>" + msg);
}
catch(IOException ioException){
[Link]();
}
}
public static void main(String args[])
{
Provider server = new Provider();
while(true){
[Link]();
}
}
}
The client
import [Link].*;
import [Link].*;
public class Requester{
Socket requestSocket;
ObjectOutputStream out;
ObjectInputStream in;
String message;
Requester(){}
void run()
{
try{
//1. creating a socket to connect to the server
requestSocket = new Socket("localhost", 2004);
[Link]("Connected to localhost in port 2004");
//2. get Input and Output streams
out = new
ObjectOutputStream([Link]());
[Link]();
in = new ObjectInputStream([Link]());
//3: Communicating with the server
do{
try{
message = (String)[Link]();
[Link]("server>" + message);
sendMessage("Hi my server");
message = "bye";
sendMessage(message);
}
catch(ClassNotFoundException classNot){
[Link]("data received in unknown
format");
}
}while();
}
catch(UnknownHostException unknownHost){
[Link]("You are trying to connect to an unknown
host!");
}
catch(IOException ioException){
[Link]();
}
finally{
//4: Closing connection
try{
[Link]();
[Link]();
[Link]();
}
catch(IOException ioException){
[Link]();
}
}
}
void sendMessage(String msg)
{
try{
[Link](msg);
[Link]();
[Link]("client>" + msg);
}
catch(IOException ioException){
[Link]();
}
}
public static void main(String args[])
{
Requester client = new Requester();
[Link]();
}
}
Practical No. 8
For Sender:-
import [Link].*;
import [Link].*;
public class Sender{
Socket requestSocket;
ObjectOutputStream out;
ObjectInputStream in;
String message;
boolean check=true;
Sender(){}
void run()
{
try{
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
//1. creating a socket to connect to the server
requestSocket = new Socket("localhost", 2004);
[Link]("Connected to localhost in port 2004");
//2. get Input and Output streams
out = new ObjectOutputStream([Link]());
[Link]();
in = new ObjectInputStream([Link]());
//3: Communicating with the server
message = (String)[Link]();
[Link]("server>" + message);
do{
try{
[Link]("Enter binary number to send:");
message = [Link]();
if(checkbinary(message)){
check=false;
[Link]("checksum >"+checksum([Link]("000")) );
message=[Link](checksum([Link]("000")));
sendMessage(message);
}else{
[Link]("Entered data is not in binary format.\n Re" );
}
}
catch(Exception classNot){
[Link]("data received in unknown format"+classNot);
}
}while(check);
try{
[Link]("Data sent" );
message = (String)[Link]();
[Link]("server>" + message);
}catch(Exception e){}
}
catch(UnknownHostException unknownHost){
[Link]("You are trying to connect to an unknown host!");
}
catch(IOException ioException){
[Link]();
}
catch(Exception e){}
finally{
//4: Closing connection
try{
[Link]();
[Link]();
[Link]();
}
catch(IOException ioException){
[Link]();
}
}
}
boolean checkbinary(String str){
int n=[Link](str);
int len=[Link]();
int sum=0;
for(int i=0;i<len;i++){
sum=n%10;
if(sum>1) return false;
}
return true;
}
String checksum(String str){
int[] a=new int[20];
int n=[Link]();
for(int i=0;i<n;i++){
a[i]=[Link]([Link](i,i+1));
}
for(int i=0;i<n-3;i++){
if(a[i]==1){
a[i]=(a[i]==1)?0:1;
a[i+1]=(a[i+1]==1)?1:0;
a[i+2]=(a[i+2]==1)?0:1;
a[i+3]=(a[i+3]==1)?0:1;
}
}
str=[Link](a[n-3]);
str=[Link]([Link](a[n-2]));
str=[Link]([Link](a[n-1]));
return str;
}
void sendMessage(String msg)
{
try{
[Link](msg);
[Link]();
[Link]("client>" + msg);
}
catch(IOException ioException){
[Link]();
}
}
public static void main(String args[])
{
Sender client = new Sender();
[Link]();
}
}
For Receiver:-
import [Link].*;
import [Link].*;
public class Reciever{
ServerSocket RecieverSocket;
Socket connection = null;
ObjectOutputStream out;
ObjectInputStream in;
String message,checksum;
Reciever(){}
void run()
{
try{
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
//1. creating a server socket
RecieverSocket = new ServerSocket(2004, 10);
//2. Wait for connection
[Link]("Waiting for connection");
connection = [Link]();
[Link]("Connection received from " +
[Link]().getHostName());
//3. get Input and Output streams
out = new ObjectOutputStream([Link]());
[Link]();
in = new ObjectInputStream([Link]());
sendMessage("Connection successful ...");
//4. The two parts communicate via the input and output streams
//do{
try{
message = (String)[Link]();
[Link]("client>" + message);
checksum=checksum(message);
message=([Link]("000"))?"correct data":"corrupted data";
sendMessage(message);
}
catch(ClassNotFoundException classnot){
[Link]("Data received in unknown format");
}
//}while();
}
catch(IOException ioException){
[Link]();
}
finally{
//4: Closing connection
try{
[Link]();
[Link]();
[Link]();
}
catch(IOException ioException){
[Link]();
}
}
}
String checksum(String str){
int[] a=new int[20];
int n=[Link]();
for(int i=0;i<n;i++){ //convwrting string message into integer ARRAY
a[i]=[Link]([Link](i,i+1));
}
for(int i=0;i<n-3;i++){ //xor operation with 1011
if(a[i]==1){
a[i]=(a[i]==1)?0:1;
a[i+1]=(a[i+1]==1)?1:0;
a[i+2]=(a[i+2]==1)?0:1;
a[i+3]=(a[i+3]==1)?0:1;
}
}
str=[Link](a[n-3]);
str=[Link]([Link](a[n-2]));
str=[Link]([Link](a[n-1]));
return str;
}
void sendMessage(String msg)
{
try{
[Link](msg);
[Link]();
[Link]("server>" + msg);
}
catch(IOException ioException){
[Link]();
}
}
public static void main(String args[])
{
Reciever server = new Reciever();
while(true){
[Link]();
}
}
}
Practical No. 9
Establish a JAVA Socket Connection for shortest path between two nodes using
Dijkstra’s algorithm Sender and Receiver.
import [Link].*;
public class Dijkstra{
/*this function show the network in matrix form which you entered*/
public static void showNetworkMatrix(int m[][],int n){
[Link]("\n\nNetwork Matrix 1st row and colomn showing nodes(or hops) id\n\n");
for(int i=0;i<=n;i++){
for(int j=0;j<=n;j++){
if(i==0&&j==0)
[Link]("nodes- ");
else if(j==0)[Link](m[i][j]+" ");
else [Link](m[i][j]+" ");
}
[Link]();
}
}
}
}
showNetworkMatrix(network,n);
int c;//just a variable used to determine error
do{
[Link](" Enter the source node id : ");
c=[Link]([Link]());
if(c==0||c>n)
[Link]("Entered wrong id number not available in [Link] again.\n Re");
}while(c==0||c>n);
int s=c;//source node id variable
do{
[Link](" Enter the destination node id : ");
c=[Link]([Link]());
if(c==0||c>n)
[Link]("Entered wrong id number not available in [Link] again.\n Re");
}while(c==0||c>n);
int d=c;//destination node id variable
int []dist=new int[n+1];//distance from source
int []pred=new int[n+1];//predecessor of the vertex;
for(int i=1;i<=n;i++){
dist[i]=-1;//no path
pred[i]=-1;//no predecessor
}
if(DijkstraAlgo(network,n,s,d,dist,pred)==1){
for(int i=1;i<=n;i++){
[Link](i+" "+dist[i]+" ");
[Link](pred[i]+"\n");
}
//path
[Link](d+"<--");
while(pred[d]!=-1){
[Link](pred[d]+"<--");
d=pred[d];
}
[Link]("Start\n");
}
else{
[Link]("No path exists ");
}
}
}
Practical No. 10
For Sender:-
import [Link].*;
import [Link].*;
public class Sender{
Socket sender;
ObjectOutputStream out;
ObjectInputStream in;
String packet,ack,str, msg;
int n,i=0,sequence=0;
Sender(){}
public void run(){
try{
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
[Link]("Waiting for Connection....");
sender = new Socket("localhost",2004);
sequence=0;
out=new ObjectOutputStream([Link]());
[Link]();
in=new ObjectInputStream([Link]());
str=(String)[Link]();
[Link]("reciver > "+str);
[Link]("Enter the data to send....");
packet=[Link]();
n=[Link]();
do{
try{
if(i<n){
msg=[Link](sequence);
msg=[Link]([Link](i,i+1));
}
else if(i==n){
msg="end";[Link](msg);break;
}
[Link](msg);
/*
chenging sequence number since data sent
*/
sequence=(sequence==0)?1:0;
[Link]();
[Link]("data sent>"+msg);
ack=(String)[Link]();
[Link]("waiting for ack.....\n\n");
if([Link]([Link](sequence))){
i++;
[Link]("receiver > "+" packet recieved\n\n");
}
else{ /* whenever ack lost or wrong ack we change the sequence number
*/
[Link]("Time out resending data....\n\n");
sequence=(sequence==0)?1:0;
}
}catch(Exception e){}
}while(i<n+1);
[Link]("All data sent. exiting.");
}catch(Exception e){}
finally{
try{
[Link]();
[Link]();
[Link]();
}catch(Exception e){}
}
}
public static void main(String args[]){
Sender s=new Sender();
[Link]();
}
}
For Receiver:-
import [Link].*;
import [Link].*;
public class Reciever{
ServerSocket reciever;
Socket connection=null;
ObjectOutputStream out;
ObjectInputStream in;
String packet,ack,data="";
int i=0,sequence=0;
Reciever(){}
public void run(){
try{
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
reciever = new ServerSocket(2004,10);
[Link]("waiting for connection...");
connection=[Link]();
sequence=0;
[Link]("Connection established :");
out=new ObjectOutputStream([Link]());
[Link]();
in=new ObjectInputStream([Link]());
[Link]("connected .");
do{
try{
packet=(String)[Link]();
if([Link]([Link](0,1))==sequence){
data+=[Link](1);
sequence=(sequence==0)?1:0;
[Link]("\n\nreceiver >"+packet);
}else{
[Link]("\n\nreceiver >"+packet +" duplicate data");
}
/*
when i==3 then i destroy the ack
*/
if(i<3){
[Link]([Link](sequence));i++;
}else{
[Link]([Link]((sequence+1)%2));i=0;
}
}catch(Exception e){}
}while();
[Link]("Data recived="+data);
[Link]("connection ended .");
}catch(Exception e){}
finally{
try{
[Link]();
[Link]();
[Link]();
}catch(Exception e){}
}
}
public static void main(String args[]){
Reciever s=new Reciever();
while(true){
[Link]();
}
}
}