Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

Sri Balaji College Of Engineering and

technology, Banad Road Jaipur

Lab Manual
UNPS Lab
(8CS5A)

1
UNIX Network Programming And Simulation Lab

Experiments :

1.Write two programs : hello_client and hello_server

• The server listens for, and accepts, a single TCP connection; it reads all the data
it can from that connection, and prints it to the screen; then it closes the
connection
• The client connects to the server, sends the string “Hello, world!”, then closes
the connection

2. Write an Echo_Client and Echo_server using TCP to estimate the round trip time from
client to the server. The server should be such that it can accept multiple connections at
any given time.

3. Repeat Exercises 1 & 2 for UDP.

4. Repeat Exercise 2 with multiplexed I/O operations

5. Simulate Bellman-Ford Routing algorithm in NS2

2
Ex-1. To write a C-program to implement Client – Server communication using RPC.

DESCRIPTION
A remote procedure call (RPC) is an inter-process communication that allows a computer
program to cause a subroutine or procedure to execute in another address space (commonly on
another
computer on a shared network) without the programmer explicitly coding the details for this
remote
interaction.
In RPC, the sender makes a request in the form of a procedure, function, or method call. RPC
translates
these calls into requests sent over the network to the intended destination.

The RPC recipient then processes the request based on the procedure name and argument list,
sending a
response to the sender when complete.

The process is initiated by the client, which sends a request message to a known remote
server to
execute a specified procedure with supplied parameters.

The remote server sends a response to the client, and the application continues its process.
While the server is processing the call, the client is blocked, it waits until the server has
finished
processing before resuming execution.

ALGORITHM:
Server:
Step 1: Start the program
Step 2: Create a socket with address family AF_INET type SOCK_STREAM and
default protocol.
Step 3: Initialize a socket and set its attributes.
Step 4: Bind the server to the socket using bind function.
Step 5: wait for the client request, on request establish a connection using accept
function.
Step 6: Read the number from the client by using read method
Step 7: Display the no.
Step 8: add the digits of a given number.
Step 9: send the result to the client by using write method

3
Step 10: stop the program.

Client:
Step 1: start.
Step 2: create a socket with address family.
Step 3: Initialize the socket and set its attributes set the required port no.
Step 4: Type AF_INET socket with default protocol.
Step 5: Connect to server using connect function to initiate the request.
Step 6: send a no to the server using write method.
Step 7: receive the result using read method.
Step 8: stop

PROGRAM:
//Server.c
#include<stdio.h>
#include<stdlib.h>
#include<netdb.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<string.h>
#include<errno.h>
#include<math.h>
int main(int argc,char **argv)
{
struct sockaddr_in servaddr,cliaddr;
char buff[1024],str[1024];
int len,len1,listenfd,connfd,n,i;
int count=0;
int no,sum=0;
listenfd=socket(AF_INET,SOCK_STREAM,0);
if(listenfd<0)
{
printf("Socket Error");
exit(0);
}
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;

4
servaddr.sin_port=htons(20003);
servaddr.sin_addr.s_addr=inet_addr("192.168.0.250");
bind(listenfd,&servaddr,sizeof(servaddr));
listen(listenfd,5);
len=sizeof(cliaddr);
connfd=accept(listenfd,(struct sockaddr*)&cliaddr,&len);
n=read(connfd,buff,1024);
printf("Received no is \t %s\n",buff);
no=atoi(buff);
printf("no=%d\n",no4);
while(no>0)
{
sum+=no%10;

no=no/10;
}
sprintf(buff,"%d",sum);
n=write(connfd,buff,1024);
close(listenfd);
return 0;
}
//Client.c
#include<stdio.h>
#include<stdlib.h>
#include<netdb.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<string.h>
#include<errno.h>
int main(int argc,char **argv)
{
struct sockaddr_in servaddr,cliaddr;
char buff[1024],str[1000];
int len,sockfd,n;
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd<0)
printf("Socket Error");
bzero(&servaddr,sizeof(servaddr));

