You are on page 1of 62

DISTRIBUTED

SYSTEMS

INDEX
Sr. No. Title Date Sign

Implementing Client-Server Communication Model


A. Chat using TCP
B. Chat using UDP
1 13/11/2017
C. Identifying Prime Number using TCP
D. Identifying Even/Odd using UDP
E. Multicast

2 Implementation of RMI 14/11/2017


3 Implementation of RPC 14/11/2017

Implementation of Web Services A.


4 Without Using a database 29/11/2017
B. Using a database

Implementation of an Mutual Exclusion Algorithm –


5 11/12/2017
Ring Based Algorithm

Implementation of an Election Algorithm – Bully


6 Algorithm 21/11/2017

7 Implementation of Two-Phase Commit Protocol 23/11/2017

Implementation of an Clock Synchronization Algorithm


8 02/01/2018

9 Concept of Sharing Resources – Samba Server 04/01/2018

Implement The Concept of Distributed File System


10 Architecture – NFS Configuration 04/01/2018

PRACTICAL 1
IMPLEMENTING CLIENT-SERVER COMMUNICATION
MODEL

A. Chat Functionality Using TCP

TCP (Transmission Control Protocol) is a standard that defines how to establish and maintain
a network conversation via which application programs can exchange data. It defines the
basic rules defining the internet. TCP is a connection-oriented protocol, which means a
connection is established and maintained until the application programs at each end have
finished exchanging messages. It determines how to break application data into packets that
networks can deliver, sends packets to and accepts packets from the network layer, manages
flow control, and - because it is meant to provide error-free data transmission - handles
retransmission of dropped or garbled packets as well as acknowledgement of all packets that
arrive. In the Open Systems Interconnection (OSI) communication model, TCP covers parts
of Layer 4, the Transport Layer, and parts of Layer 5, the Session Layer.
Working of the programs:
• First compile and run the server file followed by the client.
• The prompt on the server shows whether it is ready and also if the client is connected
or not.
• On the client prompt the user can type the message he/she wants and press enter to
send the message.
• The server receives the message and can now reply to the client.
• This goes on until client wants to exit, which is done by him/her by typing ‘EXIT’ and
hitting the enter key.

Program for Server Side:

import java.io.*; import


java.net.*; public class
tcpserverchat
{
public static void main(String[] args) throws Exception
{
ServerSocket sersock = new ServerSocket(3000);
System.out.println("Server ready");
Socket sock = sersock.accept( );
System.out.println("Client connected");
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
DataOutputStream out = new DataOutputStream(sock.getOutputStream());
DataInputStream in = new DataInputStream(sock.getInputStream());
String rec,send;
while((rec = in.readLine()) != null)
{
if(rec.equalsIgnoreCase("exit"))
break;
System.out.println("Client says :"+ rec);
System.out.println("Server says:"); send=br.readLine();
out.writeBytes(send + "\n");
}
br.close();
in.close(); out.close();
sock.close();
}
}

Program for Client Side:

import java.io.*; import


java.net.*; public class
tcpclientchat
{
public static void main(String[] args) throws Exception
{
Socket sock = new Socket("127.0.0.1", 3000);
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
DataOutputStream out = new DataOutputStream(sock.getOutputStream());
DataInputStream in = new DataInputStream(sock.getInputStream());
String msg;
System.out.println("To stop type EXIT");
while((msg = br.readLine()) != null)
{
out.writeBytes(msg + "\n");
if(msg.equalsIgnoreCase("exit"))
break;
System.out.println("Server says :"+ in.readLine());
System.out.println("Client says:");
}
br.close();
in.close(); out.close();
sock.close();
}
}

Output: Server Prompt


Output: Client Prompt

B. Chat Functionality Using UDP


UDP (User Datagram Protocol) is an alternative communications protocol to Transmission Control
Protocol (TCP) used primarily for establishing low-latency and loss tolerating connections between
applications on the Internet. Both UDP and TCP run on top of the Internet Protocol (IP) and are
sometimes referred to as UDP/IP or TCP/IP. Both protocols send short packets of data, called
datagrams. UDP provides two services not provided by the IP layer. It provides port numbers to help
distinguish different user requests and, optionally, a checksum capability to verify that the data arrived
intact.
Working of the programs:
• First compile and run the server file followed by the client.
• The prompt on the server shows whether it is ready and also if the client is connected
or not.
• On the client prompt the user can type the message he/she wants and press enter to
send the message.
• The server receives the message and can now reply to the client.
• This goes on until client wants to exit, which is done by him/her by typing ‘EXIT’ and
hitting the enter key.

Program for Server Side:

import java.io.*; import


