Unix Networking Programming
Unix Networking Programming
Unix Networking Programming
Table of Contents
Syllabus...................................................................................................................... 2
8CS5 UNIX NETWORK PROGRAMMING & SIMULATION LAB.........................................3
1.
2.
3.
4.
5.
6.
7.
2
Syllabus
3
8CS5 UNIX NETWORK PROGRAMMING &
SIMULATION LAB
S.
No.
1.
2.
3.
Experiment Title
4.
5.
6.
7.
Introduction to NS2
8.
4
1.
A socket is one of the most fundamental technologies of computer networking. Sockets allow
applications to communicate using standard mechanisms built into network hardware and
operating systems. Although network software may seem to be a relatively new "Web"
phenomenon, socket technology actually has been employed for roughly two decades.
Software applications that rely on the Internet and other computer networks continue to grow in
popularity. Many of today's most popular software packages -- including Web browsers, instant
messaging applications and peer to peer file sharing systems -- rely on sockets.
Point-to-Point Communication
In a nutshell, a socket represents a single connection between exactly two pieces of software.
More than two pieces of software can communicate in client/server or distributed systems (for
example, many Web browsers can simultaneously communicate with a single Web server) but
multiple sockets are required to do this. Socket-based software usually runs on two separate
computers on the network, but sockets can also be used to communicate locally (interprocess) on
a single computer.
Sockets are bidirectional, meaning that either side of the connection is capable of both sending
and receiving data. Sometimes the one application that initiates communication is termed the
client and the other application the server, but this terminology leads to confusion in nonclient/server systems and should generally be avoided.
Libraries
Programmers access sockets using code libraries packaged with the operating system. Several
libraries that implement standard application programming interfaces (APIs) exist. The first
mainstream package - the Berkeley Socket Library is still widely in use on UNIX systems.
Another very common API is the Windows Sockets (Winsock) library for Microsoft operating
systems. Relative to other network programming technologies, socket APIs are quite mature:
Winsock has been in use since 1993 and Berkeley sockets since 1982.
Interface Types
Socket interfaces can be divided into three categories. Perhaps the most commonly-used type,
the stream socket, implements "connection-oriented" semantics. Essentially, a "stream" requires
that the two communicating parties first establish a socket connection, after which any data
passed through that connection will be guaranteed to arrive in the same order in which it was
sent.
Datagram sockets offer "connection-less" semantics. With datagrams, connections are implicit
rather than explicit as with streams. Either party simply sends datagrams as needed and waits for
5
the other to respond; messages can be lost in transmission or received out of order, but it is the
application's responsibility and not the socket's to deal with these problems. Implementing
datagram sockets can give some applications a performance boost and additional flexibility
compared to using stream sockets, justifying their use in some situations.
The third type of socket -- the so-called raw socket -- bypasses the library's built-in support for
standard protocols like TCP and UDP. Raw sockets are used for custom low-level protocol
development.
6
2.Java - Networking (Socket Programming)
The term network programming refers to writing programs that execute across multiple devices
(computers), in which the devices are all connected to each other using a network.
The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide
the low-level communication details, allowing you to write programs that focus on solving the
problem at hand.
The java.net package provides support for the two common network protocols:
TCP: TCP stands for Transmission Control Protocol, which allows for reliable communication
between two applications. TCP is typically used over the Internet Protocol, which is referred to
as TCP/IP.
UDP: UDP stands for User Datagram Protocol, a connection-less protocol that allows for
packets of data to be transmitted between applications.
This tutorial gives good understanding on the following two subjects:
Socket Programming: This is most widely used concept in Networking and it has been
explained in very detail.
URL Processing: This would be covered separately. Click here to learn about URL
Processing in Java language.
Socket Programming:
Sockets provide the communication mechanism between two computers using TCP. A client
program creates a socket on its end of the communication and attempts to connect that socket to
a server.
When the connection is made, the server creates a socket object on its end of the communication.
The client and server can now communicate by writing to and reading from the socket.
The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a
mechanism for the server program to listen for clients and establish connections with them.
The following steps occur when establishing a TCP connection between two computers using
sockets:
i.
ii.
iii.
7
iv.
v.
The constructor of the Socket class attempts to connect the client to the specified server
and port number. If communication is established, the client now has a Socket object
capable of communicating with the server.
On the server side, the accept() method returns a reference to a new socket on the server
that is connected to the client's socket.
After the connections are established, communication can occur using I/O streams. Each socket
has both an OutputStream and an InputStream. The client's OutputStream is connected to the
server's InputStream, and the client's InputStream is connected to the server's OutputStream.
TCP is a two way communication protocol, so data can be sent across both streams at the same
time. There are following usefull classes providing complete set of methods to implement
sockets.
8
SN Methods with Description
public int getLocalPort()
1. Returns the port that the server socket is listening on. This method is useful if you passed in
0 as the port number in a constructor and let the server find a port for you.
public Socket accept() throws IOException
Waits for an incoming client. This method blocks until either a client connects to the server
2.
on the specified port or the socket times out, assuming that the time-out value has been set
using the setSoTimeout() method. Otherwise, this method blocks indefinitely
3.
When the ServerSocket invokes accept(), the method does not return until a client connects.
After a client does connect, the ServerSocket creates a new Socket on an unspecified port and
returns a reference to this new Socket. A TCP connection now exists between the client and
server, and communication can begin.
9
IOException.
Connects to the specified host and port, creating a socket on the local host at the specified
address and port.
public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws
IOException.
4.
This method is identical to the previous constructor, except that the host is denoted by an
InetAddress object instead of a String
5.
public
Socket()
Creates an unconnected socket. Use the connect() method to connect this socket to a server.
When the Socket constructor returns, it does not simply instantiate a Socket object but it actually
attempts to connect to the specified server and port.
Some methods of interest in the Socket class are listed here. Notice that both the client and server
have a Socket object, so these methods can be invoked by both the client and server.
SN Methods with Description
public void connect(SocketAddress host, int timeout) throws IOException
1. This method connects the socket to the specified host. This method is needed only when you
instantiated the Socket using the no-argument constructor.
2.
3.
4.
5.
10
public void close() throws IOException
8. Closes the socket, which makes this Socket object no longer capable of connecting again to
any server
2.
3.
4.
String getHostAddress()
Returns the IP address string in textual presentation.
5.
String getHostName()
Gets the host name for this IP address.
6.
7.
String toString()
Converts this IP address to a String.
11
public class GreetingClient
{
public static void main(String [] args)
{
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try
{
System.out.println("Connecting to " + serverName
+ " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out =
new DataOutputStream(outToServer);
12
{
e.printStackTrace();
}
}
}
Socket Server Example:
The following GreetingServer program is an example of a server application that uses the Socket
class to listen for clients on a port number specified by a command-line argument:
// File Name GreetingServer.java
import java.net.*;
import java.io.*;
13
try
{
System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to "
+ server.getRemoteSocketAddress());
DataInputStream in =
new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out =
new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to "
+ server.getLocalSocketAddress() + "\nGoodbye!");
server.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
14
public static void main(String [] args)
{
int port = Integer.parseInt(args[0]);
try
{
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
15
3.TCP Socket Example
16
17
class TCPServer
18
{
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(
new InputStreamReader(
connectionSocket.getInputStream()));
DataOutputStream outToClient =
new DataOutputStream(
connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
}
19
}
TCP client code:
import java.io.*;
import java.net.*;
class TCPClient
{
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
BufferedReader inFromUser
InputStreamReader(System.in));
DataOutputStream outToServer =
new DataOutputStream(
clientSocket.getOutputStream());
BufferedReader inFromServer =
new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
new
BufferedReader(new
20
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
clientSocket.close();
}
}
To Compile
javac TCPServer.java
javac TCPClient.java
To Run
Server:
java TCPServer
Client:
java TCPClient
hello how are you [Enter]
21
4.UDP Socket Programming for Client_Hello and
Server_Hello
UDP Socket Example
UDP client/server communication flow:
22
UDPServer.java communication model:
class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket =
new DatagramSocket(9876);
23
while(true)
{
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
24
UDP client code:
import java.io.*;
import java.net.*;
class UDPClient
{
public static void main(String args[]) throws Exception
{
BufferedReader inFromUser =
new BufferedReader(
new InputStreamReader(System.in));
byte[] sendData;
sendData = sentence.getBytes();
25
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length,
IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
clientSocket.close();
}
}
Running the Server and Client
To Compile
javac UDPServer.java
javac UDPClient.java
To Run
Server:
26
java UDPServer
Client:
java UDPClient
hello how are you [Enter]
27
5. UDP Socket Programming for Echo_Client and
Echo_Server
UDP client/server communication flow:
28
UDPServer.java communication model:
class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket =
new DatagramSocket(9876);
29
while(true)
{
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length,
IPAddress, port);
serverSocket.send(sendPacket);
}
30
}
}
UDP client code:
import java.io.*;
import java.net.*;
class UDPClient
{
public static void main(String args[]) throws Exception
{
BufferedReader inFromUser =
new BufferedReader(
new InputStreamReader(System.in));
byte[] sendData;
31
sendData = sentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length,
IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
clientSocket.close();
}
}
32
6.Sending Mail Using UDP Sockets
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class SMTPDemo {
public static void main(String args[]) throws IOException,
UnknownHostException {
String msgFile = "file.txt";
String from = "java2s@java2s.com";
String to = "yourEmail@yourServer.com";
String mailHost = "yourHost";
SMTP mail = new SMTP(mailHost);
if (mail != null) {
if (mail.send(new FileReader(msgFile), from, to)) {
System.out.println("Mail sent.");
} else {
System.out.println("Connect to SMTP server failed!");
}
}
System.out.println("Done.");
}
static class SMTP {
private final static int SMTP_PORT = 25;
InetAddress mailHost;
33
InetAddress localhost;
BufferedReader in;
PrintWriter out;
public SMTP(String host) throws UnknownHostException {
mailHost = InetAddress.getByName(host);
localhost = InetAddress.getLocalHost();
System.out.println("mailhost = " + mailHost);
System.out.println("localhost= " + localhost);
System.out.println("SMTP constructor done\n");
}
public boolean send(FileReader msgFileReader, String from, String to)
throws IOException {
Socket smtpPipe;
InputStream inn;
OutputStream outt;
BufferedReader msg;
msg = new BufferedReader(msgFileReader);
smtpPipe = new Socket(mailHost, SMTP_PORT);
if (smtpPipe == null) {
return false;
}
inn = smtpPipe.getInputStream();
outt = smtpPipe.getOutputStream();
in = new BufferedReader(new InputStreamReader(inn));
out = new PrintWriter(new OutputStreamWriter(outt), true);
if (inn == null || outt == null) {
System.out.println("Failed to open streams to socket.");
return false;
}
String initialID = in.readLine();
System.out.println(initialID);
System.out.println("HELO " + localhost.getHostName());
out.println("HELO " + localhost.getHostName());
String welcome = in.readLine();
System.out.println(welcome);
System.out.println("MAIL From:<" + from + ">");
34
out.println("MAIL From:<" + from + ">");
String senderOK = in.readLine();
System.out.println(senderOK);
System.out.println("RCPT TO:<" + to + ">");
out.println("RCPT TO:<" + to + ">");
String recipientOK = in.readLine();
System.out.println(recipientOK);
System.out.println("DATA");
out.println("DATA");
String line;
while ((line = msg.readLine()) != null) {
out.println(line);
}
System.out.println(".");
out.println(".");
String acceptedOK = in.readLine();
System.out.println(acceptedOK);
System.out.println("QUIT");
out.println("QUIT");
return true;
}
}
}
35
7.Network Simulator 2
About Simulator and NS-2
Fundamentally, there are various techniques available to analyze the behavior of wired and
wireless networks, primarily these techniques are Analytical Modeling, Real Time Physical
Measurements and Computer Simulations etc..
A. Analytical Modeling: Analytical models are mathematical models that have a closed
form solution, i.e. the solution to the equations used to describe changes in a system can
be expressed as a mathematical analytic function. Mathematical models can help students
understand and explore the meaning of equations or functional relationships. After
developing a conceptual model of a physical system it is natural to develop a
mathematical model that will allow one to estimate the quantitative behavior of the
system. It is very tedious.
Statistical Models: Statistical models can be used to characterize numerical output from
mathematical models to help understand the model behavior and to assess the model's
ability to simulate important features of the natural system (model validation). Feeding
this information back into the model development process will enhance model
performance. Statiscal model is used to estimate probabilistic future behavior of a system
based on past statistical information, a statistical prediction model. The goal of
developing an analytical model is to predict the performance of an application given a
new machine specified by some hardware parameters.
B. Real Time Physical Measurements: Time is an essential part of the measuring system
used to sequence events, to compare the durations of events and the intervals between
them, and to quantify the motions of objects. It is the state of things as they actually exist,
rather than as they may appear or may be thought to be. It may not be possible all the
time.
C. Computer Simulations: Computer Simulations is a practical approach to the quantitative
analysis of a network. Simulation is usually a software package that runs on a computer
for the purpose of simulating some sort of system, in order to get a better idea how the
system functions. During the last decade simulation has become a very powerful and an
important tool for planning, designing and controlling complex system. Nowadays an
error in real life costs a lot of money.
A network simulator is a software program that imitates the working of a computer network. In
simulators, the computer network is typically modelled with devices, traffic etc and the
performance is analysed. Typically, users can then customize the simulator to fulfill their specific
analysis needs. Simulators typically come with support for the most popular protocols in use
today.
36
Network simulators serve a variety of needs. Compared to the cost and time involved in setting
up an entire test bed containing multiple networked computers, routers and data links, network
simulators are relatively fast and inexpensive. They allow researcher/engineers to test scenarios
that might be particularly difficult or expensive to emulate using real hardware- for instance,
simulating the effects of a sudden burst in traffic or a DoS attack on a network service.
NS-2 Network Simulator is very popular and its is freely available for academic research
purpose, some other notable simulation software for wireless networks are (1) Global Mobile
Network Simulator (GloMoSim) (2) OPNET (3) OMNET (4) NetSim etc.
NS-2 started as a variant of the REAL network simulator in 1989 and has since been supported
by the Virtual InterNetwork Testbed (VINT) project that is a DARPA-funded research project
whose aim is to build a network simulator. The first version of NS was for wired networks but
the demand to support wireless networking made the Monarch Group to create new version NS2.
NS-2 allows for the simulation of various protocols, applications, routing, queue types etc. A
graphical front end has been developed for use with NS known as Network Animator (NAM).
Alternatively trace files can be created for analysis, which can be displayed using Gnuplot,
tracegraph orXgraph even Microsoft Excel can also be used for this purpose.
Network Simulator - 2 (NS-2) is an event driven, discrete object oriented and packet level
simulator developed at UC Berkeley is used by networking researcher to simulate and analyze
the performance of wired, wireless and satellite networks. NS-2 is an open source network
simulator which is use to build different network prototype. Ns2 support simulation of different
network protocols as TCP,UDP, traffic sources FTP, web, CBRand routing and multicast
protocols over wired and wireless (802.11 for wireless) networks.
The core engine is used C++ code and OTcl for configuration and simulation the scripts in NS-2.
37
performs multicast routing. To create Multicast nodes the user must notify in the input
OTcl script.
The following table shows the node types that are used in NS.
B. Network Protocols: A protocol is a set of rules use to talk to each other. Network protocol
is a group of technologies' rules to communication to each computer or device. NS-2
supports almost all different versions of TCP, multicast, wired networking, routing and
wireless protocols. The following table shows the some examples of protocols. Protocols
Description Internet Protocol (IP) It is a transmission mechanism used by the TCP/IP.
This is a unreliable, connectionless and a data-oriented protocol that communicates data
38
across a network which is used by both source and host. It comes in two versions IPV4
and IPV6.
39
40
C. Constant Bit Rate (CBR) data transfer: CBR is a bandwidth-allocation service that
requiresthe user to determine the bandwidth at the time the connection is set up. CBR
reservesa constant amount of bandwidth at the time of connection set up so that the data
can be sent in a steady stream. This form of data transfer is often used when transmitting
uncompressed voice and video which require jitter (small time variations) over a network
as it keeps the video streaming at a constant rate. The source may send at a negotiated or
41
lower rate at any time and for any duration. The connection in Ns would normally be set
up with a UDP agent and the traffic source would be CBR.
D. Traffic Generator Function: Traffic Generator is a tool for generating artificial traffic for
a network simulation. It use for measurement and testing the network. A traffic generator
function has two parts; the source is the agent which is the originator of the packets sent
down the network. The packets are sent along the network and end up in the sink which
has a Null agent attached; the sink is the destination for the packets. Currently, there are
four C++ classes built into NS-2 which provide traffic generator functions are all derived
from the base class TrafficGenerator. These traffic generator functions are shown in
following table.
NS2 Programming
Here we are providing a 'providing a 'providing a 'providing a 'template' that we can use it for all
tcl scripts. We will introduce basics of how to create event scheduler, create a simple pair of
nodes and make communication between the two nodes. Then we will introduce a standard
template for all tcl scripts with simple examples.
In this page we are going to introduce the concepts of:
42
FTP over TCP
Part of Introduction to TCP/IP model
Application Layer : CBR,FTP,telnet..
Transport layer : TCP,UDP
Network layer : rtproto
Data link Layer: Transmission mode,
Physical layer
TCP/IP model
Application Layer: Applications agents are Telnet, FTP, Rlogin, CBR
Transport Layer: The transport uses two protocols, UDP and TCP. UDP which stands for User
Datagram Protocol does not guarantee packet delivery and applications which use this must
provide their own means of verifying delivery. TCP does guarantee delivery of packets to the
applications which use it.
Network Layer: The network layer is concerned with packet routing and used low level protocols
such as ICMP, IP, and IGMP. Here Network protocols are omitted for simple examples
Link Layer: The link layer is concerned with the actual transmittal of packets as well as IP to
Ethernet address translation. Data transfer in two modes i.e. simplex mode and in duplex mode.
All the links are created at data link layer. Network layer next is to data link layer.
Where can you write Scripts?;
After login into terminal, follow step given below
1) vi filename.tcl
It will open page, there you can write tcl scripts.
2) save file
Press esc-> colon (shift + semicolon) ->wq (save and quit)
It save the file
3) To run tcl script
ns filename.tcl
43
Basically NS 2 programming contains the following steps.
1) Create the event scheduler
2) Turn on tracing
3) Creating network
a. Computing setup routing - rtproto
b. Creating transport connection-Agents
c. Creating traffic-Applications
4) Monitoring
a. Visualization using nam
Note: every tcl script must write in small letters only except protocol agents i.e. TCP, FTP
Template
Every ns2 script starts with creating simulator object
44
Two types of trace
1) generic trace
for use with xgraph, and other things
2) nam trace
for use with visualization
# open trace file
set tracefile [open out.tr w]
$ns trace-all $tracefile
#Open the nam trace file
set nf [open out.nam w]
$ns namtrace-all $nf
Since we have started tracing, we should end also. For this we use finish procedure.
#Define a 'finish' procedure
proc finish {}
{
global ns tracefile nf
$ns flush-trace
close $nf
close $tracefile
# close tracefile
45
Every tcl script must contain following statement
$ns run
Golden rules
Follow the template tcl like Bible.
All communication between 2 agents.
Upper layer to lower layer, we attach agents.
Same layer in two nodes, we connect agents.
Agents are tcp, udp, telnet, cbretc
UDP communication
In UDP communication, data is flows from UDP agent to Null agent.
46
47
Traffic generator cbr0 will stops at 4.0
Simple Examples
So far we are not talking about data flow. Here we will explain with CBR protocol.
48
Result
Before 1.0ms
After 1.0ms
49
Example 2:(CBR over TCP)
Result:
50
Before 1.0ms
After 1.0ms
51
Example3:(FTP over TCP)
Result:
Here we are using FTP Application agent as a traffic generator instead of CBR. The difference is
CBR traffic generator will produce constant bit rate where as FTP traffic generator produces
maximum available bit rate.
We are writing code
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
and Similarly for telnet also
set telneto [new Application/TELNET]
$ftp0 attach-agent $telnet0
52
Instead of CBR
set cbr0 [new Application/Traffic/CBR]
$cbr0 attach-agent $tcp0
Before 1.0ms
After 1.0ms