5
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(20003);
servaddr.sin_addr.s_addr=inet_addr("192.168.0.250");
connect(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr));
printf("\nenter a number\t");
scanf("%s",buff);
n=write(sockfd,buff,1024);
n=read(sockfd,buff,1024);
printf("\nResult is \t%s",buff);
close(sockfd);
return 0;
}
OUTPUT
Server
[admin@localhost admin]$ cc Server.c
rpcserv.c: In function `main':
rpcserv.c:30: warning: passing arg 2 of `bind' from incompatible pointer type
[admin@localhost admin]$
[admin@localhost admin]$ ./a.out
Received no is 879
no4=879
Client
[admin@localhost admin]$ cc Client.c
[admin@localhost admin]$ ./a.out

enter a no 879
Recived msg is 24

RESULT:
Thus the C-Program to implement Client - Server Communication using RPC was
executed and output verified using various samples.

Ex.2 Programs using TCP Sockets (like date and time server & client, echo server &
client, etc.)

Ex.No: 2. a PROGRAM USING TCP SOCKETS DATE AND TIME SERVER

AIM: To implement date and time display from client to server using TCP Sockets

6
DESCRIPTION:
TCP Server gets the system date and time and opens the server socket to read the
client
details. Client send its address to the server. Then client receives the date and time
from server to display. TCP socket server client connection is opened for
communication. After the date time is displayed the server client connection is closed
with its respective streams to be closed.

ALGORITHM:
Server
1. Create a server socket and bind it to port.
2. Listen for new connection and when a connection arrives, accept it.
3. Send server‟s date and time to the client.
4. Read client‟s IP address sent by the client.
5. Display the client details.
6. Repeat steps 2-5 until the server is terminated.
7. Close all streams.
8. Close the server socket.
9. Stop.
Client
1. Create a client socket and connect it to the server‟s port number.
2. Retrieve its own IP address using built-in function.
3. Send its address to the server.
4. Display the date & time sent by the server.
5. Close the input and output streams.
6. Close the client socket.
7. Stop.

PROGRAM:
//TCP Date Server--tcpdateserver.java
import java.net.*;
import java.io.*;
import java.util.*;
class tcpdateserver
{
public static void main(String arg[])
{

7
ServerSocket ss = null;
Socket cs;
PrintStream ps;
BufferedReader dis;
String inet;
try
{ ss = new ServerSocket(4444);

System.out.println("Press Ctrl+C to quit");


while(true)
{
cs = ss.accept();
ps = new PrintStream(cs.getOutputStream());
Date d = new Date();
ps.println(d);
dis = new BufferedReader(new
InputStreamReader(cs.getInputStream()));
inet = dis.readLine();
System.out.println("Client System/IP address is :"+ inet);
ps.close();
dis.close();
}
}
catch(IOException e)
{
System.out.println("The exception is :" + e);
}
}
}
// TCP Date Client--tcpdateclient.java
import java.net.*;
import java.io.*;
class tcpdateclient
{
public static void main (String args[])
{
Socket soc;
BufferedReader dis;
String sdate;
PrintStream ps;

8
try
{
InetAddress ia = InetAddress.getLocalHost();
if (args.length == 0)
soc = new Socket(InetAddress.getLocalHost(),4444);
else
soc = new Socket(InetAddress.getByName(args[0]),4444);
dis = new BufferedReader(new
InputStreamReader(soc.getInputStream()));
sdate=dis.readLine();
System.out.println("The date/time on server is : " +sdate);
ps = new PrintStream(soc.getOutputStream());
ps.println(ia);
ps.close(); catch(IOException e)
{
System.out.println("THE EXCEPTION is :" + e);
}}}

OUTPUT
Server:
$ javac tcpdateserver.java
$ java tcpdateserver
Press Ctrl+C to quit
Client System/IP address is : localhost.localdomain/127.0.0.1
Client System/IP address is : localhost.localdomain/127.0.0.1
Client:
$ javac tcpdateclient.java
$ java tcpdateclient
The date/time on server is: Wed Jul 06 07:12:03 GMT 2011
Every time when a client connects to the server, server‟s date/time will be returned
to the
client for synchronization.

RESULT:
Thus the program for implementing to display date and time from client to server
using
TCP Sockets was executed successfully and output verified using various samples.

Ex.No: 2.b Implementation of Client-Server Communication Using TCP

9
AIM:
To implement a chat server and client in java using TCP sockets.

DESCRIPTION:
TCP Clients sends request to server and server will receives the request and
response
with acknowledgement. Every time client communicates with server and receive
response from it.

ALGORITHM:
Server
1. Create a server socket and bind it to port.
2. Listen for new connection and when a connection arrives, accept it.
3. Read Client's message and display it
4. Get a message from user and send it to client
5. Repeat steps 3-4 until the client sends "end"
6. Close all streams
7. Close the server and client socket
8. Stop
Client
1. Create a client socket and connect it to the server‟s port number
2. Get a message from user and send it to server
3. Read server's response and display it
4. Repeat steps 2-3 until chat is terminated with "end" message
5. Close all input/output streams
6. Close the client socket
7. Stop

PROGRAM:
//Server.java
import java.io.*;
import java.net.*;
class Server {
public static void main(String args[]) {
String data = "Networks Lab";
try {

10
ServerSocket srvr = new ServerSocket(1234);
Socket skt = srvr.accept();
System.out.print("Server has connected!\n");
PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
System.out.print("Sending string: '" + data + "'\n");
out.print(data);
out.close();
skt.close();
srvr.close();
}
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}
}
}
//Client.java
import java.io.*;
import java.net.*;
class Client {
public static void main(String args[]) {
try {
Socket skt = new Socket("localhost", 1234);
BufferedReader in = new BufferedReader(new
InputStreamReader(skt.getInputStream()));
System.out.print("Received string: '");
while (!in.ready()) {}
System.out.println(in.readLine());
System.out.print("'\n");
in.close();
}
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}}}