java.net.*; public class
udpserverchat
{
public static void main(String[] a) throws IOException
{
byte buf[] = new byte[1024];
DatagramSocket serversocket = new DatagramSocket(790);
DatagramPacket dp = new DatagramPacket(buf,buf.length);
BufferedReader dis = new BufferedReader(new
InputStreamReader(System.in));
InetAddress ia = InetAddress.getLocalHost();
System.out.println("TO STOP CHATTING TYPE EXIT");
while(true)
{
serversocket.receive(dp);
String inMsg = new String(dp.getData(),0,dp.getLength());
if(inMsg.equalsIgnoreCase("exit"))
{
System.out.println("CLIENT HAS BEEN
DISCONNECTED");
break;
}
System.out.println("Client: "+inMsg);
System.out.print("Me:");
String outMsg = new String(dis.readLine());
buf = outMsg.getBytes();
serversocket.send(new DatagramPacket(buf,outMsg.length(),ia,789));
}
}
}

Program for Client Side:

import java.io.*; import


java.net.*; public class
udpclientchat
{
public static void main(String[] a) throws IOException
{
byte buf[] = new byte[1024];
DatagramSocket clientsocket = new DatagramSocket(789);
DatagramPacket dp = new DatagramPacket(buf, buf.length);
BufferedReader dis = new BufferedReader(new
InputStreamReader(System.in));
InetAddress ia = InetAddress.getLocalHost();
System.out.println("SERVER IS READY TO CHAT. TO STOP CHATTING
TYPE EXIT");
while(true)
{
System.out.print("Me:");
String outMsg = new String(dis.readLine());
buf = outMsg.getBytes();
if(outMsg.equalsIgnoreCase("exit"))
{
System.out.println("YOU HAVE BEEN DISCONNECTED
FROM THE SERVER");
clientsocket.send(new DatagramPacket(buf,outMsg.length(),
ia,790));
break;
}
clientsocket.send(new DatagramPacket(buf,outMsg.length(), ia,790));
clientsocket.receive(dp);
String inMsg = new String(dp.getData(), 0,dp.getLength());
System.out.println("Server: " + inMsg);
}
}
}
Output: Server Prompt

Output: Client Prompt


C. Identifying Prime Number Using TCP

TCP (Transmission Control Protocol) is a standard that defines how to establish and maintain
a network conversation via which application programs can exchange data. It defines the
basic rules defining the internet. TCP is a connection-oriented protocol, which means a
connection is established and maintained until the application programs at each end have
finished exchanging messages. It determines how to break application data into packets that
networks can deliver, sends packets to and accepts packets from the network layer, manages
flow control, and - because it is meant to provide error-free data transmission - handles
retransmission of dropped or garbled packets as well as acknowledgement of all packets that
arrive. In the Open Systems Interconnection (OSI) communication model, TCP covers parts
of Layer 4, the Transport Layer, and parts of Layer 5, the Session Layer.
Working of the programs:
• First compile and run the server file followed by the client.
• The prompt on server shows whether the server is ready or not.
• On the client prompt, enter the number which you want to identify, as if it is a prime
number or not.
• Server processes the number and returns the output to the client, which is displayed on
the client prompt.

Program for Server Side:

import java.io.*; import


java.net.*;
public class tcpserverprimenumber
{ public static void main(String[] args) throws Exception
{
ServerSocket sersock = new ServerSocket(3000);
System.out.println("Server ready");
Socket sock = sersock.accept( );
DataInputStream istream = new DataInputStream(sock.getInputStream()); int
x= istream.readInt();
DataOutputStream ostream = new
DataOutputStream(sock.getOutputStream());
for(int i=2;i<=x;i++)
{ if(x%i==0)
{ if(i==x) ostream.writeUTF(x + " is prime");
else ostream.writeUTF(x + " is not prime");
break;
}
}
}
}

Program for Client Side:

import java.io.*; import


java.net.*;
public class tcpclientprimenumber
{ public static void main(String[] args) throws Exception
{
Socket sock = new Socket("127.0.0.1", 3000);
BufferedReader keyRead = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter a number"); int n=
Integer.parseInt(keyRead.readLine());
DataOutputStream ostream = new
DataOutputStream(sock.getOutputStream())
;
ostream.writeInt(n);
DataInputStream istream = new
DataInputStream(sock.getInputStream());
System.out.println(istream.readUTF()); }
}

Output: Server Prompt


Output: Client Prompt
D. Identifying Even/Odd using UDP

UDP (User Datagram Protocol) is an alternative communications protocol to Transmission Control


Protocol (TCP) used primarily for establishing low-latency and loss tolerating connections between
applications on the Internet. Both UDP and TCP run on top of the Internet Protocol (IP) and are
sometimes referred to as UDP/IP or TCP/IP. Both protocols send short packets of data, called
datagrams. UDP provides two services not provided by the IP layer. It provides port numbers to help
distinguish different user requests and optionally, a checksum capability to verify that the data arrived
intact.
Working of the programs:
• First compile and run the server file followed by the client.
• The prompt on server shows whether the server is ready or not.
• On the client prompt, enter the number which you want to identify, as if it is even
number or not (odd).
• Server processes the number and returns the output to the client, which is displayed on
the client prompt.

Program for Server Side:

import java.io.*; import


java.net.*;
public class udpserveroddeven
{ public static void main(String[] a) throws Exception
{
DatagramSocket ds = new DatagramSocket(2000);
byte buf[] = new byte[1024];
System.out.println("Server is ready");
DatagramPacket dp = new DatagramPacket(buf, buf.length);
ds.receive(dp);
String str = new String(dp.getData(), 0,dp.getLength());
System.out.println(str);
int
n=Integer.parseInt(str);
String s=new String();
if(n%2==0) s="Num is
even";
else s="Num is not even";
byte buf1[] = new byte[1024];
buf1=s.getBytes();
DatagramPacket dp1 = new DatagramPacket(buf1,
buf1.length,InetAddress.getLocalHost(),1000);
ds.send(dp1);
}
}

Program for Client Side:

import java.io.*; import


java.net.*;
public class udpclientoddeven
{ public static void main(String[] a) throws Exception
{
DatagramSocket ds = new DatagramSocket(1000);
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter a num");
String n=br.readLine(); byte
buf[] = new byte[1024];
buf=n.getBytes();
DatagramPacket dp = new DatagramPacket(buf,
buf.length,InetAddress.getLocalHost(),2000);
ds.send(dp);
byte buf1[] = new byte[1024];
DatagramPacket dp1 = new DatagramPacket(buf1, buf1.length);
ds.receive(dp1);
String str = new String(dp1.getData(), 0,dp1.getLength());
System.out.println(str);
}
}

Output: Server Prompt


Output: Client Prompt
E. Multicast

Multicast is communication between a single sender and multiple receivers on a network.


Typical uses include the updating of mobile personnel from a home office and the periodic
issuance of online newsletters. Together with anycast and unicast, multicast is one of the
packet types in the Internet Protocol Version 6 (IPv6). Also it is one of the issues of
distributed systems. Multicast has an entire class (Class D) for its use to broadcast certain
message. A multicast address specifies a limited form of broadcast that is received by a group
of stations whose network interfaces have been configured to receive packets with that
multicast address.
Not all implementations of Ethernet network interfaces can recognize multicast addresses.
Working of the programs:
• First compile and run the server file followed by the client1 and client2.
• The prompt on server ask for the message to be entered, whereas the clients wait to
receive the message sent by the server.
• When the server sends (broadcasts/multicasts) the message, both the clients receive
the messages in their prompts.

Program for Server Side:

import java.io.*; import


java.net.*;
public class multisocketserver
{ public static void main(String args[]) throws Exception {
System.out.println("Server says");
while(true)
{
InetAddress addr = InetAddress.getByName("224.0.0.3");
DatagramSocket server_socket = new DatagramSocket();
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter a message:");
String outMsg = br.readLine();
DatagramPacket msgPacket = new
DatagramPacket(outMsg.getBytes(),outMsg.getBytes().length,addr,8888);
server_socket.send(msgPacket);
if (outMsg.equals("EXIT"))
{
br.close();
server_socket.close();
System.out.print("Process closed.");
break;
}
outMsg=" ";
}
}
}

Program for Client 1 Side:

import java.io.*; import


java.net.*;
public class multisocketclient
{
public static void main(String args[]) throws Exception
{
System.out.println("Server says");
byte[] buf = new byte[500];
InetAddress addr = InetAddress.getByName("224.0.0.3"); MulticastSocket
clientSocket = new MulticastSocket(8888);
clientSocket.joinGroup(addr);
while(true)
{
DatagramPacket msgPacket = new DatagramPacket(buf,buf.length);
clientSocket.receive(msgPacket);
String inMsg = new String(buf,0,buf.length);
if (inMsg.equals("EXIT"))
{
clientSocket.leaveGroup(addr);
clientSocket.close();
break;
}
System.out.println("Socket 1 received a message:"+inMsg);
inMsg=" ";
}
}
}

Program for Client 2 Side:

import java.io.*; import


java.net.*;
public class multisocketclient1
{ public static void main(String args[]) throws Exception
{
System.out.println("Server Says");
byte[] buf = new byte[500];
InetAddress addr = InetAddress.getByName("224.0.0.3"); MulticastSocket
clientSocket = new MulticastSocket(8888);
clientSocket.joinGroup(addr);
while(true)
{
DatagramPacket msgPacket = new DatagramPacket(buf,buf.length);
clientSocket.receive(msgPacket);
String inMsg = new String(buf,0,buf.length);
if (inMsg.equals("EXIT"))
{
clientSocket.leaveGroup(addr);
break;
}
System.out.println("Socket 2 received a message:"+inMsg);
}
}
}

Output: Server Side


Output: Client1 Side

Output: Client2 Side


PRACTICAL 2
IMPLEMENTATION OF RMI
Remote method invocation (RMI) is closely related to RPC but extended into the world of
distributed objects. In RMI, a calling object can invoke a method in a potentially remote
object. RMI allows the programmer to pass parameters not only by value, as input or output
parameters, but also by object reference. Passing references is particularly attractive if the
underlying parameter is large or complex. The remote end, on receiving an object reference,
can then access this object using remote method invocation, instead of having to transmit the
object value across the network.
Figure for remote and local method invocations:

Working of the programs:


• First compile the client, interface and server programs.
• Now in the server prompt create the stub and skeleton class files for the server
program and start the rmi registry.
• Now execute the server program followed by the client.
• On the client prompt enter the two numbers, after which we get the appropriate
answers after processing the two numbers.

Program for Server Side:

import java.rmi.*; import java.rmi.server.*; public class Cal_Server extends


UnicastRemoteObject implements Cal_Main
{ public Cal_Server() throws RemoteException
{
System.out.println("Server Is Instantiated");
}
public int sum(int first,int Second) throws RemoteException
{ return first+Second;
}
public int sub(int first,int Second) throws RemoteException
{ return first-Second;
}
public int mul(int first,int Second) throws RemoteException {
return first*Second;
}
public static void main(String args[])
{ try
{
Cal_Server p = new Cal_Server();
Naming.rebind("Cal_Main",p);
}
catch(Exception e)
{
System.out.println("Exception occured : "+e.getMessage());
}
}
}

Program for Interface:

import java.rmi.*;
public interface Cal_Main extends Remote
{ public int sum(int a,int b) throws RemoteException;
public int sub(int a,int b) throws RemoteException; public
int mul(int a,int b) throws RemoteException; }

Program for Client:

import java.rmi.*;
import java.io.*; public
class Cal_Client
{ public static void main(String arg[])
{ try
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
Cal_Main p = (Cal_Main)Naming.lookup("Cal_Main");
System.out.println("Enter First Number");
String strFirst = br.readLine();
System.out.println("Enter Second Number");
String strSecond = br.readLine();
System.out.println("Sum:"+p.sum(Integer.parseInt(strFirst),Integer.par
seInt(strSecond)));
System.out.println("Sub:"+p.sub(Integer.parseInt(strFirst),Integer.pars
eInt(strSecond)));
System.out.println("Mul:"+p.mul(Integer.parseInt(strFirst),Integer.pars
eInt(strSecond)));
}
catch(Exception e)
{
System.out.println("Error Occured : "+e.getMessage());
}
}
}
Output: Server Prompt

Output: Client Prompt

PRACTICAL 3
IMPLEMENTATION OF RPC
Remote Procedure Call (RPC) is a protocol that one program can use to request a service
from a program located in another computer on a network without having to understand the
network's details. A procedure call is also sometimes known as a function call or a subroutine
call. RPC uses the client-server model. The requesting program is a client and the service
providing program is the server. Like a regular or local procedure call, an RPC is a
synchronous operation requiring the requesting program to be suspended until the results of
the remote procedure are returned. However, the use of lightweight processes or threads that
share the same address space allows multiple RPCs to be performed concurrently.
Working of the programs:
• Compile the client and server programs.
• First run the server program followed by the client.
• On the client prompt enter the number for the count of numbers Fibonacci Series will
be made. On the server prompt the Fibonacci Series of the required count is displayed.

Program for Server Side:

import java.io.*; import


java.net.*; public class
RPC_S
{
public static void main(String args[]) throws Exception
{
byte buff[] = new byte[2000];
DatagramSocket serverSocket = new DatagramSocket(790);
DatagramPacket inPacket = new DatagramPacket(buff,buff.length);
InetAddress ia = InetAddress.getLocalHost();
while(true) {
serverSocket.receive(inPacket);
String inMessage = new
String(inPacket.getData(),0,inPacket.getLength());
System.out.println("Number received from client: "+inMessage);
int no = Integer.parseInt(inMessage);
int n1, n2=0, n3=1;
System.out.print("Fibonacci Series of "+no+":\n");
for(int i=1;i<=no;i++)
{
System.out.print(n3+"\n");
n1 = n2;
n2 = n3;
n3 = n1 + n2;
}
}
}
}
Program for Client Side:
import java.io.*; import
java.net.*; public class
RPC_C
{
public static void main(String args[]) throws Exception
{
byte buf[] = new byte[1024];
DatagramSocket clientsocket = new DatagramSocket(789);
BufferedReader dis = new BufferedReader(new
InputStreamReader(System.in));
InetAddress ia = InetAddress.getLocalHost();
while(true)
{
System.out.print("Enter the number:");
String outMsg = new String(dis.readLine());
buf = outMsg.getBytes();
clientsocket.send(new DatagramPacket(buf,outMsg.length(), ia,790));
}
}
}
Output: Server Prompt

Output: Client Prompt


PRACTICAL 4
IMPLEMENTATION OF WEB SERVICES
A. Without Using Database

• Create a Web Service:

I. Choosing a Container:

Choose File ->New Project ->Java Web -> Web Application -> Project Name:
CalculatorWSApplication->Next->Finish

II. Creating a Web Service from Java Class:

Right-click CalculatorWSApplication node -> New -> Web Service -> Name: CalculatorWS
> Package: org.me.calculator -> Select Implement Web Service as a Stateless Session Bean -
> Finish

• Adding Operation to Web Service:

I. Adding an operation to Web Service:

Click on Design View -> Click Add Operation -> Name: add -> Return Type: int -> Click
Add -> Create parameter of type int named I -> Again click Add -> Create parameter of type
int named j -> Click OK -> Click Source and code the following:
public int add(@WebParam(name = “i”) int i, @WebParam(name = “j”)int j)
{
int k = i+j;
return k;
}

• Deploying and Testing the Web Service

I. Testing Successful Deployment:

Right-click the Project -> Deploy -> Expand Web Services node of CalculatorWSApplication
project -> Right-click CalculatorWS node -> Test Web Service -> Tester Page is opened in
browser -> Type any two numbers below:
Output:

• Consuming the Web Service


I. Client: Java Class in Java SE Application

File -> New Project -> Java -> Java Application -> Name: CalculatorWS_Client_Application
-> Finish->Right-click CalculatorWS_Client_Application node -> New -> Web Service
Client -> In Project, Browse to CalculatorWS web service in the CalculatorWSApplication ->
OK -> Finish -> Go to Source -> Drag the add node from the Web Services References node
below the main method -> Code the following in main() method:
public static voide main(String[] args)
{
try {
int i = 13; int j
= 29; int result =
add(i,j);
System.out.println(“Result = ” +result);
}
catch(Exception e) {
System.out.println(“Exception = ” +e); }
}

Right-click project -> Run

Output:
B. Using MySQL database

• Creating MySQL Table

Create database bookshop;


Use bookshop;
Create table books (isbn varchar(20), bookname varchar(20), bookprice varchar(20));
Insert into books values (“123-456-042”,”Hitchhiker’s Guide”,”422”);
Insert into books values ("123-022-423","Catch-22","300");

• Creating a web service

I. Choosing Container:

File -> New Project -> Java Web -> Web Application -> Next -> Name: BookWS -> Select
Use Dedicated Folder for Storing Libraries -> Name: BookWS -> Package: webservice ->
Select option Implement Web Service as a Stateless Session Bean -> Finish

• Adding an operation to web service:

Click Design View -> Click Add Operation -> Name: getBookDetails -> Return Type:
java.lang.String -> Click Add -> Create a parameter of type String named isbn -> OK ->
Click Source -> Modify the code spec:
@WebMethod(operationName = "getBookDetails") public String
getBookDetails(@WebParam(name = "isbn") String isbn) { //TODO
write your implementation code here:
Connection dbcon = null;
Statement stmt = null;
ResultSet rs = null;
String query = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
dbcon =
DriverManager.getConnection("jdbc:mysql://localhost/bookshop","root","123456");
stmt = dbcon.createStatement();
query = "select * from books where isbn = '" +isbn+ "'";
rs = stmt.executeQuery(query); rs.next();
String bookDetails = "<h1>The name of the book is <b>" +rs.getString("bookname")
+ "</b> and its cost is <b>" +rs.getString("bookprice") + "</b></h1>.";
return bookDetails;
}
catch(Exception e) {
System.out.println("Sorry failed to connect to the database... " +e.getMessage());
}
return null;
}
• Adding MySQL Connector
Right-click Libraries -> Select Add JAR/Folder -> Select the connector and open it

• Deploying and testing the Web Service

Right-click BookWS Project -> Deploy -> Expand the Web Services Directory -> Right-click
BookWS Web Service -> Test We Service -> In the browser, enter the ISBN number -> Click
getBookDetails -> We get the following:

• Consuming the Web Service

File -> New Project -> Java Web -> Web Application -> Next -> Name:
BookWSServletClient -> Select option Use Dedicated folder for Storing Libraries -> Next ->
Finish

• Adding Web Service to Client Application

Right-click BookWSServletClient Project -> New -> Web Service Client -> Click Browse ->
Browse throught the Web Service which needs to be consumed -> Click ok -> Finish

• Creating a servlet
New -> Servlet -> Name: retreiveBookDetails -> Package:servlet -> Next -> Configure
Servlet Deployment to be kept defaults -> Finish -> Replace the following code spec:
out.println(“<h1>Servlet retreiveBookDetails at” +request.getContextPath()+ “</h1>”); With
the code spec of getBookDetails() operation of the web service by dragging and dropping the
getBookDetails operation. -> Now change the following code spec: Add this code –
outprintln(getBookDetails(request.getParameter(“isbn”))); to processRequest() method
between out.println(“<body”); and out.println(“</body>”)

• Creating an HTML form

Make the changes in the index.html code:


<!DOCTYPE HTML PUBLIC" -//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html14/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html''charset=UTF-8">
<title>SOAP Client - Get Book Details</title>
</head>
<body bgcolor="white">
<form name="frmgetBookDetails" method="post" action="retreiveBookDetails"> <h1>
ISBN : <input type="text" name="isbn"/><br><br>
</h1>
<input type="submit" value="Submit"/>
</form>
</body>
</html>

Build and Run the Application

Output:
PRACTICAL 5
IMPLEMENTATION OF A MUTUAL EXCLUSION ALGORITHM
– RING BASED ALGORITHM
One of the simplest ways to arrange mutual exclusion between the N processes without
requiring an additional process is to arrange them in a logical ring. This requires only that
each process pi has a communication channel to the next process in the ring, p(i + 1)mod N.
The idea is that exclusion is conferred by obtaining a token in the form of a message passed
from process to process in a single direction – clockwise, say – around the ring. The ring
topology may be unrelated to the physical interconnections between the underlying
computers. If a process does not require to enter the critical section when it receives the
token, then it immediately forwards the token to its neighbour. A process that requires the
token waits until it receives it, but retains it. To exit the critical section, the process sends the
token on to its neighbour.
Working of the programs:
• First compile all programs.
• Run the server first followed by the clients.
• Client 1 gets a prompt on whether he wants to use the token to send any data or not. If
yes then he can type and send the data, else no the client 2 gets a prompt for the same.
In this similar fashion, the ring based mutual exclusion algorithm works using a token.

Program for Server Side:

import java.io.*; import


java.net.*;
public class Ring_Algo_Server implements Runnable
{
Socket socket = null; static
ServerSocket server_s;
Ring_Algo_Server(Socket newSocket)
{
this.socket = newSocket;
}
public static void main(String args[]) throws Exception
{
server_s = new ServerSocket(7000);
System.out.println("SERVER STARTED");
while(true)
{
Socket s = server_s.accept();
Ring_Algo_Server server = new
Ring_Algo_Server(s); Thread t = new Thread(server);
t.start();
}
}
public void run()
{
try
{
BufferedReader br =new BufferedReader(new
InputStreamReader(socket.getInputStream()));
while(true)
{
System.out.println(br.readLine());
}
}
catch(Exception e)
{
System.out.print(e.getMessage());
}
}
}

Program for Client1 Side:

import java.io.*; import


java.net.*;
public class Ring_Algo_Client_1
{
public static void main(String args[]) throws Exception
{
Socket client_socket = new Socket("localhost",7000);
ServerSocket server_s = new ServerSocket(7001);
Socket s = server_s.accept();
PrintStream out_msg = new PrintStream(client_socket.getOutputStream());
PrintStream out_msg1 = new PrintStream(s.getOutputStream());
BufferedReader br =new BufferedReader(new
InputStreamReader(s.getInputStream()));
BufferedReader br1 =new BufferedReader(new
InputStreamReader(System.in));
String msg = "TOKEN";
while(true)
{
if(msg.equalsIgnoreCase("TOKEN"))
{
System.out.print("\nDO YOU WANT TO SEND SOME
DATA?(YES/NO):");
msg = br1.readLine();
if(msg.equalsIgnoreCase("YES"))
{
System.out.print("ENTER THE DATA:");
msg = br1.readLine();
out_msg.println(msg);
}
out_msg1.println("TOKEN");
}
System.out.print("WAITING FOR THE TOKEN");
msg = br.readLine();
}
}
}

Program for Client2 Side:

import java.io.*; import


java.net.*;
public class Ring_Algo_Client_2
{
public static void main(String args[]) throws Exception
{
Socket client_socket = new Socket("localhost",7000);
Socket server_s = new Socket("localhost",7001);
BufferedReader br =new BufferedReader(new
InputStreamReader(server_s.getInputStream()));
BufferedReader br1 = new BufferedReader(new
InputStreamReader(System.in));
PrintStream out_msg = new PrintStream(client_socket.getOutputStream());
PrintStream out_msg1 = new PrintStream(server_s.getOutputStream());
String msg;
while(true)
{
System.out.print("WAITING FOR THE TOKEN");
msg = br.readLine();
if(msg.equalsIgnoreCase("TOKEN"))
{
System.out.print("\nDO YOU WANT TO SEND SOME
DATA?(YES/NO):");
msg = br1.readLine();
if(msg.equalsIgnoreCase("YES"))
{
System.out.print("ENTER THE DATA:");
msg = br1.readLine();
out_msg.println(msg);
}
out_msg1.println("TOKEN");
}
}
}
}
Output: Server Prompt

Output: Client1 Prompt


Output: Client2 Prompt

PRACTICAL 6
IMPLEMENTATION OF AN ELECTION ALGORITHM – BULLY
ALGORITHM
The bully algorithm [Garcia-Molina 1982] allows processes to crash during an election,
although it assumes that message delivery between processes is reliable. Unlike the ring-
based algorithm, this algorithm assumes that the system is synchronous: it uses timeouts to
detect a process failure. Another difference is that the ring-based algorithm assumed that
processes have minimal a priori knowledge of one another: each knows only how to
communicate with its neighbour, and none knows the identifiers of the other processes. The
bully algorithm, on the other hand, assumes that each process knows which processes have
higher identifiers, and that it can communicate with all such processes. There are three types
of message in this algorithm: an election message is sent to announce an election; an answer
message is sent in response to an election message and a coordinator message is sent to
announce the identity of the elected process – the new ‘coordinator’. A process begins an
election when it notices, through timeouts, that the coordinator has failed. Several processes
may discover this concurrently.
Working of the program:
• After compiling and running the program, enter the number of processes.
• Give each process a Status and Priority.
• Select the initiation process.
• Final Co-coordinator with the highest priority is selected.

Program:

import java.io.*; import


java.util.*;
public class Bully_Algorithm
{
static int n;
static int process[] = new int[100]; static int status[]
= new int[100]; static int coordinator; public
static void main(String args[]) throws Exception
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("\nBully Algo\n");
System.out.print("\nENTER THE NUMBER OF PROECESSES:");
n = Integer.parseInt(br.readLine());
for(int i=0;i<n;i++)
{
System.out.println("\nFOR PROCESS ID "+(i+1)+":");
System.out.print("STATUS:");
status[i] = Integer.parseInt(br.readLine());
System.out.print("PRIORITY:");
process[i] = Integer.parseInt(br.readLine()); //accepting and storing the input in priority
array
}
System.out.println("\nWHICH PROCESS WILL INITIATE THE
ELECTION?");
System.out.print("PROCESS ID:");
int election = Integer.parseInt(br.readLine());
algorithm(election); //calling the static method
System.out.println("\nFINAL COORDINATOR IS:"+coordinator);
}
public static void algorithm(int election1)
{
election1 = election1 - 1;
coordinator = election1 + 1;
for(int i=0;i<n;i++)
{
if(process[election1]<process[i])
{
System.out.println("\nELECTION MESSAGE IS SENT
FROM "+(election1+1)+" to "+(i+1));
if(status[i] == 1)
algorithm(i+1);
}
}
}
}

Output:
PRACTICAL 7
IMPLEMENTATION OF TWO PHASE COMMIT PROTOCOL
In the first phase of the two-phase commit protocol the coordinator asks all the participants if
they are prepared to commit; in the second, it tells them to commit (or abort) the transaction.
If a participant can commit its part of a transaction, it will agree as soon as it has recorded the
changes it has made (to the objects) and its status in permanent storage and is therefore
prepared to commit. It consists of a voting and a completion phase.

Working of Programs:
• Compile and run the server first followed by the client.
• Run 2/3 Clients and after server is ready Commit or Abort the clients on the
individual prompts.
• Each client is informed of a new addition and the server keeps the count of clients.

Program for Server Side:

import java.io.*; import


java.net.*; import
java.util.*; public class
Server
{ boolean closed=false,inputFromAll=false;
List<clientThread> t;
List<String> data;
Server()
{ t = new ArrayList<clientThread>();
data= new ArrayList<String>();
}
public static void main(String args[])
{
Socket clientSocket = null;
ServerSocket serverSocket =
null; int port_number=1111;
Server ser=new Server();
try
{ serverSocket = new ServerSocket(port_number);
}
catch (IOException e)
{
System.out.println(e);
}
while(!ser.closed)
{

try
{ clientSocket = serverSocket.accept();
clientThread th=new clientThread(ser,clientSocket);
(ser.t).add(th);
System.out.println("\nNow Total clients are : "+(ser.t).size());
(ser.data).add("NOT_SENT");
th.start();
}
catch (IOException e)
{
}
} try
{ serverSocket.close();
}
catch(Exception e1)
{
}
}
}
class clientThread extends Thread {
DataInputStream is = null;
String line;
String destClient="";
String name;
PrintStream os = null;
Socket clientSocket = null;
String clientIdentity;
Server ser;
public clientThread(Server ser,Socket clientSocket)
{ this.clientSocket=clientSocket;
this.ser=ser;
}
public void run()
{
try
{
is = new
DataInputStream(clientSocket.getInputStream()); os =
new PrintStream(clientSocket.getOutputStream());
os.println("Enter your name."); name = is.readLine();
clientIdentity=name;
os.println("Welcome "+name+" to this 2 Phase Application.\nYou will receive
a vote Request now...");
os.println("VOTE_REQUEST\nPlease enter COMMIT or ABORT to proceed
: ");
for(int i=0; i<(ser.t).size(); i++)
{
if((ser.t).get(i)!=this)
{
((ser.t).get(i)).os.println("---A new user "+name+" entered the Appilcation---
");
} } while
(true) {
line = is.readLine();
if(line.equalsIgnoreCase("ABORT"))
{
System.out.println("\nFrom '"+clientIdentity+"' : ABORT\n\nSince aborted we
will not wait for inputs from other clients.");
System.out.println("\nAborted...."); for(int i=0; i<(ser.t).size(); i++)
{
((ser.t).get(i)).os.println("GLOBAL_ABORT");
((ser.t).get(i)).os.close();
((ser.t).get(i)).is.close();
}
break;
}
if(line.equalsIgnoreCase("COMMIT"))
{
System.out.println("\nFrom '"+clientIdentity+"' : COMMIT");
if((ser.t).contains(this))
{
(ser.data).set((ser.t).indexOf(this), "COMMIT");
for(int j=0;j<(ser.data).size();j++)
{
if(!(((ser.data).get(j)).equalsIgnoreCase("NOT_SENT")))
{
ser.inputFromAll=true
; continue; } else {
ser.inputFromAll=fals
e;
System.out.println("\nWaiting for inputs from other clients.");
break;
}}
if(ser.inputFromAll)
{
System.out.println("\n\nCommited...."); for(int
i=0; i<(ser.t).size(); i++)
{
((ser.t).get(i)).os.println("GLOBAL_COMMIT");
((ser.t).get(i)).os.close();
((ser.t).get(i)).is.close();
}
break;
}
}//if t.contains
}//commit }//while
ser.closed=true;
clientSocket.close()
;
}
catch(IOException e)
{
};
}
}

Program for Client Side:

import java.io.*; import java.net.*;


public class Client implements Runnable
{ static Socket clientSocket = null; static
PrintStream os = null; static
DataInputStream is = null; static
BufferedReader inputLine = null; static
boolean closed = false; public static
void main(String[] args)
{
int port_number=1111; String
host="localhost";
try
{ clientSocket = new Socket(host, port_number);
inputLine = new BufferedReader(new
InputStreamReader(System.in)); os = new
PrintStream(clientSocket.getOutputStream()); is = new
DataInputStream(clientSocket.getInputStream()); }
catch (Exception e)
{
System.out.println("Exception occurred : "+e.getMessage());
}
if (clientSocket != null && os != null && is != null)
{ try
{ new Thread(new Client()).start();
while (!closed)
{
os.println(inputLine.readLine());
} os.close();
is.close();
clientSocket.close()
;
}
catch (IOException e)
{
System.err.println("IOException: " + e);
}
}}
public void run()
{
String responseLine;
try
{ while ((responseLine = is.readLine()) != null)
{
System.out.println("\n"+responseLine); if
(responseLine.equalsIgnoreCase("GLOBAL_COMMIT")==true ||
responseLine.equalsIgnoreCase("GLOBAL_ABORT")==true )
{ break; } }
closed=true
;
}
catch (IOException e)
{
System.err.println("IOException: " + e);
}
}
}

Output: Server Prompt


Output: Client1 Prompt
Output: Client2 Prompt

Output: Client3 Prompt


PRACTICAL 8
IMPLEMENTATION OF A CLOCK SYNCHRONIZATION
ALGORITHM
Computers each contain their own physical clocks. These clocks are electronic devices that
count oscillations occurring in a crystal at a definite frequency, and typically divide this count
and store the result in a counter register. Computer clocks, like any others, tend not to be in
perfect agreement. The instantaneous difference between the readings of any two clocks is
called their skew. Also, the crystal-based clocks used in computers are, like any other clocks,
subject to clock drift, which means that they count time at different rates, and so diverge.
Computer clocks can be synchronized to external sources of highly accurate time. Working
of program:
• Compile server and client. Run server, followed by client.
• In Server CMD enter max time and skew. It will display the Global TimeStamp (G).
Then enter the data in Client CMD. Continue for different data.

Program for Server Side:

import java.net.*; import


java.sql.*; import
java.util.Scanner;
public class SCServer
{
public static void main(String args[]) throws Exception
{
InetAddress lclhost; lclhost
= InetAddress.getLocalHost(); long
maxtime, skewtime, datatime; String
maxtimestr, skewtimestr;
Scanner sc = new Scanner(System.in);
ClntServer ser = new ClntServer(lclhost);
System.out.println("Enter the maximum time"); maxtimestr =
sc.nextLine();
System.out.println("Enter the maximum skew time");
skewtimestr = sc.nextLine();
maxtime = Long.parseLong(maxtimestr);
skewtime = Long.parseLong(skewtimestr);
while (true)
{
datatime = System.currentTimeMillis();
long G = datatime - maxtime - skewtime;
System.out.println("G =" + G);
ser.setTimeStamp(new Timestamp(G));
ser.recPort(8001);
ser.recData();
}
}
}
class ClntServer
{
InetAddress lclhost;
int recport; Timestamp
obtmp;
ClntServer(InetAddress lclhost)
{
this.lclhost = lclhost;
}
void recPort(int recport)
{
this.recport = recport;
}
void setTimeStamp(Timestamp obtmp)
{
this.obtmp = obtmp;
}
void recData() throws Exception
{
DatagramSocket ds;
DatagramPacket dp; byte buf[] = new
byte[256]; ds = new
DatagramSocket(recport);
dp = new DatagramPacket(buf, buf.length);
ds.receive(dp);
ds.close();
String msgstr = new String(dp.getData(), 0, dp.getLength());
System.out.println(msgstr);
Timestamp obtmp = new Timestamp(Long.parseLong(msgstr));
if (this.obtmp.before(obtmp) == true)
{
System.out.println("The Message is accepted");
}
else
{
System.out.println("The Message is rejected");
}
}
}

Program for Client Side:


import java.net.*; import
java.util.Scanner; public
class SCClient
{
public static void main(String args[]) throws Exception
{
InetAddress lclhost; lclhost
= InetAddress.getLocalHost(); while
(true)
{
Client cntl = new Client(lclhost);
cntl.sendPort(9001);
cntl.sendData();
}
}
}
class Client
{
InetAddress lclhost;
int senport;
Client(InetAddress lclhost)
{
this.lclhost = lclhost;
}
void sendPort(int senport)
{
this.senport = senport;
}
void sendData() throws Exception
{
DatagramPacket dp;
DatagramSocket ds;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the data");
String str = sc.nextLine();
ds = new DatagramSocket(senport);
dp = new DatagramPacket(str.getBytes(), str.length(), lclhost, senport - 1000);
ds.send(dp);
ds.close();
}
}
Output: Server Prompt

Output: Client Prompt


PRACTICAL 9
CONCEPT OF SHARING RESOURCES – SAMBA SERVER
Samba is an open-source software suite that runs on Unix/Linux based platforms but is able to
communicate with Windows clients like a native application. So Samba is able to provide this
service by employing the Common Internet File System (CIFS). At the heart of this CIFS is
the Server Message Block (SMB) protocol. Samba does this by performing these 4 key
things: File & print services
• Authentication and Authorization
• Name resolution
• Service announcement (browsing)
Samba can be run on many different platforms including Linux, Unix, OpenVMS and
operating systems other than Windows and allows the user to interact with a Windows client
or server natively. It can basically be described as the Standard Windows interoperability
suite of programs for Linux and Unix.

IMPLEMENTATION:

Windows XP

Create workgroup and assign computer name. A workgroup is a collection of computers


on a local area network (LAN) that share common resources and responsibilities.

Right-click on My Computer -> Computer Name -> Click on Change


Name: WIN
Workgroup: BSCIT
Click on OK -> Click on OK -> Click on OK -> Click on No (For Restart)
IP Address of NIC

Control Panel -> Network Connections -> Right Click on LAN -> Properties -> TCP/IP
Properties
IP Address: 192.168.x.30
Subnet Mask: 255.255.255.0
Start -> Log Off -> Login again To implement above changes

RHEL6

rqmquery samba Check whether samba package


is installed

mv /etc/samba/smb.conf /etc/samba/smb.conf.bak Backup of existing configuration


file
service iptables stop Disable firewalls
vim /etc/sysconfig/network-scripts/ifcfg-eth0 NIC Configuration
DEVICE=eth0 Driver of NIC
HWADDR=__________________ MAC address
IPADDR=192.168.x.10 IP Address
NETWORK=192.168.x.0 Network
NETMASK=255.255.255.0 Subnet Mask of IP Address
BROADCAST=192.168.x.255 Broadcast IP Address
BOOTPROTO=static static IP Address
ONBOOT=yes Bring up on boot
:wq
service network restart Restart network service to
implement the new NIC
configuration

vim /etc/samba/smb.conf Configuration file of Samba


Server

Enter the following contents


[global]
workgroup=BSCIT
netbios name=LIN
:wq Save
service smb restart Restart service to implement
changes made in configuration
file

testparm If service is successfully


restarted, will display
parameters set in configuration
file

Windows XP

Start -> Run: \\192.168.x.10 Access RHEL6 on Windows XP. Will


prompt for username and password.
But since there are no samba users
created, RHEL6
cannot be accessed on Windows XP
Click on Cancel

RHEL6

useradd ty Create new local user account


smbpasswd -a ty smbpasswd -> Set encrypted samba
password so that user can login
via samba. –a -> adds user to local
smbpasswd file

Windows XP

Start -> Run: \\192.168.x.10 Access RHEL6 on Windows XP. Can access
RHEL6 on Windows XP with samba user ty and
its password. Will display the server but with no
contents as shares have not been created.

RHEL 6

mkdir /ns /asp /st /java


cd /ns touch n1 n2
cat > n3
Samba Server
Text to be entered
^D Save
cd /asp touch
a1 a2 a3 cd /st
touch s1 s2 s3
cd /java touch
j1 j2 j3
cd /~/Desktop
vim /etc/samba/smb.conf Edit configuration file of Samba
Server

Append the following contents

[ns]
path=/ns
:wq
Save
Restart service to implement changes
service smb restart
made in configuration file
testparm If service is successfully restarted, will
display parameters set in configuration
file

Windows XP

Start -> Run: \\192.168.x.10

Access RHEL6 on Windows XP. Will not


prompt for user name and password
again. Will display the server with content
‘ns’. The shared directory can be accessed
in read only mode
Right-click -> New ->Folder Close the Error as the share is default, read only
Window

RHEL6

chmod a+w /ns Assign write permission on /ns to all


vim /etc/samba/smb.conf Edit configuration file of Samba
Server
Edit the following share
[ns] path=/ns
writable=yes
:wq Save

service smb restart Restart service to implement changes


made in configuration file
testparm If service is successfully restarted, will
display parameters set in configuration
file. ‘writable=yes’ will be displayed as
‘read only = No’ Windows
XP

Start -> Run: \\192.168.x.10 Access RHEL6 on Windows XP.


Right-click -> New ->Folder: crypt No error as the share is writable and directory has
‘w’ permission Close the Window

RHEL6

ls /ns Check contents of /ns. Will also


contain directory created in Windows
vim /etc/samba/smb.conf Edit configuration file of Samba
Server

Append the following contents


[asp] path=/asp
:wq Save
service smb restart Restart service to implement changes
made in configuration file
testparm If service is successfully restarted, will
display parameters set in configuration
file

Windows XP

Start -> Run: \\192.168.x.10 Access RHEL6 on Windows XP. Will


display share ‘ns’ in read write mode
and ‘asp’ read only mode Close the Window

RHEL6

vim /etc/samba/smb.conf Edit configuration file of Samba Server

Edit the following share


[asp] path=/asp
available=no

:wq Save

service smb restart Restart service to implement changes


made in configuration file
testparm If service is successfully restarted, will
display parameters set in configuration
file

Windows XP

Start -> Run: \\192.168.x.10 Access RHEL6 on Windows XP. Will


display share ‘ns’ in read write mode and
share ‘asp’ will not be displayed
Close the Window
Start -> Log Off -> Login again
Start -> Run: \\192.168.x.10 Access RHEL6 on Windows XP. Will
prompt for user name and password
whenever you logout
Click on Cancel
Start -> Control Panel -> User Accounts -> Create a New Account -> Name: ty -> Click on
Next -> Click on Create Account -> Select account ‘ty’ -> Create a password: ty -> Close the
Window

Start -> Log off -> Login as user ‘ty’

Start -> Run: \\192.168.x.10 Access RHEL6 on Windows XP. Will not prompt for
user name and password as Windows login user name and password is same as
samba user and password Close the Window

RHEL6

vim /etc/samba/smb.conf Edit configuration file of Samba Server

Append the following contents


[st] path=/st
:wq Save
service smb restart Restart service to implement changes made in
configuration file
testparm If service is successfully restarted, will display
parameters set in configuration file
Windows XP
Start -> Run: \\192.168.x.10 Access RHEL6 on Windows XP. Will display
share ‘ns’ in read write mode and ‘st’read only
mode
Close the Window

RHEL6

vim /etc/samba/smb.conf Edit configuration file of Samba Server


Edit the following share
[st] path=/st
valid users=bscit
:wq

Save
Restart service to implement changes made in
service smb restart
configuration file
testparm If service is successfully restarted, will display
parameters set in configuration file

Windows XP

Start -> Run: \\192.168.x.10

Access RHEL6 on Windows XP. Will display


share ‘ns’ in read write mode and ‘st’. If you try
to access ‘st’, will prompt for user name and
Click on Cancel password as user ‘ty’ has logged in and share ‘st’
Close the Window can be accessed only by user ‘bscit’

RHEL6

vim /etc/samba/smb.conf
Edit configuration file of Samba Server
Append the following contents
[java]
path=/java
:wq Save
service smb restart Restart service to implement changes made in
configuration file
testparm If service is successfully restarted, will display
parameters set in configuration file

Windows XP

Start -> Run: \\192.168.x.10


Access RHEL6 on Windows XP. ‘java’ can be
Close the Window accessed in read only mode

RHEL6

vim /etc/samba/smb.conf Edit configuration file of Samba Server


Edit the following share
[java] path=/java
deny hosts=192.168.x.30

:wq Save
service smb restart Restart service to implement changes made in
configuration file
testparm If service is successfully restarted, will display
parameters set in configuration file

Windows XP

Start -> Run: \\192.168.x.10 Access RHEL6 on Windows XP. Will display
share ‘java’ but if you try to access it, will prompt
for user name and password as user the current
IP Address is 192.168.11.30, which is denied access

Click on Cancel
Close the Window

Windows XP

Right-click on the Desktop -> New -> Folder: la


Right-click on la -> Sharing and Security -> Select ‘Share this folder’ -. Share name: la ->
Select ‘Allow network users to change my files’ -> Click on OK

RHEL6

smbclient //192.168.x.30/la Access Windows shared folders on Linux system.


Will prompt for password of root user. On
successful login, displays the prompt smb/>
/ refers to shared folder (‘la’ in this case)

mkdir bscit
exit Exit from the shared folder
mount //192.168.x.30/la /data Mount Windows shared folder on local directory

cd /data touch
l1 l2 l3 cd
~/Desktop
umount /data

Windows XP

Check the contents of ‘la’ folder on the Desktop


PRACTICAL 10
IMPLEMENT THE CONCEPT OF DISTRIBUTED FILE SYSTEM
ARCHITECTURE – NFS CONFIGURATION
The Network File System (NFS) is a client/server application that lets a computer user view and
optionally store and update files on a remote computer as though they were on the user's own
computer. The NFS protocol is one of several distributed file system standards for network-attached
storage (NAS). NFS allows the user or system administrator to mount (designate as accessible) all or
a portion of a file system on a server. The portion of the file system that is mounted can be accessed
by clients with whatever privileges are assigned to each file (read-only or read-write). NFS uses
Remote Procedure Calls (RPC) to route requests between clients and servers.

RHEL 6

vim /etc/sysconfig/network-scripts/ifcfg-eth0 NIC Configuration


DEVICE=eth0 Driver of NIC
HWADDR=__________________ MAC address
IPADDR=192.168.x.10 IP Address
NETWORK=192.168.x.0 Network
NETMASK=255.255.255.0 Subnet Mask of IP Address
BROADCAST=192.168.x.255 Broadcast IP Address
BOOTPROTO=static static IP Address
ONBOOT=yes Bring up on boot
:wq Save

service network restart Restart network service to implement the


new NIC configuration
mkdir /abc /xyz
cd /abc touch
a b c cd /xyz
touch x y z
cd ~/Desktop

chmod a+w /abc Assign write permission on /abc to all


vim /etc/exports NFS configuration file
/abc 192.168.X.20(rw) Export /abc in rw mode to 192.168.X.20
/xyz Export/xyz in readonly mode to all
:wq Save
service iptables stop Disable firewalls

service rpcbind restart The rpcbind utility maps RPC services to the ports on
which they listen. Because RPC-based services rely on
rpcbind to make all connections with incoming client
requests, rpcbind must be available before any of these
services start.

service nfs restart Restart service to implement changes made in


configuration file

RHL9

vim /etc/sysconfig/network-scripts/ifcfg-eth0 NIC Configuration


DEVICE=eth0 Driver of NIC
HWADDR=__________________ MAC address
IPADDR=192.168.X.20 IP Address
NETWORK=192.168.X.0 Network
NETMASK=255.255.255.0 Subnet Mask of IP Address
BROADCAST=192.168.x.255 Broadcast IP Address
BOOTPROTO=static static IP Address
ONBOOT=yes Bring up on boot
:wq Save

service network restart Restart network service to implement the


new NIC configuration

service iptables stop Disable firewalls

service portmap restart portmap service enables NFS clients to


identify NFS services on

NFS Servers

mkdir /a /z
showmount -e 192.168.x.10 Show NFS Exports
showmount -d 192.168.x.10 Show locally mounted NFS Exports

mount -t nfs 192.168.x.10:/abc /a mount NFS Export on local directory (-t


specifies file system)

mount -t nfs 192.168.x.10:/xyz /x


showmount -d 192.168.x.10 Show locally mounted NFS Exports
mount cd Check all mountings
/a
mkdir bscit No error as Export has rw permission
touch 1 2 3 cd
/x
mkdir bscit cd Error as Export does not have w
~ permission

umount /a Unmount NFS Export


umount /x

Automount Service

RHL9

mkdir /linux
chmod a+w /linux Assign write permission on /linux to all vim
/etc/auto.master Edit master map file
/linux /etc/auto.lin Mount point and path of secondary map file
:wq Save
vim /etc/auto.lin Secondary map file

la -fstype=nfs,rw 192.168.x.10:/abc will mount /abc on /linux/la in rw mode


(la->submount point)

:wq Save
service autofs start Start automount service
service autofs status Displays configured and active mount points cd /linux/la
rm -rf a User can perform read write operations as mount is
rw mkdir ty cd ~
service autofs stop Stop automount service service autofs
status There will be no active mount points cd /linux/la
Error as subdirectory la is available only
when automount is on

RHEL6

ls /abc

You might also like