OUTPUT
Server:
$ javac Server.java
$ java Server
Server started

11
Client connected
Cilent

$ javac Client.java
$ java Client
RESULT
Thus both the client and server exchange data using TCP socket programming.

Ex.No: 2. c IMPLEMENTATION OF TCP/IP ECHO

AIM: To implementation of echo client server using TCP/IP

DESCRIPTION:
TCP Server gets the message and opens the server socket to read the client details.
Client
send its address to the server. Then client receives the message from server to
display.

ALGORITHM
Server
1. Create a server socket and bind it to port.
2. Listen for new connection and when a connection arrives, accept it.
3. Read the data from client.
4. Echo the data back to the client.
5. Repeat steps 4-5 until „bye‟ or „null‟ is read.
6. Close all streams.
7. Close the server socket.
8. Stop.
Client
1. Create a client socket and connect it to the server‟s port number.
2. Get input from user.
3. If equal to bye or null, then go to step 7.
4. Send user data to the server.
5. Display the data echoed by the server.
6. Repeat steps 2-4.
7. Close the input and output streams.
8. Close the client socket.

12
9. Stop.

PROGRAM:

// TCP Echo Server--tcpechoserver.java


import java.net.*;
import java.io.*;
public class tcpechoserver
{
public static void main(String[] arg) throws IOException
{
ServerSocket sock = null;
BufferedReader fromClient = null;
OutputStreamWriter toClient = null;
Socket client = null;
try
{
sock = new ServerSocket(4000); System.out.println("Server Ready");

client = sock.accept(); System.out.println("Client Connected");


fromClient = new BufferedReader(new
InputStreamReader(client.getInputStream()));
toClient = new OutputStreamWriter(client.getOutputStream());
String line;
while (true)
{
line = fromClient.readLine();
if ( (line == null) || line.equals("bye"))
break;
System.out.println ("Client [ " + line + " ]");
toClient.write("Server [ "+ line +" ]\n");
toClient.flush();
}
fromClient.close();
toClient.close();
client.close();

13
sock.close();
System.out.println("Client Disconnected");
}
catch (IOException ioe)
{
System.err.println(ioe);
}
}
}
//TCP Echo Client--tcpechoclient.java
import java.net.*;
import java.io.*;
public class tcpechoclient
{
public static void main(String[] args) throws IOException
{
BufferedReader fromServer = null, fromUser = null;
PrintWriter toServer = null;
Socket sock = null;
try
{
if (args.length == 0)
sock = new Socket(InetAddress.getLocalHost(),4000);
else
sock = new Socket(InetAddress.getByName(args[0]),4000);
fromServer = new BufferedReader(new
InputStreamReader(sock.getInputStream()));
fromUser = new BufferedReader(new InputStreamReader(System.in));
toServer = new PrintWriter(sock.getOutputStream(),true);
String Usrmsg, Srvmsg;
System.out.println("Type \"bye\" to quit");
while (true)

{
System.out.print("Enter msg to server : ");
Usrmsg = fromUser.readLine();
if (Usrmsg==null || Usrmsg.equals("bye"))
{
toServer.println("bye"); break;
}

14
else
toServer.println(Usrmsg);
Srvmsg = fromServer.readLine();
System.out.println(Srvmsg);
}
fromUser.close();
fromServer.close();
toServer.close();
sock.close();
}
catch (IOException ioe)
{
System.err.println(ioe);
}

OUTPUT
Server:
$ javac tcpechoserver.java
$ java tcpechoserver
Server Ready Client Connected Client [ hello ]
Client [ how are you ] Client [ i am fine ] Client [ ok ]
Client Disconnected

Client :
$ javac tcpechoclient.java
$ java tcpechoclient
Type "bye" to quit
Enter msg to server : hello
Server [ hello ]
Enter msg to server : how are you
Server [ how are you ]
Enter msg to server : i am fine
Server [ i am fine ]
Enter msg to server : ok
Server [ ok ]
Enter msg to server : bye

RESULT

15
Thus data from client to server is echoed back to the client to check reliability/noise
level of the channel.

Ex .3 Programs using UDP Sockets

Ex.No: 3.a PROGRAM USING UDP SOCKET UDP CHAT SERVER/CLIENT

AIM:
To implement a chat server and client in java using UDP sockets.

DESCRIPTION:
UDP is a connectionless protocol and the socket is created for client and server to
transfer
the data. Socket connection is achieved using the port number. Domain Name System
is the naming convention that divides the Internet into logical domains identified in
Internet Protocol version 4 (IPv4) as a 32-bit portion of the total address.

ALGORITHM:
Server
1. Create two ports, server port and client port.
2. Create a datagram socket and bind it to client port.
3. Create a datagram packet to receive client message.
4. Wait for client's data and accept it.
5. Read Client's message.
6. Get data from user.
7. Create a datagram packet and send message through server port.
8. Repeat steps 3-7 until the client has something to send.
9. Close the server socket.
10. Stop.
Client
1. Create two ports, server port and client port.
2. Create a datagram socket and bind it to server port.
3. Get data from user.
4. Create a datagram packet and send data with server ip address and client port.
5. Create a datagram packet to receive server message.
6. Read server's response and display it.
7. Repeat steps 3-6 until there is some text to send.
8. Close the client socket.
9. Stop.

16
PROGRAM
// UDP Chat Server--udpchatserver.java
import java.io.*;
import java.net.*;
class udpchatserver
{
public static int clientport = 8040,serverport = 8050;
public static void main(String args[]) throws Exception
{
DatagramSocket SrvSoc = new DatagramSocket(clientport);
byte[] SData = new byte[1024];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Server Ready");
while (true)

{
byte[] RData = new byte[1024];
DatagramPacket RPack = new DatagramPacket(RData,RData.length);
SrvSoc.receive(RPack);
String Text = new String(RPack.getData());
if (Text.trim().length() == 0)
break;
System.out.println("\nFrom Client <<< " + Text );
System.out.print("Msg to Cleint : " );
String srvmsg = br.readLine();
InetAddress IPAddr = RPack.getAddress();
SData = srvmsg.getBytes();
DatagramPacket SPack = new DatagramPacket(SData,SData.length,IPAddr,
serverport);
SrvSoc.send(SPack);
}
System.out.println("\nClient Quits\n");
SrvSoc.close();
}
}
// UDP Chat Client--udpchatclient.java
import java.io.*;
import java.net.*;
class udpchatclient

17
{
public static int clientport = 8040,serverport = 8050;
public static void main(String args[]) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader (System.in));
DatagramSocket CliSoc = new DatagramSocket(serverport);
InetAddress IPAddr;
String Text;
if (args.length == 0)
IPAddr = InetAddress.getLocalHost();
else
IPAddr = InetAddress.getByName(args[0]);
byte[] SData = new byte[1024];
System.out.println("Press Enter without text to quit");
while (true)
{
System.out.print("\nEnter text for server : ");
Text = br.readLine();
SData = Text.getBytes();
DatagramPacket SPack = new DatagramPacket(SData,SData.length, IPAddr,
clientport );
CliSoc.send(SPack);
if (Text.trim().length() == 0)
break;
byte[] RData = new byte[1024];

DatagramPacket RPack = new DatagramPacket(RData,RData.length);


CliSoc.receive(RPack);
String Echo = new String(RPack.getData()) ;
Echo = Echo.trim();
System.out.println("From Server <<< " + Echo);
}
CliSoc.close();
}
}
OUTPUT
Server
$ javac udpchatserver.java
$ java udpchatserver
Server Ready

18
From Client <<< are u the SERVER
Msg to Cleint : yes
From Client <<< what do u have to serve
Msg to Cleint : no eatables
Client Quits
Client
$ javac udpchatclient.java$ java udpchatclient
Press Enter without text to quit
Enter text for server : are u the SERVER
From Server <<< yes
Enter text for server : what do u have to serve
From Server <<< no eatables
Enter text for server : Ok

RESULT
Thus both the client and server exchange data using UDP sockets.

4. USER DATAGRAM PROTOCOL USING NS-2

AIM: To implement User Datagram Protocol (UDP) using NS-2

ALGORITHM:

Step 1: Start network simulator OTCL editor.


Step 2: Create new simulator using set ns [new Simulator] syntax
Step 3: Create procedure to trace all path
proc finish {} {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam udp.nam &
exit 0 }
Step 4: Connect with TCP and SINK command.
$ns connect $tcp $sink
Step 5: Run and Execute the program.

19
$ns run
PROGRAM:
set ns [new Simulator]
set nf [open udp.nam w]
$ns namtrace-all $nf
set tf [open out.tr w]
$ns trace-all $tf
proc finish {} {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam udp.nam &
exit 0
}
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
$ns duplex-link $n0 $n4 1Mb 50ms DropTail
$ns duplex-link $n1 $n4 1Mb 50ms DropTail
$ns duplex-link $n2 $n5 0.1Mb 1ms DropTail
$ns duplex-link $n3 $n5 1Mb 1ms DropTail
$ns duplex-link $n4 $n5 1Mb 50ms DropTail
$ns duplex-link-op $n2 $n5 queuePos 1
set tcp [new Agent/UDP]
$ns attach-agent $n0 $tcp
set sink [new Agent/Null]

$ns attach-agent $n2 $sink


$ns connect $tcp $sink
set ftp [new Application/Traffic/CBR]
$ftp attach-agent $tcp
$ns at 0.0 "$ftp start"
$ns at 2.5 "$ftp stop"
$ns at 3 "finish"
$ns run

20
OUTPUT:
RESULT:
Thus the program for implementing UDP was executed using NS-2 and output
verified using Network Animator.

5. TRANSMISSION CONTROL PROTOCOL USING NS-2

AIM: To implement Transmission Control Protocol (TCP) using NS-2.

ALGORITHM:

Step 1: Start network simulator OTCL editor.


Step 2: Create new simulator using set ns [new Simulator] syntax
Step 3: Create procedure to trace all path
proc finish {} {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam tcp.nam &
exit 0}
Step 4: Connect with TCP and SINK command.
$ns connect $tcp $sink
Step 5: Run and Execute the program.
$ns run
PROGRAM:
set ns [new Simulator]
set nf [open tcp.nam w]
$ns namtrace-all $nf
set tf [open out.tr w]
$ns trace-all $tf
proc finish {} {
global ns nf tf
$ns flush-trace
close $nf

close $tf

21
exec nam tcp.nam &
exit 0
}
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
$ns duplex-link $n0 $n4 1Mb 50ms DropTail
$ns duplex-link $n1 $n4 1Mb 50ms DropTail
$ns duplex-link $n2 $n5 1Mb 1ms DropTail
$ns duplex-link $n3 $n5 1Mb 1ms DropTail
$ns duplex-link $n4 $n5 1Mb 50ms DropTail
$ns duplex-link-op $n4 $n5 queuePos 0.5
set tcp [new Agent/TCP]
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n2 $sink
$ns connect $tcp $sink
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ns at 0.0 "$ftp start"
$ns at 2.5 "$ftp stop"
$ns at 3 "finish"
$ns run

OUTPUT:
RESULT:
Thus the program for implementing TCP was executed using NS-2 and output
verified using Network Animator.

22
23

You might also like