Você está na página 1de 177

1

B.E. 3/4 II Semester


WEB PROGRAMMING AND NETWORKING LAB
List of Experiments Prescribed by Osmania University
Web Programming Experiments:
1. Creation of Static web site using XHTML
2. Demonstration of XML, XSLT
3. Validation of Static web page using Java Script
4. Creation of dynamic content in a web site using Servlets
5. Program to handle sessions in a web application.
6. Program to demonstrate usage of Filters in a web application.
7. Creation of dynamic content in a web site using JSP
8. Creation of dynamic content in a web site using ASP .NET
9. Providing data store support for web site using JDBC
10. Creation of Web Services using WSDL
Network Programming Experiments:
11. Understanding and using the following commands. Ifconfig, netstat, ping, arp,
telnet, tftp, ftp.
12. Implementation of concurrent and iterative Echo server using both connection
oriented and connectionless Socket System Calls.
13. Implementation of time of the day service as Connection Oriented Concurrent
Server using Socket System Calls.
14. Build a concurrent Multithreaded File Transfer server. Use separate Threads to
allow the server to handle multiple clients concurrently.
15. Implementation of Remote Program execution using Socket system calls.
Programs to demonstrate the usage of Advanced Socket System calls like
Getsockopt(), Setsockopt(), Select(), Readv(), getpeername(), Getsockname().
16. Implementation a Concurrent Chat Server that allows currently logged in users to
communicate with one another. Use Socket System calls.

2
17. Implementation of Remote files Access using RPC.

WEB PROGRAMMING AND NETWORKING LAB


CONTENTS
S.No.

Name of the Experiment

Page No.

1. Creation of Static web site using XHTML

2. Demonstration of XML, XSLT

12

3. Validation of Static web page using Java Script

20

4. Creation of dynamic content in a web site using Servlets

25

5. Program to handle sessions in a web application.

30

6. Program to demonstrate usage of Filters in a web application.

43

7. Creation of dynamic content in a web site using JSP

49

8. Creation of dynamic content in a web site using ASP .NET

55

9. Providing data store support for web site using JDBC

64

10. Creation of Web Services using WSDL

74

11. Understanding and using the following commands.


Ifconfig, netstat, ping, arp, telnet, tftp, ftp.

80

12. Implementation of concurrent and iterative Echo server using


both connection oriented and connectionless Socket System Calls. 102
13. Implementation of time of the day service as Connection
Oriented Concurrent Server using Socket System Calls

127

14. Build a concurrent Multithreaded File Transfer server.


Use separate Threads to allow the server to handle multiple
clients concurrently.

130

15. Implementation of Remote Program execution using


Socket system calls. Programs to demonstrate the usage of
Advanced Socket System calls like Getsockopt(), Setsockopt(),
Select(), Readv(), getpeername(), Getsockname().

135

16. Implementation a Concurrent Chat Server that allows currently


logged in users to communicate with one another.
17. Implementation of Remote files Access using RPC.

168
174

1. Creation of Static web site using XHTML

AIM: To demonstrate creation of a website using XHTML elements.


REQUIREMENTS:
HARDWARE REQUIREMENTS: Pentium-III (233Hz)/128MB RAM /3.2 GB HDD
SOFTWARE REQUIREMENTS: Windows NT4.0 /Internet Explorer 5

THEORY:
Extensible Hyper Text Markup Language tells the Web browser how to display the page.
Frames: To display more than one XHTML document in the same browser window. Each
XHTML document is called a frame, and each frame is independent of the others.
The <frameset> tag defines how to divide the window into frames. Each frameset defines
a set of rows or columns. The values of the rows/columns indicate the amount of screen
area each row/column will occupy.
Tables: Tables are defined with the <table> tag. A table is divided into rows (with the
<tr> tag), and each row is divided into data cells (with the <td> tag).A data cell can
contain text, images, lists, paragraphs, forms, horizontal rules, tables, etc.
Forms: A form is an area that can contain form elements. Form elements are elements
that allow the user to enter information (like text fields, text area fields, drop-down
menus, radio buttons, checkboxes, etc.) in a form. The most used form tag is the <input>
tag. The type of input is specified with the type attribute.
The following UI screens correspond to a sample website.

SOURCE CODE:

index.html
<?xml version = "1.0" encoding = "utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"><HTML>
<HEAD>
<TITLE> Frames </TITLE>
</HEAD>
<frameset rows="25%,65%,*">
<frame src="one.html" name="a" />
<frameset cols="25%,*">
<frame src="leftframe.html" name="b" />
<frame src="http://vcenet" name="c" />
</frameset>
<frame src="copy.html" name="d" />
</frameset>
</HTML>
Format.html
<?xml version = "1.0" encoding = "utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<HTML>
<HEAD>
<TITLE> Formatting Tags</TITLE>
</HEAD>
<BODY>
<h1>This is the text</h1>
<h6>This is the text</h6>
<b>This is the text</b> <br></br>
<i>This is the text</i> <br></br>
<em>This is the text</em> <br />
<small>This is the text</small> <br />
<big>This is the text</big><br />

5
X<sup>2</sup><br />
X<sub>2</sub><br />
<u>This is the text</u><br />
<strike>This is the text</strike><br />
<pre>
#include&lt;stdio.h&gt;
main() {
printf("Hello World!");
}
</pre>
</BODY>
</HTML>
Anchor.html
<?xml version = "1.0" encoding = "utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"><HTML>
<HEAD>
<TITLE> Anchor tags </TITLE>
</HEAD>
<BODY>
<a href=".\format.html" target="c">Format Tags</a>
<a href=".\lists.html" target="c">
<img src=".\images\Winter.jpg" alt="Image is Winter scene" height="100"
width="100" > </img>
</a>
<a href=".\tables.html" target="c">Tables</a> <br>
</BODY>
</HTML>
Lists.html
<?xml version = "1.0" encoding = "utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"><HTML>
<HEAD>
<TITLE> Lists </TITLE>
</HEAD>

<BODY>
<ol type="I" start="10">
<li>Java</li>
<li>C</li>
<li>Python</li>
<li>C++</li>
<ul type="square">
<li>Java</li>
<li>C</li>
<li>Python</li>
<li>C++</li>
<li>Scala</li>
</ul>
<li>Scala</li>
</ol>

<dl>
<dt>C</dt>
<dd>This is a programming language</dd>
<dt>C</dt>
<dd>This is a programming language</dd>
</dl>
</BODY>
</HTML>
Tables.html
<?xml version = "1.0" encoding = "utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"><HTML>
<HEAD>
<TITLE> Tables</TITLE>
</HEAD>
<BODY>
<table border="3" align="center" cellspacing="10" cellpadding="5">
<caption>Student marks</caption>
<tr>
<th>M1</th>
<th>M2</th>
<th>M3</th>

7
</tr>
<tr>
<td colspan="2" align="center">100 </td>
<td>65</td>
</tr>
<tr>
<td>82 </td>
<td> 98</td>
<td rowspan="2"> 53</td>
</tr>
<tr>
<td> 35</td>
<td>45 </td>
<!-- <td> 99</td> -->
</tr>

</table>
</BODY>
</HTML>
Forms.html
<?xml version = "1.0" encoding = "utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<HTML>
<HEAD>
<TITLE> Forms </TITLE>
</HEAD>
<BODY>
<form method="post">
Username<input type="text" name="un" value="enter" /><br>
Password<input type="password" name="pwd" /> <br>
<input type="radio" name="r" value="M"/>M
<input type="radio" name="r" value="F"/>F
<input type="submit" name="s" value="submit" />
</form>
</BODY>
</HTML>
Copy.html

8
&copy; Copy Right Reserved to S.Vinay kumar
Logo.html
<?xml version = "1.0" encoding = "utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"><HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<BODY bgcolor="cyan">
<h1 align="center">WebSite 1</h1>
</BODY>
</HTML>
Leftframe.html
<?xml version = "1.0" encoding = "utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<HTML>
<HEAD>
<TITLE> Anchor tags </TITLE>
</HEAD>
<BODY>
<a href=".\format.html" target="c">Format Tags</a>
<a href=".\lists.html" target="c">Lists</a> <br>
<a href=".\tables.html" target="c">Tables</a> <br>
<a href=".\anchor.html" target="c">Anchor tags</a> <br>
<a href=".\forms.html" target="c">Form</a> <br>
</BODY>
</HTML>

OUTPUT:

10

11

2. Demonstration of XML, XSLT


AIM: To create an XML file containing information about a catalog of CDs and use
XSLT to transform data to XHTML to display the data.
REQUIREMENTS:
HARDWARE REQUIREMENTS: Pentium-III (233Hz)/128MB RAM /3.2 GB HDD
SOFTWARE REQUIREMENTS: Windows NT4.0 /Internet Explorer 5
THEORY:
XML is used to describe the data.
Applications have to agree on the tag names. Applications that have the right DTD or
XML Schema can process the XML document according to the rules specified.
Extensible Styles Language Transformations enables you to transform XML documents
into another form.

SOURCE CODE:
catalog.xml

12

<?xml version="1.0" encoding="iso-8859-1"?>


<?xml-stylesheet type="text/xsl" href="cd.xsl"?>
<!--Change name in href to cd1.xsl,cd2.xsl,cd3.xsl to view different outputs-->
<catalog>
<cd>
<title>Lord of the rings</title>
<artist>Kate</artist>
<country>US</country>
<Company>Warner Bros</Company>
<price>250</price>
<year>2006</year>
</cd>
<cd>
<title>Quantum of Solace</title>
<artist>James Bond</artist>
<country>US</country>
<Company>Para Mount</Company>
<price>250</price>
<year>2007</year>
</cd>
<cd>
<title>Slumdog Millionaire</title>
<artist>Anil Kapoor</artist>
<country>India</country>
<Company>Warner Bros</Company>
<price>250</price>
<year>2009</year>
</cd>
</catalog>

13
cd.xsl( To display title and artist from a catalog)
<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>CD collection</h2>
<table border="1">
<tr bgcolor="cyan">
<th align="left">Title</th>
<th align="left">Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template></xsl:stylesheet>
cd1.xsl( To display in sorted order on artist)

<?xml version="1.0" encoding="iso-8859-1"?>


<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>

14
<h2>CD collection</h2>
<table border="1">
<tr bgcolor="cyan">
<th align="left">Title</th>
<th align="left">Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<xsl:sort select="artist"/>
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html></xsl:template></xsl:stylesheet>
cd2.xsl( To display data of catalog for year greater than2007)

<?xml version="1.0" encoding="iso-8859-1"?>


<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>CD collection</h2>
<table border="1">
<tr bgcolor="cyan">
<th align="left">Title</th>
<th align="left">Artist</th>
<th align="left">Year</th>
</tr>

15
<xsl:for-each select="catalog/cd">
<xsl:if test="year &gt; 2007">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
<td><xsl:value-of select="year"/></td>
</tr>
</xsl:if>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

cd3.xsl ( To demonstrate for-each element)

<?xml version="1.0" encoding="iso-8859-1"?>


<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>CD collection</h2>
<table border="1">
<tr bgcolor="cyan">
<th align="left">Title</th>
<th align="left">Artist</th>
<th align="left">Year</th>
</tr>

16
<xsl:for-each select="catalog/cd">
<xsl:choose>
<xsl:when test="year &gt; 2007">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
<td><xsl:value-of select="year"/></td>
</tr>
</xsl:when>
<xsl:otherwise>
<tr><td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
<td>sorry year cannot be permitted</td>
</tr></xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

OUTPUT:
//Using cd.xsl

17

//Using cd1.xsl

18

//Using cd2.xsl

//Using cd3.xsl

19

3. Validation of Static Web Page using Java Script

20

AIM: To demonstrate validation of a webpage using JavaScript elements.


REQUIREMENTS:
HARDWARE REQUIREMENTS: Pentium-III (233Hz)/128MB RAM /3.2 GB HDD
SOFTWARE REQUIREMENTS: Windows NT4.0 /Internet Explorer 5
THEORY:
JavaScript was designed to add interactivity to HTML pages. JavaScript is a scripting
language. Scripts to be executed when they are called, or when an event is triggered, go
in the head section. Scripts to be executed when the page loads is to be written in body
section. JavaScript has the ability to create dynamic web pages. Events are actions that
can be detected by JavaScript. Every element on a web page has certain events which can
trigger JavaScript functions. Java Script allows Client Side Validations.
SOURCE CODE:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Form Validation </title>
<script type="text/javascript">
function unamevalidate()
{
// Username should be atleast 5 characters long
var un=document.form.uname;
if(un.value==""||un.value==null)
{
alert("this field must not be empty");
un.focus();
return false;
}
if(un.value.length<=5)
{

21
alert("Username should be atleast 5 characters long");
un.focus();
return false;
}
else
return true;
}

function emailvalidate()
{
//Emailid should
var email=document.form.emailid;
if(email.value==""||email.value==null)
{
alert("this field must not be empty");
email.focus();
return false;
}
if(email.test(/^[a-z][a-z0-9_]{0,7}@[a-z]{1,5}.[a-z]{2,3}$/)!=0)
{
alert("Invalid Email Address");
email.focus();
email.select();
return false;
}
else
return true;
}

function checkboxvalidate()

22
{
//Selection of atleast one course
var k=0;
Array c[]=window.document.form.c.value;
for(i=0;i<c.length;i++)
if(isChecked(c[i]))
{
var k=k+1;

}
if(k<1){
alert("Atleast one should be selected");
return false;}
else
return true;

}
</script>
</head>

<body>
<h2>Student Enrollment to the Course</h2><br><br>
<form method=post action="process.html" name="form" onsubmit="return
checkboxvalidate();">
UserName*:

<input type="text" name="uname" onblur="return

unamevalidate();" onfocus="true"/> <br>


Email-Id*:

<input type="text" name="emailid" onChange="return

emailvalidate();"/> <br>
Course*:
J2EE&nbsp;&nbsp;

<input type="checkbox" name="c" value="dhtml" />

23
<input type="checkbox" name="c" value="javascript"
/>VB.Net&nbsp;&nbsp;
<input type="checkbox" name="c" value="html" checked="checked"
/>C#&nbsp;&nbsp;
<input type="checkbox" name="c" value="css" />Oracle<br><br>
<input type=submit value="Send" name="send" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type=reset />

</form>
</body>
</html>
OUTPUT:

24

25

4. Creation of dynamic content in a web site using Servlets


AIM: Generating dynamic content in a website using servlets .
a) Authentication Servlet authenticates username, password entered by the
user and sends appropriate response to the user
b) Session Tracking using Cookie
c) Session Tracking using Session object
REQUIREMENTS:
HARDWARE REQUIREMENTS: Pentium-III (233Hz)/512MB RAM /20 GB HDD
SOFTWARE REQUIREMENTS: JDK1.5, JRE1.5, Tomcat 6.0, Windows NT4.0 /IE 5
THEORY:
Procedure to Create a Web-Application:
According Servlet 2.2 specification a web application can contain servlets,jsp and other
resources like html,image and other class files.
Once an application is developed we can configure the application by packing up all the
related files in a war file and we can deploy it in any server that is 2.2 complaint.

Steps to pack the resources related to a web application.


1) Create a top level directory, say authenticate (this is the name of our web application).
This directory is the document root of the application.
2) Copy the html files or related files under this directory according to the requirement by
creating appropriate directory structure under authenticate.
3) Create a Directory WEB-INF under authenticate directory.
4) Create a file web.xml and store it under WEB-INF directory. This is called
Deployment Descriptor.
5) Copy your servlet classes and other classes used by the application under
WEB-INF/classes
6) If the application uses additional jar files copy them under WEB-INF/lib directory.
7) create a war file by using jar utility using the total content of authenticate directory.
E:\authenticate>jar cvf authenticate.war

26

SOURCE CODE:

form.html

<?xml version = "1.0" encoding = "utf-8" ?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<HTML>
<HEAD>
</HEAD>
<BODY>
<FORM METHOD=get ACTION="auth">
UserName:<input type=text name=uname />
Password:<input type=text name=pwd />
<input type=submit name=s value=submit/>
</FORM>
</BODY>
</HTML>
</p>
<html>
Authenticate.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Authenticate extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse resp) throws
ServletException,IOException

27
{
String uname,pwd;
uname=req.getParameter("uname");
pwd=req.getParameter("pwd");

PrintWriter out=resp.getWriter();
resp.setContentType("text/html");
//Let us consider we retrived data from DB and set var un,pwd
if(uname.equals("XYZ")&&pwd.equals("XYZ")){
out.println(uname);
out.println(pwd);
out.println("Authentication Successful...");
}
else{//Authentication failed-display errors
out.println("<p style={color:red}>Invalid UserName or Password</p><br>");
//Display form following errors
out.println("html code for displaying form");

/*OR
out.println("<a href=\"form.html\">Go Back</a>");
*/

/*OR
ServletConfig config=getServletConfig();
ServletContext application=getServletContext();
RequestDispatcher rd=application.getRequestDispatcher("/form.html");
rd.include(req,resp);
*/
}
}
}

28

web.xml

<?xml version="1.0" encoding="UTF-8" ?>


<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
<servlet>
<servlet-name>valserv</servlet-name>
<servlet-class>Authenticate</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>valserv</servlet-name>
<url-pattern>/auth</url-pattern>
</servlet-mapping>
</web-app>

29
OUTPUT:

30

5. Program to handle Sessions in a Web Application


AIM: Generating dynamic content in a website using servlets .
a) Authentication Servlet authenticates username, password entered by the
user and sends appropriate response to the user
b) Session Tracking using Cookie
c) Session Tracking using Session object
REQUIREMENTS:
HARDWARE REQUIREMENTS: Pentium-III (233Hz)/512MB RAM /20 GB HDD
SOFTWARE REQUIREMENTS: JDK1.5, JRE1.5, Tomcat 6.0, Windows NT4.0 /IE 5
THEORY:
Procedure to Create a Web-Application:
According Servlet 2.2 specification a web application can contain servlets,jsp and other
resources like html,image and other class files.
Once an application is developed we can configure the application by packing up all the
related files in a war file and we can deploy it in any server that is 2.2 complaint.

Steps to pack the resources related to a web application.


1) Create a top level directory, say authenticate (this is the name of our web application).
This directory is the document root of the application.
2) Copy the html files or related files under this directory according to the requirement by
creating appropriate directory structure under authenticate.
3) Create a Directory WEB-INF under authenticate directory.
4) Create a file web.xml and store it under WEB-INF directory. This is called
Deployment Descriptor.
5) Copy your servlet classes and other classes used by the application under
WEB-INF/classes
6) If the application uses additional jar files copy them under WEB-INF/lib directory.
7) create a war file by using jar utility using the total content of authenticate directory.
E:\authenticate>jar cvf authenticate.war

31

index.html
<?xml version = "1.0" encoding = "utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<HTML>
<HEAD>
</HEAD>
<BODY>
<FORM METHOD=post ACTION="serv1">
UserName<input type=text name=uname /><br>
Age<input type=text name=age /><br>
<input type=submit name=continue value=continue />
</FORM>
</BODY>
</HTML>

SessionServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class SessionServlet extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws
ServletException,IOException
{
String uname,age;
uname=req.getParameter("uname");
age=req.getParameter("age");

32
//Create cookies and send them as response
Cookie c1= new Cookie("uname",uname);
Cookie c2= new Cookie("age",age);
c1.setPath("/");
c2.setPath("/");
//age in seconds
c1.setMaxAge(100);
c2.setMaxAge(100);
//Include them as part of response
resp.addCookie(c1);
resp.addCookie(c2);

PrintWriter out=resp.getWriter();
resp.setContentType("text/html");
/*code to display other form fields*/
out.println("<HTML><BODY>");
out.println("<FORM METHOD=post ACTION=\"serv2\">");
out.println("qualification<input type=text name=qual /><br>");
out.println("company<input type=text name=comp /><br>");
out.println("<input type=submit name=submit value=submit />" );
out.println("</FORM></BODY></HTML>");
}
}

Result.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Result extends HttpServlet
{

33
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws
ServletException,IOException
{
//Retrieve data from form
String qual,comp;
qual=req.getParameter("qual");
comp=req.getParameter("comp");
PrintWriter out=resp.getWriter();
resp.setContentType("text/html");

//Retrieve data from cookies


Cookie[] c=req.getCookies();
/*if(c!=null){
for(int i =0 ;i<c.length;i++){
out.println("Cookie Name = "+ c[i].getName()+"<br>");
out.println("Cookie Value ="+c[i].getValue()+"<br>");
}}*/

/*code to display information entered*/

out.println("<HTML><BODY>");
out.println("The information provided by you is:");
out.println(c[0].getName()+":"+c[0].getValue()+"<br>");
out.println(c[1].getName()+":"+c[1].getValue()+"<br>");
out.println("Qualification:"+qual+"<br>");
out.println("Company:"+comp+"<br>");
out.println("Thank you for subscribing.."+c[0].getValue());
out.println("</BODY></HTML>");
}
}

34
web.xml

<?xml version="1.0" encoding="UTF-8" ?>


<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<servlet>
<servlet-name>session</servlet-name>
<servlet-class>SessionServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>result</servlet-name>
<servlet-class>Result</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>session</servlet-name>
<url-pattern>/serv1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>result</servlet-name>
<url-pattern>/serv2</url-pattern>
</servlet-mapping>
<!-- Establish the default list of welcome files -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
</welcome-file-list>
</web-app>

35
OUTPUT:

36

37
b) SOURCE CODE:
index.html
<?xml version = "1.0" encoding = "utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<HTML>
<HEAD>
</HEAD>
<BODY>
<FORM METHOD=post ACTION="serv1">
UserName<input type=text name=uname /><br>
Age<input type=text name=age /><br>
<input type=submit name=continue value=continue />
</FORM>
</BODY>
</HTML>
SessionServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class SessionServlet extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws
ServletException,IOException
{
String uname,age;
uname=req.getParameter("uname");
age=req.getParameter("age");

//Create cookies and send them as response

38
HttpSession s= req.getSession(true);
s.setAttribute("uname",uname);
s.setAttribute("age",age);

PrintWriter out=resp.getWriter();
resp.setContentType("text/html");
/*code to display other form fields*/
out.println("<HTML><BODY>");
out.println("<FORM METHOD=post ACTION="+resp.encodeURL("serv2")+">");
out.println("qualification<input type=text name=qual /><br>");
out.println("company<input type=text name=comp /><br>");
out.println("<input type=submit name=submit value=submit />" );
out.println("</FORM></BODY></HTML>");
}
}
Result.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Result extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws
ServletException,IOException
{
//Retrieve data from form
String qual,comp;
qual=req.getParameter("qual");
comp=req.getParameter("comp");
PrintWriter out=resp.getWriter();
resp.setContentType("text/html");
//Retrieve data from cookies

39
HttpSession s=req.getSession(true);
/*if(c!=null){
for(int i =0 ;i<c.length;i++){
out.println("Cookie Name = "+ c[i].getName()+"<br>");
out.println("Cookie Value ="+c[i].getValue()+"<br>");
}}*/

/*code to display information entered*/


out.println("<HTML><BODY>");
out.println("The information provided by you is:");
out.println("Username"+":"+s.getAttribute("uname")+"<br>");
out.println("Age"+":"+s.getAttribute("age")+"<br>");
out.println("Qualification:"+qual+"<br>");
out.println("Company:"+comp+"<br>");
out.println("Thank you for subscribing.."+s.getAttribute("uname"));
out.println("</BODY></HTML>");
}
}
web.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<servlet>
<servlet-name>session</servlet-name>

<servlet-class>SessionServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>result</servlet-name>

40
<servlet-class>Result</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>session</servlet-name>
<url-pattern>/serv1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>result</servlet-name>
<url-pattern>/serv2</url-pattern>
</servlet-mapping>
<!-- Establish the default list of welcome files -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
</welcome-file-list>
</web-app>

41
OUTPUT:

42

43

6. Program to demonstrate the usage of Filters in a Web Application


AIM: Usage of Filters in a Web Application.

REQUIREMENTS:
HARDWARE REQUIREMENTS: Pentium-III (233Hz)/512MB RAM /20 GB HDD
SOFTWARE REQUIREMENTS: JDK1.5, JRE1.5, Tomcat 6.0, Windows NT4.0 /IE 5
THEORY:
Procedure to Create a Web-Application:
According Servlet 2.2 specification a web application can contain servlets,jsp and other
resources like html,image and other class files.
Once an application is developed we can configure the application by packing up all the
related files in a war file and we can deploy it in any server that is 2.2 complaint.

Steps to pack the resources related to a web application.


1) Create a top level directory, say authenticate (this is the name of our web application).
This directory is the document root of the application.
2) Copy the html files or related files under this directory according to the requirement by
creating appropriate directory structure under authenticate.
3) Create a Directory WEB-INF under authenticate directory.
4) Create a file web.xml and store it under WEB-INF directory. This is called
Deployment Descriptor.
5) Copy your servlet classes and other classes used by the application under
WEB-INF/classes
6) If the application uses additional jar files copy them under WEB-INF/lib directory.
7) create a war file by using jar utility using the total content of authenticate directory.
E:\authenticate>jar cvf authenticate.war

44
index.html
<?xml version = "1.0" encoding = "utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<HTML>
<HEAD>
</HEAD>
<BODY>
<FORM METHOD=post ACTION="f1">
UserName<input type=text name=uname /><br>
Password<input type=text name=pwd /><br>
<input type=submit name=continue value=continue />
</FORM>
</BODY>
</HTML>

AuthFilter.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;

public class AuthFilter implements Filter


{

private FilterConfig f = null;


private ServletContext sc = null;

public void init(FilterConfig filterConfig)


{
f = filterConfig;

45
sc = f.getServletContext();
}

public void doFilter(ServletRequest request,


ServletResponse response,
FilterChain chain)
throws IOException, ServletException
{
java.lang.Boolean isAuth=null;
HttpServletRequest hreq = (HttpServletRequest) request;
String login_page="/serv1";
String un = hreq.getParameter("uname");
String pwd = hreq.getParameter("pwd");
sc.log("in filter :"+hreq.getRequestURI());
sc.log("in filter :"+hreq.getServletPath());
HttpSession session = hreq.getSession(true);
isAuth = (Boolean)session.getAttribute("canaccess");
sc.log("uname = " + un + "password = " + pwd +" isauth = " + isAuth);
if(isAuth != null){
sc.log("already authenticated");
chain.doFilter(request,response);
return;
}
if(isAuth == null && un !=null && pwd !=null){
/* here is the code to check for uname/pwd */
sc.log("user identified trying to set the information in session");
session.setAttribute("canaccess",(Boolean)new Boolean(true));
chain.doFilter(request,response);
return;
}else{
sc.log("Trying to forward request to login page");

46
sc.getRequestDispatcher(login_page).forward(request, response);
sc.log("after forwarding request to login page");
return;
}
}

public void destroy()


{
f=null;
}

login.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Result extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws
ServletException,IOException
{

PrintWriter out=resp.getWriter();
resp.setContentType("text/html");

out.println("Successful..");
out.println("Cookie Value ="+c[i].getValue()+"<br>");
}
}

47
web.xml

<?xml version="1.0" encoding="UTF-8" ?>


<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<filter>
<filter-name>session</filter-name>
<filter-class>AuthFilter</filter-class>
</filter>
< servlet >
<servlet-name>result</servlet-name>
<servlet-class>Result</servlet-class>
</servlet>
<filter-mapping>
< filter-name>session</ filter-name>
<url-pattern>/*</url-pattern>
</ filter-mapping>
<servlet-mapping>
<servlet-name>result</servlet-name>
<url-pattern>/serv1</url-pattern>
</servlet-mapping>
<!-- Establish the default list of welcome files -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
</welcome-file-list>
</web-app>

48
OUTPUT:

49

7. Creation of dynamic content in a web site using JSP


AIM: Generating dynamic content in a website using JSP (Java Server Pages).
a) A simple jsp page used to display the user-agent header.
b) A JSP to authenticate the user
REQUIREMENTS:
HARDWARE REQUIREMENTS: Pentium-III (233Hz)/512MB RAM /20 GB HDD
SOFTWARE REQUIREMENTS: JDK1.5, JRE1.5, Tomcat 6.0, Windows NT4.0 /IE 5
THEORY:
Java Server Page is designed to simplify the process of developing a web application on
the top of servlet technology. Writing and configuring the application using JSP is easy.
Javax.servlet.jsp and javax.servlet.jsp.tagext contains the interfaces to support JSP
technology and Tag libraries.
We can place our JSP files directly under WEB_APP_ROOT or any other sub directory
except WEB-INF. We need not add an entry in web.xml file for most of JSPs. In JSP
files we can use Page directives like language, import, and include etc. These directives
very much similar to preprocessor directives in C.
a) SOURCE CODE:
index.jsp

USER AGENT :
<%=request.getHeader("User-Agent")%>

web.xml
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE web-app PUBLIC


"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
</web-app>

50
OUTPUT:

51
b) SOURCE CODE:
index.jsp
<HTML>
<HEAD>
</HEAD>
<BODY>
<FORM METHOD=get ACTION="auth">
UN<input type=text name=uname />
PWD<input type=text name=pwd />
<input type=submit name=s />
</FORM>
</BODY>
</HTML>
auth.jsp
<%@page isErrorPage="false" errorPage="error.jsp"%>
<%
String uname=request.getParameter("uname");
String pwd=request.getParameter("pwd");
if(uname.equals("XYZ")&&pwd.equals("XYZ")){
out.println(uname);
out.println(pwd);
out.println("Authentication Successful...");
}
else
throw new Exception("Invalid UserName or Password");
%>
error.jsp
<%@page isErrorPage="true"%>
<%=exception%> <br>
<jsp:include page="../index.jsp" />

52
web.xml
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE web-app PUBLIC


"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
<servlet>
<servlet-name>valserv</servlet-name>
<jsp-file>/jsp/auth.jsp</jsp-file>
</servlet>
<servlet>
<servlet-name>error</servlet-name>
<jsp-file>/jsp/error.jsp</jsp-file>
</servlet>

<servlet-mapping>
<servlet-name>valserv</servlet-name>
<url-pattern>/auth</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>error</servlet-name>
<url-pattern>/error.jsp</url-pattern>
</servlet-mapping>
</web-app>

53
OUTPUT:

54

55

8. Creation of dynamic content in a web site using ASP .NET


AIM: Generating dynamic content in a website using ASP.Net.
REQUIREMENTS:
HARDWARE REQUIREMENTS: Pentium-III (233Hz)/512MB RAM /40 GB HDD
SOFTWARE REQUIREMENTS: Visual Studio 2005, IIS, Windows NT4.0 /IE 5
THEORY:
Steps to create web site:
1. Open Visual Studio .Net
2. Create New Project, click ASP.NET web application
3. In the project types list, click Visual C# Projects
4. Select default.aspx , use ToolBox (Standard) to add controls to the web form
5. Write Code-behind pages associated with web forms and contain the server-side
code for the web forms
6. Add required number of files/webforms
7. Create Web.config configuration file
8. Save all and Build the application
9. Select the aspx page and click view in browser to run the application.

SOURCE CODE:
default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Employee Details</title>
</head>
<body>
<form id="form1" runat="server">

56
<div>
Employee Details<br />
<br />
<asp:HyperLink ID="addnew" runat="server"
NavigateUrl="~/addnewrecord.aspx">Add New Record</asp:HyperLink>
<br />
Delete<br />
Modify<br />
</div>
</form>
</body>
</html>
default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{

}
}

57
addnewrecord.aspx

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="addnewrecord.aspx.cs" Inherits="addnewrecord" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >


<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Add New Record<br />
<br />
Employee Id :
<asp:TextBox ID="empid" runat="server" MaxLength="4"></asp:TextBox><br />
<br />
Employee Name :
<asp:TextBox ID="empname" runat="server"></asp:TextBox><br />
<br />
Date Of Birth :&nbsp;
<asp:TextBox ID="dob" runat="server"></asp:TextBox><br />
<br />
Gender :
<asp:DropDownList ID="ddlgender" runat="server" AutoPostBack="True">
<asp:ListItem Selected="True" Value="M">Male</asp:ListItem>
<asp:ListItem Value="F">Female</asp:ListItem>
</asp:DropDownList><br />

58
<br />
Department :
<asp:TextBox ID="dept" runat="server"></asp:TextBox><br />
<br />
Address1 :
<asp:TextBox ID="add1" runat="server"></asp:TextBox><br />
<br />
Phone No.:
<asp:TextBox ID="phone" runat="server"></asp:TextBox><br />
<br />
EMail :
<asp:TextBox ID="email" runat="server"></asp:TextBox><br />
<br />
<asp:Button ID="Button" runat="server" Text="Register"
OnClick="Button_Click" /></div>
</form>
</body>
</html>

addnewrecord.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

59
using System.Web.Util;
using System.Data.OleDb;

public partial class addnewrecord : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Registration Form");
}
protected void Button_Click(object sender, EventArgs e)
{
string strempid = empid.Text;
string strempname = empname.Text;
string strdatedob = dob.Text;
string strgender = ddlgender.SelectedValue.ToString();
string strdept = dept.Text;
string strphoneno = phone.Text;
string stremail = email.Text;
string stradd1 = add1.Text;
string connectionString =
ConfigurationManager.ConnectionStrings["developer"].ConnectionString;

OleDbConnection oracon = new OleDbConnection(connectionString);


try
{

oracon.Open();
string qrystaffinsert = "insert into emp_details values(" + strempid + ",'" +

strempname + "',to_date('" + strdatedob + "','dd-mon-yyyy'),'" + strgender + "','" +


strdept + "','" + strphoneno + "','" + stremail + "') ";

OleDbCommand cmdstaffinsert = new OleDbCommand(qrystaffinsert);


cmdstaffinsert.Connection = oracon;

60
cmdstaffinsert.CommandType = CommandType.Text;
int result1 = cmdstaffinsert.ExecuteNonQuery();
if (result1 == 1)
{
Response.Write("Record inserted");
}
else
{
Response.Write("problem in insert record");
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}

finally
{
oracon.Close();
oracon.Dispose();
}
}
}

Web.config

<?xml version="1.0"?>
<!-Note: As an alternative to hand editing this file you can use the
web admin tool to configure settings for your application. Use
the Website->Asp.Net Configuration option in Visual Studio.

61
A full list of settings and comments can be found in
machine.config.comments usually located in
\Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration>
<appSettings/>
<connectionStrings>
<add name="developer" connectionString="Provider=OraOLEDB.Oracle.1; User
Id=exam31; Password=exam31; Data Source=orastudb"/>

</connectionStrings>

<system.web>
<!-Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<compilation debug="false" />
<!-The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<authentication mode="Windows" />
<!-The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages

62
to be displayed in place of a error stack trace.

<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">


<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
</system.web>
</configuration>

OUTPUT:

63

64

9. Providing data store support for web site using JDBC


AIM: Use JDBC API within Servlets to connect to MySql database and update/retrieve
the data.
a) Demonstration of Statement object to retrieve data and authenticate user.
b) Demonstration of PreparedStatement to insert and retrieve data.
REQUIREMENTS:
HARDWARE REQUIREMENTS: Pentium-III (233Hz)/512MB RAM /40 GB HDD
SOFTWARE REQUIREMENTS: JDK1.5, JRE1.5, Tomcat 6.0, MySql 5.0,
Windows NT4.0 /IE 5
THEORY:
Create appropriate tables in mysql database using mysql console
Procedure to Establish connection with Database:
1. Select the Driver and extract name of the class that implements java.sql.Driver
interface
2. Determine URL format, username, password, service name from administrator
3. After collecting the above information we need to write code to register driver.
4. Use DriverManager.getConnection() to establish connection with database
5. Use DriverManager class to create Statement, PreparedStatement, ResultSet etc
objects to execute queries.
a) SOURCE CODE:
form.html
<?xml version = "1.0" encoding = "utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<HTML>
<HEAD>
</HEAD>
<BODY>
<FORM METHOD=get ACTION="auth">
UserName:<input type=text name=uname />

65
Password:<input type=text name=pwd />
<input type=submit name=s value=submit />
</FORM>
</BODY>
</HTML>

Authenticate.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class Authenticate extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse resp) throws
ServletException,IOException
{
String uname,pwd,password="";
uname=req.getParameter("uname");
pwd=req.getParameter("pwd");

PrintWriter out=resp.getWriter();
resp.setContentType("text/html");
//Let us retrieve data from DB and set var password
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con;
con = DriverManager.getConnection("jdbc:mysql://localhost/test","","");
System.out.println(con);
//SELECT * FROM pet WHERE name REGEXP "^b";
// Once connected, we can execute any sql statement
Statement stmt = con.createStatement();

66
ResultSet rs = stmt.executeQuery("select password from login where username
like \""+uname+"\" ");
while(rs.next()){
password=rs.getString(1);
}
if(password.equals("")){//Authentication failed
out.println("<p style={color:red}>Invalid UserName</p><br>");
ServletConfig config=getServletConfig();
ServletContext application=getServletContext();
RequestDispatcher rd=application.getRequestDispatcher("/form.html");
rd.include(req,resp);
}
else
if(pwd.equals(password))
{
out.println("Authentication Successful...");
}
else
{//Authentication failed
out.println("<p style={color:red}>Invalid UserName & Password</p><br>");
ServletConfig config=getServletConfig();
ServletContext application=getServletContext();
RequestDispatcher rd=application.getRequestDispatcher("/form.html");
rd.include(req,resp);
}
}catch(Exception ex)
{System.out.println("Exception"+ex);}
}
}
web.xml
<?xml version="1.0" encoding="UTF-8" ?>

67
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<servlet>
<servlet-name>valserv</servlet-name>
<servlet-class>Authenticate</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>valserv</servlet-name>
<url-pattern>/auth</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:
Database(MySQL) Console

68

69

70
b) SOURCE CODE:
form.html
<?xml version = "1.0" encoding = "utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<HTML>
<HEAD>
</HEAD>
<BODY>
<FORM METHOD=get ACTION="auth">
Enter Dept:<input type=text name=dept />
<input type=submit name=s value=submit />
</FORM>
</BODY>
</HTML>
Department.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class Department extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse resp) throws
ServletException,IOException
{
String dept;
dept=req.getParameter("dept");

PrintWriter out=resp.getWriter();
resp.setContentType("text/html");

71
System.out.println("entered dept:"+dept);
//Let us retrive data from DB and set var password
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con;
con = DriverManager.getConnection("jdbc:mysql://localhost/test","","");
System.out.println(con);

// Once connected, we can execute any sql statement


PreparedStatement stmt = con.prepareStatement("select * from student where
dept like ?");
//set query criteria
stmt.setString(1,dept);
ResultSet rs = stmt.executeQuery();
//Display data in table
out.println("<b>Data related to student in"+dept+"department:</b>");
out.println("<table border=2 >");
while(rs.next()){
out.println("<tr>");
out.println("<td>"+rs.getString(1)+"</td>");
out.println("<td>"+rs.getString(2)+"</td>");
out.println("<td>"+rs.getString(3)+"</td>");
out.println("</tr>");
}
out.println("</table>");

}catch(Exception ex)
{System.out.println("Exception"+ex);}
}
}

72
web.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<servlet>
<servlet-name>valserv</servlet-name>
<servlet-class>Authenticate</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>valserv</servlet-name>
<url-pattern>/auth</url-pattern>
</servlet-mapping>
</web-app>

73
OUTPUT:

74

10. Creation of a Web services using WSDL


AIM: Demonstration creation of a web service using WSDL.
REQUIREMENTS:
HARDWARE REQUIREMENTS: Pentium-III (233Hz)/512MB RAM /40 GB HDD
SOFTWARE REQUIREMENTS: Visual Studio 2005, IIS, Windows NT4.0 /IE 5
THEORY:
A Web Service is a URL-addressable software resource that performs discrete
function(s). They are web based applications that use open, XML-based standards and
transport protocols to exchange data with clients. Web Services communicate using a
standard protocol known as SOAP and is located by its listing in a UDDI directory.
SOAP a lightweight XML-based messaging protocol used to encode the information in
Web service request and response messages before sending them over a network.
WSDL an XML-formatted language used to describe a Web service's capabilities as
collections of communication endpoints capable of exchanging messages. WSDL is an
integral part of UDDI, an XML-based worldwide business registry.

Steps to generate Web Service using Visual Studio 2005:


1. Open Visual Studio 2005
2. Create New Web Site, Select ASP.Net Web Service and set the language to C#
3. Open Service.cs and write the methods that are to be exposed as service
4. Select Service.asmx and include a directive webservice and include the Service.cs
file as part of CodeBehind
5. Save the solution
6. Build the solution
7. Run the service by calling ctrl+F5
8. We can locate the services by using the URL
http://localhost:1176/testservice/Service.asmx
9. Click the service that you want to be serviced with.
10. To view the WSDL http://localhost:1176/testservice/Service.asmx?WSDL

75

SOURCE CODE:
Service.cs
public class Service : System.Web.Services.WebService
{
public Service () {
//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
public string HelloWorld() {
return "Hello World";
}
[WebMethod]
public string method(String s)
{
return "Return from method"+s;
}
}

Service.asmx

<%@ WebService Language="C#"


CodeBehind="~/App_Code/Service.cs" Class="Service" %>

76

OUTPUT:

77

78

79

80

11. Understanding and using the Following Commands


1.1 ARP COMMAND:
arp - manipulate the system ARP cache
arp [-evn] [-H type] [-i if] -a [hostname]
arp [-v] [-i if] -d hostname [pub]
arp [-v] [-H type] [-i if] -s hostname hw_addr [temp]
arp [-v] [-H type] [-i if] -s hostname hw_addr [netmask nm] pub
arp [-v] [-H type] [-i if] -Ds hostname ifa [netmask nm] pub
arp [-vnD] [-H type] [-i if] -f [filename]

DESCRIPTION
Arp manipulates the kernels ARP cache in various ways. The primary options are
clearing an address mapping entry and manually setting up one. For debugging purposes,
the arp program also allows a complete dump of the ARP cache.
OPTIONS:
-v, --verbose
Tell the user what is going on by being verbose.
-n, --numeric
Shows numerical addresses instead of trying to determine symbolic host, port or
user names.
-H type, --hw-type type, -t type
When setting or reading the ARP cache, this optional parameter tells arp which
class of entries it should check for. The default value of this parameter is ether (i.e.
hardware code 0x01 for IEEE 802.3 10Mbps Ethernet). Other values might include
network technologies such as ARCnet (arc net) , PROnet (pronet) , AX.25 (ax25) and
NET/ROM(netrom).
-a [hostname], --display [hostname]
Shows the entries of the specified hosts. If the hostname parameter is not used,
all entries will be displayed. The entries will be displayed in alternate (BSD) style.
-d hostname, --delete hostname

81

Remove any entry for the specified host. This can be used if the indicated host is brought
down, for example:
-D, --use-device
Use the interface ifa's hardware address.
-e

Shows the entries in default (Linux) style.

-i If, --device If
Select an interface. When dumping the ARP cache only entries matching the
specified interface will be printed. When setting a permanent or temp ARP

entry

this interface will be associated with the entry; if this option is not used, the kernel will
guess based on the routing table. For pub entries the specified interface is the interface on
which ARP requests will be answered.
NOTE: This has to be different from the interface to which the IP datagrams will be
routed.
-s hostname hw_addr, --set hostname
Manually create an ARP address mapping entry for host hostname with hardware
address set to hw_addr class, but for most classes one can assume that the usual
presentation

can be used.

For the Ethernet class, this is 6 bytes in hexadecimal,

separated by colons. When adding proxy arp entries (that is those with the publish flag
set a netmask may be specified to proxy arp for entire subnets. This is not good
practice, but is supported by older kernels because it can be useful. If the temp flag is not
supplied entries will be permanent stored into the ARP cache.
NOTE: As of kernel 2.2.0 it is no longer possible to set an ARP entry for an entire
subnet. Linux instead does automatic proxy arp when a route exists and it is
forwarding.
-f filename, --file filename
Similar to the -s option, only this time the address info is taken from file filename
set up. The name of the data file is very often /etc/ethers, but this is not official. If no
filename is specified /etc/ethers is used as default.
The format of the file is simple; it only contains ASCII text lines with a hostname, and a
hardware address separated by white space. Additionally the pub, temp and net mask

82
flags can be used. In all places where a hostname is expected, one can also enter an IP
address in dotted-decimal notation.
As a special case for compatibility the order of the hostname and the hardware address
can be exchanged.Each complete entry in the ARP cache will be marked with the C
flag. Permanent entries are marked with M and published entries have the P flag.
1.2. TELNET:
telnet - user interface to the TELNET protocol
telnet [-8EFKLacdfrx] [-X authtype] [-b hostalias] [-e escapechar]
[-k realm] [-l user] [-n tracefile] [host [port]]
DESCRIPTION:
The telnet command is used to communicate with another host using the
protocol. If telnet is invoked without the host argument, it

TELNET

enters command mode,

indicated by its prompt (telnet>). In this mode, it accepts and executes the commands
listed below. If it is invoked with arguments, it performs an open command with those
arguments.
OPTIONS:
-8

Specifies an 8-bit data path. This causes an attempt to negoti


ate the TELNET BINARY option on both input and output.

-E

Stops any character from being recognized as an escape character.

-F

If Kerberos V5 authentication is being used, the -F option allows

the local credentials to be forwarded to the remote system,including any credentials that
have already been forwarded into the local environment.
-K

Specifies no automatic login to the remote system.

-L

Specifies an 8-bit data path on output. This causes the BINARY


option to be negotiated on output.

-X atype
Disables the atype type of authentication.
-a

Attempt automatic login. Currently, this sends the user name via

the USER variable of the ENVIRON option if supported by the remote system. The
name used is that of the current user as returned by getlogin(2) if it agrees with the
current user ID, otherwise it is the name associated with the user ID.

83
-b hostalias

Uses bind(2) on the local socket to bind it to an aliased address (see ifconfig(8) and the
``alias'' specifier) or to the address of another interface than the one naturally chosen by
connect(2).
This can be useful when connecting to services which use IP addresses for authentication
and reconfiguration of the server is undesirable (or impossible).
-c

Disables the reading of the user's .telnetrc file.

-d

Sets the initial value of the debug toggle to TRUE.

-e escapechar
Sets the initial telnet escape character to escape char. If escape char is omitted,
then there will be no escape character.
-f

If Kerberos V5 authentication is being used, the -f option allows

the local credentials to be forwarded to the remote system.


-k realm
If Kerberos authentication is being used, the -k option requests
that telnet obtain tickets for the remote host in realm instead of the remote host's realm, as
determined by krb_realmofhost(3).

1.3. FTP
ftp - Internet file transfer program
ftp [-pinegvd] [host]
pftp [-inegvd] [host]

DESCRIPTION:Ftp is the user interface to the Internet standard File Transfer Protocol. The program
allows a user to transfer files to and from a remote network site.options may be specified
at the command line, or to the command interpreter.
OPTIONS:

84
-p

Use passive mode for data transfers. Allows use of ftp in environments where a

firewall prevents connections from the outside world back to the client machine. Requires
that the ftp server support the PASV command. This is the default now for all clients (ftp
and pftp) due to security concerns using the PORT transfer mode. The flag is kept for
compatibility only and has no effect anymore.
-i
-n

turn off interactive prompting during multiple file transfers.


Restrains ftp from attempting ``auto-login'' upon initial connection. If auto-login

is enabled, ftp will check the .netrc (see netrc(5)) file in the user's home directory for an
entry describing an account on the remote machine. If no entry exists, ftp will prompt for
the remote machine login name (default is the user identity on the local machine), and, if
necessary, prompt for a password and an account with which to login.
-e

Disables command editing and history support, if it was compiled into the ftp

executable. Otherwise, does nothing.


-g

Disables file name globbing.

-v

Verbose option forces ftp to show all responses from the remote

server, as well as report on data transfer statistics.


-d

Enables debugging.

The client host with which ftp is to communicate may be specified on the

command

line. If this is done, ftp will immediately attempt to establish a connection to an FTP
server on that host; otherwise, ftp will enter its
instructions from the user. When ftp is

command interpreter and await

awaiting commands from the user the prompt

`ftp>' is provided to the user. The following commands are recognized by ftp:
[Command [args]]
Invoke an interactive shell on the local machine. If there are arguments, the first is taken
to be a command to execute directly, with the rest of the arguments as its arguments.

$ macro-name [args]
Execute the macro macro-name that was defined with the macdef command. arguments
are passed to the macro un globbed.
account [passwd]

85
Supply a supplemental password required by a remote system for access to resources
once a login has been successfully completed. If no argument is included, the user will
be prompted for an account password in a non-echoing input mode.
append local-file [remote-file]
Append a local file to a file on the remote machine.If remote-file is left unspecified, the
local file name is used in naming the remote file after being altered by any ntrans or
nmap setting. File transfer uses the current settings for type, format, mode, and structure
1.4 NETSAT:
netstat command netstat displays the contents of various network-related data structures
in various formats, depending on the options you select.
The first form of the command displays a list of active sockets for each protocol. The
second form selects one from among various other network data structures. The third
form shows the state of the interfaces. The fourth form displays the routing table, the fifth
form displays the multicast routing table, and the sixth form displays the state of DHCP
on one or all interfaces.
SYNOPSIS
Shows network status.
SYNTAX:netstat [-a] [-n] [-v]
netstat [-g | -m | -p | -s | -f address_family ] [-n] [-P protocol]
netstat [ -i ] [ -I interface ] [ interval ]
netstat -r [-a] [-n] [-v ]
netstat -M [-n] [-s ]
netstat -D [ -I interface ]

-a

Show the state of all sockets and all routing table entries; normally,
sockets used by server processes are not shown and only interface,
host, network, and default routes are shown.

-n

Show network addresses as numbers. netstat normally displays


addresses as symbols. This option may be used with any of the
display formats.

86
-v

Verbose. Show additional information for the sockets and the


routing table.

-g

Show the multicast group memberships for all interfaces.

-m

Show the STREAMS statistics.

-p

Show the address resolution (ARP) tables.

-s

Show per-protocol statistics. When used with the -M option, show


multicast routing statistics instead.

-i

Show the state of the interfaces that are used for TCP/IP traffic.

-r

Show the routing tables.

-M

Show the multicast routing tables. When used with the -s option,
show multicast routing statistics instead.

-d

Show the state of all interfaces that are under Dynamic Host
Configuration Protocol (DHCP) control.

-D

Show the status of DHCP configured interfaces.

-f address_family imit statistics or address control block reports to those of the


specified address_family, which can be one of:
inet

For

the

AF_INET

address

family

unix For the AF_UNIX address family


-P protocol

Limit display of statistics or state of all sockets to those applicable


to protocol.

- I interface

Show the state of a particular interface. interface can be any valid


interface such as ie0 or
le0.

1.5 ping, ping6- send ICMP ECHO_REQUEST to network hosts

SYNOPSIS
ping [-LRUbdfnqrvVaAB] [-c count] [-m mark] [-i interval] [-l preload]
[-p pattern] [-s packetsize] [-t ttl] [-w deadline] [-F flowlabel] [-I
interface] [-M hint] [-N nioption] [-Q tos] [-S sndbuf] [-T timestamp

87
option] [-W timeout] [hop ...] destination

DESCRIPTION
ping uses the ICMP protocol's mandatory ECHO_REQUEST datagram to elicit
an ICMP ECHO_RESPONSE from a host or gateway. ECHO_REQUEST
datagrams (``pings'') have an IP and ICMP header, followed by a struct timeval
and then an arbitrary number of ``pad'' bytes used to fill out the packet.
ping6 can also send Node Information Queries (RFC4620).
OPTIONS
-a

Audible ping.

-A Adaptive ping. Interpacket interval adapts to round-trip time, so that


effectively not more than one (or more, if preload is set) unanswered probes present in
the network. Minimal interval is 200msec for not super-user. On networks with low rtt
this mode is essentially equivalent to flood mode.
-b

Allow pinging a broadcast address.

-B Do not allow ping to change source address of probes. The address is


bound to one selected when ping starts.
-m mark
use mark to tag the packets going out. This is useful for variety of reasons
within the kernel such as using policy routing to select specific outbound processing.
-c count
Stop after sending count ECHO_REQUEST packets. With deadline
option, ping waits for count ECHO_REPLY packets, until the timeout
expires.
-d

Set the SO_DEBUG option on the socket being used. Essentially,


this socket option is not used by Linux kernel.

-F flow label
Allocate and set 20 bit flow label on echo request packets.
(Only ping6). If value is zero, kernel allocates random flow
label.

88
-f Flood ping. For every ECHO_REQUEST sent a period ``.'' is printed, while
for ever ECHO_REPLY received a backspace isp printed. This provides a rapid
display of how many packets are being dropped. If interval is not given, it sets interval
to zero and outputs packets as fast as they come back or one hundred times per
second, whichever is more. Only the super-user may use this option with zero interval.
-i interval
Wait interval seconds between sending each packet. The default is to wait for
one second between each packet normally, or not to wait in flood mode. Only super-user
may set interval to values less 0.2 seconds.
-I interface address
Set source address to specified interface address. Argument may be numeric IP
address or name of device. When pinging IPv6 link-local address this option is required.

-l preload
If preload is specified, ping sends that many packets not waiting for reply.
Only the super-user may select preload more than 3.
-L

Suppress loopback of multicast packets. This flag only applies


if the ping destination is a multicast address.

When using ping for fault isolation, it should first be run on the local host, to verify
that the local network interface is up and running. Then, hosts and gateways further and
further away should be ``pinged''. Round-trip times and packet loss statistics are
computed. If duplicate packets are received, they are not included in the packet loss
calculation, although the round trip time of these packets is used
In calculating the minimum/average/maximum round-trip time numbers.
When the specified number of packets have been sent (and received) or if the program is
terminated with a SIGINT, a brief summary is displayed. Shorter current statistics can be
obtained without termination of process with signal SIGQUIT.
If ping does not receive any reply packets at all it will exit with code 1. If a packet
count and deadline are both specified, and fewer than count packets are received by
the time the deadline has arrived, it will also exit with code 1. On other error it exits
with code 2. Otherwise it exits with code 0. This makes it possible to use the exit code
to see if a host is alive or not. This program is intended for use in network testing,
measurement and management. Because of the load it can impose on the network, it is

89
unwise to use ping during normal operations or from automated scripts.
ICMP PACKET DETAILS
An IP header without options is 20 bytes. An ICMP ECHO_REQUEST packet
contains an additional 8 bytes worth of ICMP header followed by an arbitrary amount
of data. When a packetsize is given, this indicated the size of this extra piece of data
(the default is 56). Thus the amount of data received inside of an IP packet of type ICMP
ECHO_REPLY will always be 8 bytes more than the requested data space (the ICMP
header).
If the data space is at least of size of struct timeval ping uses the beginning bytes of this
space to include a timestamp which it uses in the computation of round trip times. If the
data space is shorter, no round trip times are given.

1.6 ifconfig - configure a network interface


SYNOPSIS
ifconfig [-v] [-a] [-s] [interface]
ifconfig [-v] interface [aftype] options | address ...
DESCRIPTION
Ifconfig is used to configure the kernel-resident network interfaces. It is
used at boot time to set up interfaces as necessary. After that, it is usually only
needed when debugging or when system tuning is needed. If no arguments are
given, ifconfig displays the status of the currently active interfaces. If a single
interface argument is given, it displays the status of the given interface only; if a
single -a argument is given, it displays the status of all interfaces, even those that
are down. Otherwise, it configures an interface.

Address Families
If the first argument after the interface name is recognized as the name of a supported
address family, that address family is used
for decoding and displaying all protocol addresses. Currently supported address
families include inet (TCP/IP, default), inet6

90
(IPv6), ax25 (AMPR Packet Radio), ddp (Appletalk Phase 2), ipx (Novell IPX) and
netrom (AMPR Packet radio).
OPTIONS
-a

display all interfaces which are currently available, even if down

-s

display a short list (like netstat -i)

-v

be more verbose for some error conditions

interface
The name of the interface. This is usually a driver name followed by a unit
number, for example eth0 for the first Ethernet interface. If your kernel supports alias
interfaces, you can specify them with eth0:0 for the first alias of eth0. You can use them
to assign a second address. To delete an alias interface use ifconfig eth0:0 down. Note:
for every scope (i.e. same net with address/netmask combination) all aliases are deleted,
if you delete the first (primary).
Up This flag causes the interface to be activated. It is implicitly specified if an
address is assigned to the interface.
Down This flag causes the driver for this interface to be shut down.
[-]arp Enable or disable the use of the ARP protocol on this interface.
[-] promisc
Enable or disable the promiscuous mode of the interface. If selected, all
packets on the network will be received by the interface.
[-] allmulti
Enable or disable all-multicast mode. If selected, all multicast packets on the
network will be received by the interface.
netmask addr
Set the IP network mask for this interface. This value defaults to the usual class
A, B or C network mask (as derived from the interface IP address), but it can be set to
any value.

91
add addr/prefixlen
Add an IPv6 address to an interface.
Del addr/prefixlen
Remove an IPv6 address from an interface.
io_addr addr
Set the start address in I/O space for this device.
mem_start addr
Set the start address for shared memory used by this device. Only a few devices
need this.
media type
Set the physical port or medium type to be used by the device. Not all devices
can change this setting, and those that can
Vary in what values they support. Typical values for type are 10base2 (thin
Ethernet), 10baseT (twisted-pair 10Mbps Ether net), AUI (external transceiver) and so
on. The special medium type of auto can be used to tell the driver to auto-sense the
media. Again, not all drivers can do this.
[-]broadcast [addr]
If the address argument is given, set the protocol broadcast address for this
interface. Otherwise, set (or clear) the IFF_BROADCAST flag for the interface.

[-]pointopoint [addr]
This keyword enables the point-to-point mode of an interface, meaning that it is
a direct link between two machines with nobody else listening on it.
If the address argument is also given, set the protocol address of the other side of
the link, just like the obsolete dstaddr
Keyword does. Otherwise, set or clear the IFF_POINTOPOINT flag for the
interface.
hw class address
Set the hardware address of this interface, if the device driver supports this
operation. The keyword must be followed by the name of the hardware class and the
printable ASCII equivalent of the hardware address. Hardware classes currently
supported include ether (Ethernet), ax25 (AMPR AX.25), ARCnet and netrom (AMPR

92
NET/ROM).
multicast
Set the multicast flag on the interface. This should not normally be needed as the
drivers set the flag correctly themselves.
address
The IP address to be assigned to this interface.
txqueuelen length
Set the length of the transmit queue of the device. It is useful to set this to small
values for slower devices with a high
latency (modem links, ISDN) to prevent fast bulk transfers from disturbing
interactive traffic like telnet too much.
Inter process communication using Sockets:
A socket is one end of an inter process communication channel, the two processes each
can establish their own socket.
The following steps are involved in establishing a socket on the server side is as follows:
1. Create a socket with socket () system call.
2. Bind the socket to an address using bind () system call. For a server socket on the
internet an address consists of a port number on the host machine.
3. Listen for connection with the listen () system call.
4. Accept a connection with the accept () system call. This call typically blocks until
a client connects with the server.
5. Send and receive data.

The following steps are involved in establishing a socket on the client side is as follows:
11. Create a socket with socket () system call.
12. Connect the socket to the address of the server using the connect () system
call.
13. Send and receive data. There are number of ways to do this, but the simplest is
to use the read () and write () system call.

93
In the client server design, server is considered as echo server, is the program that
reads a character string sent by a client program and returns the same to the client. There
are 2 ways to implement the above they are:

6. Connection oriented (TCP) concurrent server and iterative server.


7. Connection less (UDP) concurrent server and iterative server.

SOCKET SYSTEM CALLS:


#includes<stdio.h>:
This header file contains declaration used in most input and output functions and is
typically included in all c programs.

#includes<sys/types.h>:
This header file contains definitions of a number of data types used in system calls .these
types are used in the next two include files.

#includes<sys/socket.h>:
This header file includes a number of definitions of structures needed for sockets.

#includes<netinet/in.h>:
This header file contains constants and structures needed for internet domain address
SOCKET: socket - create an endpoint for communication
#include <sys/types.h>
#include <sys/socket.h>

int socket (int family, int type, int protocol);

DESCRIPTION:
Socket creates an endpoint for communication and returns a descriptor. The domain
parameter specifies a communication domain; this selects the protocol family which

94
will be used for communication. These families are defined in <sys/socket.h>. The
currently understood formats include:
Name

Purpose

PF_UNIX, PF_LOCAL Unix domain protocols


PF_INET

IPv4 Internet protocols

PF_INET6

IPv6 Internet protocols

PF_IPX

IPX - Novell protocols

PF_ROUTE

Routing sockets

PF_KEY

Key sockets

The socket has the indicated type, which specifies the communication semantics.
Currently defined types are:
SOCK_STREAM:
Provides sequenced, reliable, two-way, connection- based byte streams. An out-of-band
data transmission mechanism may be supported.
SOCK_DGRAM:
Supports data grams (connectionless, unreliable messages of a fixed maximum length).
SOCK_SEQPACKET:
Provides a sequenced, reliable, two-way connection- based data transmission path for
data grams of fixed maximum length; a consumer is required to read an entire packet
with each read system call.
SOCK_RAW:
Provides raw network protocol access.
SOCK_RDM:
Provides a reliable datagram layer that does not guarantee ordering.
SOCK_PACKET:
Obsolete and should not be used in new programs; Some socket types may not be
implemented by all protocol families;

for

example, SOCK_SEQPACKET is not

implemented for AF_INET.


The protocol specifies a particular protocol to be used with the socket. Normally only
a single protocol exists to support a particular socket type within a given protocol

95
family.

However, it is possible that many protocols may exist, in which case a

particular protocol must be in this manner. The protocol number to use is specific to the
"communication domain" in which communication is to take place.
Sockets of type SOCK_STREAM are full-duplex byte streams,

Similar to pipes. They do not preserve record boundaries. A stream socket must be in a
connected state before any data may be sent or received on it. A connection to
Another socket is created with a connect call. Once connected, data may be transferred
using read and write calls or some variant of the send and recv calls.

When a session has been completed a close may be performed. Out-of-band data may
also be transmitted as described in send and received as described in recv.
The communications protocols which implement a SOCK_STREAM ensure that data is
not lost or duplicated. If a piece of data for which the peer protocol has buffer space
cannot be successfully transmitted within a reasonable length of time, then the
connection is considered to be dead. When SO_KEEPALIVE is enabled on the socket
the protocol checks in a protocol-specific manner if the other end is still alive.
A SIGPIPE signal is raised if a process sends or receives on a broken stream; this
causes naive processes, which do not handle the signal, to exit. SOCK_SEQPACKET
sockets employ the same system calls as SOCK_STREAM sockets.

The only

difference is that read calls will return only the amount of data requested, and any
remaining in the arriving packet will be discarded. Also all message boundaries in
incoming data grams are preserved.

SOCK_DGRAM and SOCK_RAW sockets allow sending of data grams to


correspondents named in send calls. Data grams are generally received with recvfrom,
which returns the next datagram with its return address.
SOCK_PACKET is an obsolete socket type to receive raw packets directly from the
device driver. Use packet instead.
When the network signals an error condition to the protocol
module (e.g. using a ICMP message for IP) the pending error flag is set for the socket.

96
The next operation on this socket will return the error code of the pending error. For
some protocols it is possible to enable a per-socket error queue to retrieve detailed
information about the error; see IP_RECVERR in ip.
The operation of sockets is controlled by socket level options. These options are
defined in <sys/socket.h>.Setsockopt and getsockopt are used to set and getoptions,
respectively.

RETURN VALUE
-1 is returned if an error occurs; otherwise the return value is a descriptor referencing
the socket.

RECV:
#include <sys/types.h>
#include <sys/socket.h>

int recv(int sockfd, void *buf, size_t len, int flags);

DESCRIPTION:The recv function is used to receive messages (similar to read) from a socket, whether
or not it is connection-oriented. If from is not NULL, and the socket is not connectionoriented, the source address of the message is filled in the argument from len is a
value-result parameter, initialized to the size of the buffer associated with from, and
modified on return to indicate the actual size of the address stored there.
The recv call is normally used only on a connected socket .All three routines return the
length of the message on successful completion. If a message is too long to fit in the
supplied buffer, excess bytes may be discarded depending on the type of socket the
message is received from socket when more data arrives.
The flags argument to a recv call is formed by OR'ing one or more of the following
values:
RETURN VALUE
The call returns the number of bytes received, or -1 if an error occurred.

97

SEND: sends a message from a socket


#include <sys/types.h>
#include <sys/socket.h>

int send(int s, const void *msg, size_t len, int flags);

DESCRIPTION:
Send is used to transmit a message to another socket. Send may be used only when the
socket is in a connected state, the address of the target is given by to with tolen
specifying its size. The length of the message is given by len. If the message is
too long to pass atomically through the underlying protocol, the error EMSGSIZE is
returned, and the message is not transmitted. No indication of failure to deliver is
implicit in a send. Locally detected errors are indicated by a return value of-1.
When the message does not fit into the send buffer of the socket, send normally blocks,
unless the socket has been placed in non-blocking I/O mode. In non-blocking mode it
would return EAGAIN in this case. The select call may be used to determine when
it is possible to send more data.
RETURN VALUE:
The call returns the number of characters sent, or -1 if an error occurred.

CONNECT:
connect - initiate a connection on a socket
#include <sys/types.h>
#include <sys/socket.h>

int connect(int sockfd, const struct sockaddr *serv_addr,socklen_t addrlen);

DESCRIPTION:
The file descriptor sockfd must refer to a socket.

If the socket is of type

SOCK_DGRAM then the serv_addr address isthe address to which datagrams are sent

98
by default, and the only address from which datagrams are received. If the socket is
of type SOCK_STREAM or SOCK_SEQPACKET,

this call attempts to make a

connection to another socket. The other socket is specified by serv_addr, which is


an address (of length addrlen) in the communications space of the socket.

Each

communications space interprets the serv_addr parameter in its own way.


Generally, connection-based protocol sockets may successfully connect only once;
connectionless protocol sockets may use connect multiple times to change their
association. Connectionless sockets may dissolve the association by connecting to an
address with the sa_family member of sockaddr set to AF_UNSPEC.

RETURN VALUE:
If the connection or binding succeeds, zero is returned.On error, -1 is returned, and
errno is set appropriately.

ERRORS
The following are general socket errors only.

There may be other domain-specific

error codes.
EBADF --The file descriptor is not a valid index in the descriptor table.
EFAULT-- The socket structure address is outside the user's address space.

ACCEPT:
accept - accept a connection on a socket
#include <sys/types.h>
#include <sys/socket.h>

int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);

DESCRIPTION:The accept function is used with connection-based socket types (SOCK_STREAM,


SOCK_SEQPACKET and SOCK_RDM). It extracts the first connection request on
the queue of pending connections, creates a new connected socket with mostly the

99
same properties as sockfd, and allocates a new file descriptor for the socket, which is
returned. The newly created socket is no longer in the listening state.

The original

socket s is unaffected by this call. Note that any per file descriptor flags (everything that
can be set with the F_SETFL fcntl, like non blocking or async state) are not inherited
across an accept.
The argument addr is a pointer to a sockaddr structure. This structure is filled in with
the address of the connecting entity, as known to the communications layer. The exact
format of the address passed in the addr parameters determined by the socket's family
The addrlen argument is a value-result parameter: it should initially contain the size of
the structure pointed to by addr, on return it will contain the actual length (in bytes) of
the address returned. When addr is NULL nothing is filled in.
If no pending connections are present on the queue, and the socket is not
marked as non-blocking, accept blocks the caller until a connection is present. If the
socket is marked non-blocking and no pending connections are present on the queue,
accept returns EAGAIN.In order to be notified of incoming connections on a socket,
you can use select.

A readable event will be delivered when a new connection is

attempted and you may then call accept to get a socket for that connection.
Alternatively, you can set the socket to deliver SIGIO when activity occurs on a
socket;There may not always be a connection waiting after a SIGIO is delivered or
select or poll return a

readability event because the connection might have been

removed by an asynchronous network error or another thread before accept is called. If


this happens then the call will block waiting for the next connection to arrive.

To

ensure that accept never blocks, the passed socket s needs to have the O_NONBLOCK
flag set.

RETURN VALUE
The call returns -1 on error. If it succeeds, it returns a non-negative integer that is a
descriptor for the accepted socket.

BIND: Bind will bind a name to socket


#include <sys/socket.h>

100

int bind(int sockfd,const struct sockaddr *myaddr,socklen_t addrlen);

it gives the socket sockfd, the local address myaddr, myaddr is addrlen bytes long.
Traditionally, this is called assigning a name to a socket. When a socket is created with
socket () it exists in a name space but has no name assigned.It is normally necessary to
assign local address using bind before sock_stream socket may receive connection.

RETURN VALUE:
On sucess0 is return, on error 1 is returned and errno is set to appropriately.

LISTEN:
listen - listen for connections on a socket
#include <sys/socket.h>
int listen(int s, int backlog);

DESCRIPTION
To accept connections, a socket is first created with socket, a willingness to accept
incoming connections and a queue limit for incoming connections are specified with
listen, and then the connections are accepted with accept. The listen call applies only
to sockets of type SOCK_STREAM or SOCK_SEQPACKET.
The backlog parameter defines the maximum length the queue of pending connections
may grow to. If a connection request arrives with the queue full the client may receive
an error with an indication of ECONNREFUSED or, if the underlying protocol supports
retransmission, the request may be ignored so that retries succeed.

RETURN VALUE:On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

101

ERRORS:EADDRINUSE
Another socket is already listening on the same port.
EBADF: The argument s is not a valid descriptor.
ENOTSOCK: The argument s is not a socket.
EOPNOTSUPP: The socket is not of a type that supports the listen operation.

SENDTO and RECVFROM : similar to the standard read and write functions with 3
additional arguments .these system calls are used in UDP ,for data transfer between
server and client.
1. ssize_t

sendto(int sockfd, const void *buff ,size_t nbytes,int flags, struct


sockaddr *from, socklen_t *addrelen);

2.ssize_t

recvfrom(int sockfd, void *buff ,size_t nbytes,int flags,


struct sockaddr *to, socklen_t *addrelen);

102

12. Implementation of Concurrent and Iterative Echo Server Using both


Connection Oriented and Connectionless socket system calls.
12.1 AIM: Program for connection-oriented (TCP) service with server as concurrent
server
REQUIREMENTS:
HARDWARE

: Pentium II (233 Hz)/32MB RAM /3.2 GB HDD

SOFTWARE

: Red Hat Linux server v.7.0,c

THEORY:
A connection oriented service requires that the two application programs to establish a
logical connection with each other before communication can take place. This is also
called as virtual circuit because it appears to the application programs that they have
dedicated circuit between them, even though the actual data flow usually takes place on a
switched network. A connection oriented exchange involves:
c) Connection establishment.
d) Data transfer.
e) Connection termination.
The following diagram show a time line of the typical scenario that takes place for
connection oriented transfer, first the server is started, then client is started that connects
to the server.

103
SERVER

CLIENT

socket ()
socket ()
bind ()
bind ()
listen ()
connect ()
accept ()

read ()

write ()

write ()

read ()

Client connects to the server is 2 ways: 1) iterative server 2) concurrent server.


Iterative server: handles each client at a time (i.e) one client at a time.
Concurrent server: handles multiple clients at a time,we use fork() system call to create
a child process for each client .the parent runs the fork system call and creates a child
process and assigns each client to it .parent process waits for another connection from the
client .when 2 connection comes from the client another child is created and it is also
assigned a client.

104

Byte ordering functions:Consider a 16 bit integer that is made up of 2 bytes, we can store the 2 bytes in memory
in two types:
1) Lower order byte at the starting address known as little- endian byte order
2) Higher order byte at the starting address known as big-endian byte order.
Increasing memory
addresses

Little-endian byte order

High order byte

MSB
LSB

low order byte

16 bit value

Increasing memory
addresses

big-endian byte order

High order byte

low order byte

computer network are big endian ,this means that when little endian are going to pass
integers over network(IP address for example) they need to convert them to network byte
order .like wise when the receive integer values over the network they need to convert
them back to their own native representation.

#include<netinet/in.h>:d) uint16_t htons(uint16_t


e) uint32_t htonl(uint32_t

host16bitvalue);
host32bitvalue);
Both return: value in network byte order

3. uint16_t ntohs(uint16_t

net16bitvalues);

4. uint32_t ntohl(uint32_t

net32bitvalues);
Both return: value in host byte order

105

Byte manipulation functions:


#include< strring.h>
10. void bzero(void *dest , size_t nbytes); sets the specified number of bytes to 0
in destination(often used to initialize socket address structure to 0)
11. void bcopy(const void *src , void *dest ,size_t nbytes); moves the specified
number of bytes from source to the destination .
12. int bcmp(const void *ptr1 ,const void *ptr2 ,size_t nbytes); compares two
arbitrary byte strings are identical or not.

Address conversion function:-

they convert internet address between ASCII

strings (human understanding) and network byte binary values .


#include<arpa/inet.h>
18. int inet_aton(const char *strptr,struct in_addr *addrptr );
19. in_addr_t inet _addr(const char * strptr);
20. char *inet_ntoa(struct in_addr inaddr);
all the above convert an IPv4 address from a dotted decimal string(e.g:206.168.112.96) to its 32 bit network byte ordered binary value .

4. const char *inet_ntop(int family , const void *addrptr , char *strptr , size_t len);
Converts the numeric(addrptr) to presentation (strptr)

SOURCE CODE:
/* server program */
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<strings.h>
#include<netinet/in.h>
#define MAX 1024
main()
{

106
int sockfd,newsockfd, chilen,childpid,n;
char buff1[MAX];

/*sockaddr_in is predefined structure*/


struct sockaddr_in cli_addr, serv_addr;

/*creating a connection oriented server socket */

if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("server: cant open stream socket");
}
bzero((char *)&serv_addr,sizeof(serv_addr));
/*initializing the socket with family, port number, ipaddress*/
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr ("135.135.4.4");
serv_addr.sin_port=htons (7613);

/*Binding the structure to the server socket*/


if(bind(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr))<0)
{
perror("server:cant bind local address");
exit(1);
}

/*Listen to indicate that it is ready to receive connections*/


listen (sockfd,5);
for (;;)
{
chilen=sizeof(cli_addr);
printf("\n server is waiting for connection requests\n");

107
fflush(stdout);

/*accept takes the first connection request*/

newsockfd=accept(sockfd,(struct sockaddr *)&cli_addr,&chilen);

if(newsockfd<0)
{
perror("\n server accept error\n");
exit(1);
}
printf("\n connection established and communicating with client...");
fflush(stdout);

if((childpid=fork())<0)
{
perror("server: fork error\n");
exit(1);
}

if(childpid==0)
{
close(sockfd);
while(1)
{

/*reading a message from client*/

n=read (newsockfd, buff1, MAX);


buff1[n]='\0';
printf("\n server received from client is %s",buff1);

108
fflush(stdout);

/*sending a message to client */

write(newsockfd,buff1,strlen(buff1));
if(bcmp(buff1,"exit",4))
{
exit(0);
}
}
}
}
close(newsockfd);
}

OUTPUT:

Server:
$ cc tcpser.c
$ ./a.out
Server is waiting for connection requests.
Connection established and communicating with client..

Message received from client is Hello World.

Message sent to client is Hello World.

109
/* client side program*/
#include<sys/socket.h>
#include<sys/types.h>
#include<strings.h>
#include<stdio.h>
#include<netinet/in.h>

#define MAX 1024

main()
{
int sockfd,n;
char buff1[MAX],buff2[MAX];
/*sockaddr_in is predefined structure*/
struct sockaddr_in serv_addr;
bzero((char *)&serv_addr,sizeof(serv_addr));

/*Initializing the socket with family, port number, ipaddress*/

serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr ("135.135.4.4");
serv_addr.sin_port=htons (7613);
/*Creating a connection-oriented client socket*/

if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("client: socket error \n");
}
/*connect system call to establish a connection with a server*/

if(connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr))<0)

110
{
perror("client: cant connect to server\n");
exit(1);
}
printf("\n enter the message to be sent\n");
fflush(stdout);

/*Reading a message from Keyboard to buff1*/

if((n=read(0,buff1,MAX+1))<0)
{
perror("error in client ....\n");
exit(1);
}
buff1[n]='\0';
printf("\n message sent to the server: %s",buff1);

/*Sending a message to Server*/

if((n=write(sockfd,buff1,n))<0)
{
perror("error in client");
}
if((bcmp("exit",buff1,4))==0)
{
printf("\a\a client is exiting.....\n");
exit(1);
}

/*receiving a message from Server*/

111
if((n=read(sockfd,buff2,MAX))<0)
{
perror("error in client.........\n");
exit(1);
}
buff2[n]='\0';
printf("\n received from server \n");
fflush(stdout);
/*Displaying the message on monitor*/

if(write(1,buff2,n)<0)
{
perror("client: written by client on the screen\n");
}
/*Closing the socket*/
close(sockfd);
exit(0);
}
OUTPUT:

Client 1 :
$ cc- tcpcli1.c
$ ./a.out

Enter the message to be sent: Hello World


Message sent to the server: Hello World
Message received from the server: Hello World

Client 2 :
$ cc tcpcli2.c
$ ./a.out

112

Enter the message to be sent: Bye World


Message sent to the server: Bye World
Message received from the server: Bye World

113
12.2 AIM: Program for connection-oriented (TCP) service with server as iterative
server
REQUIREMENTS:
HARDWARE

: Pentium II (233 Hz)/32MB RAM /3.2 GB HDD

SOFTWARE

: Red Hat Linux server v.7.0,c

SOURCE CODE:
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
main()
{
int sockfd,newsockfd,n,len;
char buff[512];
/*sockaddr_in is predefined structure*/
struct sockaddr_in ser_addr,cli_addr;

/*Creating a connection-Oriented server socket*/


if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("socket error\n");
exit(1);
}
/*initializing the socket with family, port number, ipaddress*/
ser_addr.sin_family=AF_INET;
ser_addr.sin_port=htons(8810);
ser_addr.sin_addr.s_addr=htonl(INADDR_ANY);
/*Binding the structure to the server socket*/
if(bind(sockfd,(struct sockaddr*)&ser_addr,sizeof(ser_addr))<0)

114
{
perror("bind error");
exit(1);
}
/*Listen to indicate that it is ready to receive connections*/
listen(sockfd,5);
len=sizeof(cli_addr);
printf("server is waiting for connection ............................\n");
/*accept takes the first connection request*/
if((newsockfd=accept(sockfd,(struct sockaddr*)&cli_addr,&len))<0)
{
perror("accept error");
exit(1);
}
fflush(stdout);
//printf("IP addresss of client %s",inet_ntoa(cli_addr.sin_addr));
//printf("port no. of server is %d", ntohs(ser_addr.sin_port));
printf("server is connected to the client......\n");
fflush(stdout);
/*Reading a message from Client*/
n=read(newsockfd,buff,sizeof(buff));
printf("\n message received from the client :\t %s",buff);
fflush(stdout);
if(bcmp(buff,"exit",4)==0)
{
printf("\n server is closing the connection ..\n");
exit(1);
}
/*Sending a message to Client*/
write(newsockfd,buff,n);
/*Closing the socket*/

115
close(sockfd);
}

OUTPUT:
Server:
$ cc server.c
$ ./a.out
Server is waiting for connection.
IP address of Client 135.135.4.4
Port No of Server is 8033
Server is connected to the client.
Message received from the client: Hello World

/* client side program*/


#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
main()
{
int sockfd,n;
char buff1[512],buff2[512];
/*sockaddr_in is predefined structure*/
struct sockaddr_in serv_addr;
/*Creating a connection-Oriented client socket*/
if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("socket error\n");
exit(1);
}
/*Initializing the server socket with family, port number,ipaddress*/

116
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(8810);
serv_addr.sin_addr.s_addr=inet_addr ("135.135.4.4");;
/*connect system call to establish a connection with a server*/
if(connect(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr))<0)
{
perror("connect error");
exit(1);
}
printf("enter the message to be sent \n");
fflush(stdout);
printf("IP addresss of server is %s",inet_ntoa (serv_addr.sin_addr));
/*Reading a message from Keyboard to buff1*/
n=read(0,buff1,sizeof(buff1));
printf("\n message sent to the server :\t %s",buff1);
fflush(stdout);
/*Sending a message to Server*/
write(sockfd,buff1,n);
if(bcmp(buff1,"exit",4)==0)
{
printf("\n client is existing... .\n");
exit(1);
}
/*Receiving a message from Server*/
read(sockfd,buff2,n);
printf("message received from the server\n");
fflush(stdout);
/*Displaying the message on monitor*/
write(1,buff2,n);
/*Closing the socket*/
close(sockfd);

117
}
OUTPUT:
Client:
$ cc client.c
$ ./a.out
IP address of Server 135.135.4.4
Enter the message to be sent: Hello World
Message sent to the server: Hello World
Message received from the server: Hello World

118
12.3 AIM: Program for connection-less (UDP) service with server as iterative server
REQUIREMENTS:
HARDWARE

: Pentium II (233 Hz)/32MB RAM /3.2 GB HDD

SOFTWARE

: Red Hat Linux server v.7.0,c

THEORY:
In connection less service the client does not establish connection with the server. Instead
the client just sends a datagram to the server using sendto() function, similarly the server
does not accept connection from a client ,uses recvfrom() function which waits until data
arrives from some client.

UDP CLIENT

UDP SERVER

socket ()

bind ()
socket ()
recvfrom
sendto ()
Data(request)
Blocks until datagram received
From client

Process request

Data(reply)

recvfrom

close ()

sendto ()

119
1. ssize_t

sendto(int sockfd, const void *buff ,size_t nbytes,int flags, struct


sockaddr *from,socklen_t *addrelen);

2.ssize_t

recvfrom(int sockfd, void *buff ,size_t nbytes,int flags,


struct sockaddr *to, socklen_t *addrelen);

SOURCE CODE:
/* server side program*/

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#define MAX 1024
main()
{
int sockfd,n,len;
char buff[MAX];
/*sockaddr_in is predefined structure*/
struct sockaddr_in

serv_addr, cli_addr;

bzero ((struct sockaddr*)&serv_addr, sizeof(serv_addr));


/*Creating a connection-less server socket*/
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0)
{
perror("socket error");
exit(1);
}
/*Initializing the server socket with family, port number, ipaddress*/
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(8110);
serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);

120
/*Binding the structure to the server socket*/
if(bind(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr))<0)
{
perror("bind error");
exit(1);
}
len=sizeof(clie_addr);
/*Receiving a message from Client*/
n=recvfrom(sockfd,buff,MAX,0,(struct sockaddr* )&clie_addr,&len);
write(1,buff,n);
/*Sending a message to Client*/

sendto(sockfd,buff,n,0,(struct sockaddr*)&clie_addr,sizeof(clie_addr));
/*Closing the socket*/
close(sockfd);
}

OUTPUT:

Server:
$ cc server.c
$ ./a.out
Hello World

/* client side program*/

#include<sys/socket.h>
#include<sys/types.h>
#include<strings.h>
#include<stdio.h>
#include<netinet/in.h>

121
#include<arpa/inet.h>
main()
{
int sockfd, n, len ;
char buff1[512],buff2[512];
/*sockaddr_in is predefined structure*/
struct sockaddr_in serv_addr,cli_addr;
/* creating a connectionless server socket*/
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0)
{
perror("client: socket error\n");
}
/*Initializing the socket with server family, port number, ipaddress*/

serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr("135.135.4.4");
serv_addr.sin_port=htons(7641);
bzero((char *)&cli_addr,sizeof(cli_addr));

/*Initializing the socket with client family, port number, ipaddress*/


cli_addr.sin_addr.s_addr=inet_addr(135.135.4.4);
cli_addr.sin_port=htons(0);
/*Binding the structure to the client socket*/
bind(sockfd,(struct sockaddr *)&cli_addr,sizeof(cli_addr));

/*reading a message from Keyboard to buff1 */


n= read(0,buff1,sizeof(buff1));

/*sending message to server */


sendto (sockfd,buff1,n,0,(struct sockaddr *)&serv_addr,sizeof(serv_addr));
len = sizeof(serv_addr);

122
/*Receiving a message from Server*/
n = recvfrom (sockfd,buff2,sizeof(buff2),0,(struct sockaddr *)
&serv_addr, &len);
write(1,buff2,n);
}
/*Closing the socket*/
close(sockfd);
exit(0);
}

OUTPUT:

Client 1 :
$ cc udpcli.c
$ ./a.out
Client starts
Enter a message : Hello World

Client 2 :
$ ./cc udpcli2.c
$./a.out
Client starts
Enter a message : Bye World

123
12.4 AIM: Program for connection-Less (UDP) service with server as concurrent
server
REQUIREMENTS:
HARDWARE

: Pentium II (233 Hz)/32MB RAM /3.2 GB HDD

SOFTWARE

: Red Hat Linux server v.7.0,c

SOURCE CODE:
/* server side program*/
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
main()
{
int i,sockfd,newsockfd,pid,cli_addr_len,n;
char buff1[80];
/*sockaddr_in is predefined structure*/
struct sockaddr_in cli_addr,serv_addr;
/*Creating a concurrent connection-less socket*/
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0)
{
perror("server: cant open stream socket");
}
bzero((char *)&serv_addr,sizeof(serv_addr));
/*Initializing the server socket with family, port number, ipaddress*/
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);
serv_addr.sin_port=htons(7641);
/*Binding the structure to the server socket*/
if(bind(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr))<0)

124
{

perror("server:cant bind local address");


exit(1);
}
cli_addr_len=sizeof(cli_addr);
for(i=0;i<5;i++)
{
/*Receiving a message from Client*/
n=recvfrom(sockfd,buff1,80,0,(struct sockaddr *)&cli_addr, &cli_addr_len);
/*Create a child process*/
pid=fork();
if(pid= =0)
{
write(1,"server has received:",21,0);
write(1,buff1,n,0);
/*Sending a message to Client Socket*/
sendto(sockfd,buff1,n,0,(struct sockaddr *)&cli_addr, cli_addr_len);
exit(0);
}
}
/*Closing the socket*/
close(sockfd);
}
OUTPUT:
Server:
$ cc udpser.c
$ ./a.out
Server has received: hi
Server has received: hello

125
/* client side program*/
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
main()
{
int sockfd,n,serv_addr_len,cli_addr_len,i,num;
char buff1[80],buff2[80],a[ ]=135.135.4.4;
/*sockaddr_in is predefined structure*/
struct sockaddr_in serv_addr,cli_addr;
bzero((char *)&serv_addr,sizeof(serv_addr));
/*Initializing the server socket with family, port number ,ipaddress*/
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr(a);
serv_addr.sin_port=htons(7641);
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0)
{
perror("client: socket error\n");
}
bzero((char *)&cli_addr,sizeof(cli_addr));
/*Initializing the client socket with family, port number, ipaddress*/

cli_addr.sin_family=AF_INET;
cli_addr.sin_addr.s_addr=htonl(INADDR_ANY);
cli_addr.sin_port=htons(0);
/*Binding the structure to the server socket*/
bind(sockfd,(struct sockaddr *)&cli_addr,sizeof(cli_addr));
write(1,"client starts:",15);
for(i=0;i<5;i++)
{

126
write(1,"enter a message",16,0);
fflush(0);
n=read(0,buff1,80);
serv_addr_len=sizeof(serv_addr);
/*Sending a message to Server*/
sendto(sockfd,buff1,n,0,(struct sockaddr *)&serv_addr,serv_addr_len);
/*Receiving a message from Server*/
num=recvfrom(sockfd,buff2,80,0,(struct sockaddr *)&serv_addr,&serv_addr_len);
write(1,"client has received",20,0);
write(1,buff2,num);
}
/*Closing the socket*/
close(sockfd);
exit(0);
}
OUTPUT:
Client 1 :
$ cc udpcli.c
$ ./a.out
Client starts
Enter a message : Hi
Client 2 :
$ ./cc udpcli2.c
$./a.out
Client starts
Enter a message : welcome

127

13. Implementation of Time of the Day Service As Connection Oriented


Concurrent Server
AIM: Program for Time of the day service using connection-oriented (TCP) with server
as concurrent server
REQUIREMENTS:
HARDWARE

: Pentium II (233 Hz)/32MB RAM /3.2 GB HDD

SOFTWARE

: Red Hat Linux server v.7.0,c

SOURCE CODE:
/* server side program*/
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<time.h>
main()
{
unsigned long int t ;
int sockfd, newsockfd, len;
char *st,buff[512];
/*sockaddr_in is predefined structure*/
struct sockaddr_in serv_addr,cli_addr;
/*Creating a connection-Oriented client socket*/
if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("socket error\n");
exit(1);
}
/*Initializing the server socket with family, port number, ipaddress*/
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(8810);

128
serv_addr.sin_addr.s_addr=inet_addr("135.135.4.4");

/*Initializing the server socket with family, port number, ipaddress*/


bind(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr));
/* listen indicate that it is ready to receive connections*/
listen(sockfd,5);
len = sizeof(cli_addr);
/*accept takes the first connection request*/
newsockfd = accept(sockfd,(struct sockaddr *)&cli_addr, & len);
/*gets the current system time*/
Time(&t);
st =(char*) ctime (&t);
strcpy (buff, st);
write(newsockfd,buff,strlen(buff));

/*Closing the socket*/


close(sockfd);
}

OUTPUT:
Time: the time function returns number of seconds elapsed since the official birthday of
UNIX or Linux server: JANUARY 1st 1970.
C Time: the C time function returns local date and time in the following format Tue
Feb.21 10:05:50 2006 \n.

/*Connection-Oriented (TCP) Time of the Day Client */


#include<stdio.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>

129
#include<netinet/in.h>
main()
{
char buff[512];
int n,i,sockfd,newsockfd;

/*sockaddr_in is predefined structure*/


struct sockaddr_in serv_addr;
/*sockaddr_in is predefined structure*/
if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("socket error");
exit(1);
}
/*Initializing the socket with family, port number, ipaddress*/
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(8963);
serv_addr.sin_addr.s_addr=inet_addr("135.135.4.4");
/*connect system call to establish a connection with a server*/
connect (sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
n=read(sockfd,buff,sizeof(buff));
write(1,buff,n);
}

OUTPUT:
$ cc client1.c
$ ./a.out
sat dec 29 17:53:42 2012
$ cc client2.c
$ ./a.out
sat dec 29 17:54:23 2012

130

14. Build a concurrent Multithreaded File Transfer server. Use


separate Threads to allow the server to handle multiple clients
concurrently.
AIM: Program for concurrent multithreaded file transfer server.
REQUIREMENTS:
HARDWARE

: Pentium II (233 Hz)/32MB RAM /3.2 GB HDD

SOFTWARE

: Red Hat Linux server v.7.0,c

FTPServer.c
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<string.h>
#include<netinet/in.h>
#include<fcntl.h>
#define MAX 2048
main()
{
int sockfd,newsockfd,chilen,childpid,n,fd1,fd2;
char filename[1024],buff2[MAX],option[4];
struct sockaddr_in ser_addr,cli_addr;
if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("solcket error");
exit(1);
}
ser_addr.sin_family=AF_INET;
ser_addr.sin_port=htons(8122);
ser_addr.sin_addr.s_addr=inet_addr("135.135.4.4");
if(bind(sockfd,(struct sockaddr *)&ser_addr,sizeof(ser_addr))<0)
{
perror("Bind error: ");
exit(1);
}
listen(sockfd,5);
for( ; ;)

131
{
chilen=sizeof(cli_addr);
if((newsockfd=accept(sockfd,(struct sockaddr *)&cli_addr,&chilen))<0)
{
perror("accept error");
exit(1);
}
if((childpid=fork())<0)
{
perror("server:fork error");
exit(1);
}
if(childpid==0)
{
close(sockfd);
while(1)
{
n=read(newsockfd,option,3);
option[n]='\0';
if(bcmp(option,"get",3)==0) {

n=read(newsockfd,filename,sizeof(filename));
filename[n]='\0';
fd1 = open(filename,0);
n=read(fd1,buff2,MAX);
buff2[n]='\0';
write(newsockfd,buff2,strlen(buff2));
close(fd1);
}
else if(bcmp(option,"put",3)==0){
n=read(newsockfd,filename,sizeof(filename));
write(1,filename,strlen(filename));
creat(filename,S_IRWXU);
fd2=open(filename,O_WRONLY);
n=read(newsockfd,buff2,sizeof(buff2));
write(fd2,buff2,strlen(buff2));
close(fd2);
}

132
else
break;
}
}
}
close(sockfd);
}
FTPClient.c
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<string.h>
#include<netinet/in.h>
#include<fcntl.h>
#define MAX 2048
main(int argc, char* argv[])
{
int sockfd,n,ch,fd1,fd2;
char filename[1024],buff2[MAX];
struct sockaddr_in ser_addr,cli_addr;
if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("solcket error");
exit(1);
}
ser_addr.sin_family=AF_INET;
ser_addr.sin_port=htons(8122);
ser_addr.sin_addr.s_addr=inet_addr("135.135.4.4");
if(connect(sockfd,(struct sockaddr *)&ser_addr,sizeof(ser_addr))<0)
{
perror("connect error");
exit(1);
}
while(1){
printf("MENU\n1. GET\n2. PUT\n3. EXIT\nEnter your choice:");
fflush(stdout);
scanf("%d",&ch);
switch(ch){
case 1:

133
write(sockfd,"get",3);
write(1,"Enter File name: ",17);
n=read(0,filename,15);
filename[n-1]='\0';
write(sockfd,filename,strlen(filename));
creat(filename,S_IRWXU);
fd1=open(filename,O_WRONLY);
read(sockfd,buff2,MAX);
write(fd1,buff2,strlen(buff2));
close(fd1);
break;
case 2:
write(sockfd,"put",3);
write(1,"Enter File name: ",17);
n=read(0,filename,15);
filename[n-1]='\0';
write(sockfd,filename,strlen(filename));
fflush(stdout);
fd2=open(filename,0);
read(fd2,buff2,MAX);
write(sockfd,buff2,strlen(buff2));
close(fd2);
break;
case 3: exit(1);
}}
close(sockfd);
exit(0);
}

Output:

134

135

15. Implementation of Remote Program execution using socket system


calls. Programs to demonstrate the usage of Advanced

Socket

System calls like Getsockopt(), Setsockopt(), Select(),Readv(),


getpeername(), Getsockname().
15.1 AIM: Advance socket system calls: program for readv () and writev ()
REQUIREMENTS:
HARDWARE

: Pentium II (233 Hz)/32MB RAM /3.2 GB HDD

SOFTWARE

: Red Hat Linux server v.7.0,c

THEORY:
The readv () function reads count blocks from the file associated with the file descriptor
fields into the multiple buffers described by vector.

The writev () function writes at most count blocks described by vector to the file
associated with the file descriptor fields

The pointer vector points to a struct iovec defined in <sys/uio.h> as follows:

struct iovec {
void *iov_base; /* starting base address*/
size_t iov_len;

/* number of bytes*/

};

Buffers are processed in the order vector[0], vector[1],..vector[count].


int readv (int fd ,struct iovec iov[] , int iovcount);

int writev (int fd ,struct iovec iov[] , int iovcount);

136
SOURCE CODE:
/*server side program */
#include<stdio.h>
#include<sys/socket.h>
#include<errno.h>
#include<netinet/in.h>
#include<string.h>
#include<stdlib.h>
#include<sys/uio.h>

short myport;
main(int argc , char *argv[ ])
{
int sockfd , newfd ,nbyte;
struct sockaddr_in myaddr;
struct iovec i [3];
char buff[512] , buff1[7], buff2[6], buff3[7];
/* set up the base address*/
i[0].iovec_base=buff1;
i[0].iovec_len =7;
i[0].iovec_base=buff2;
i[0].iovec_len =6;
i[0].iovec_base=buff3;
i[0].iovec_len =7;
if(argc != 2)
{
perror(INVALID NO OF ARGS);
exit(1);
}
if ((sockfd = socket(AF_INET,SOCK_STREAM,0)) = = -1)
{

137
perror(UNABLE TO CREATE SOCKET);
exit(1);
}
myport = atoi(argv[1]);
myaddr.sin_family = AF_INET;
myaddr.sin_addr.s_addr = INADDR_ANY
myaddr.sin_port=htons(myport);
bzero(&(myaddr.sin_zero),8);
if((bind(sockfd,(struct sockaddr*)& myaddr, sizeof(myaddr))) = = -1)
{
perror(BIND ERROR);
exit(1);
}
if(listen (sockfd , 0) = = -1)
{
perror(listen error);
exit(1);
}
for(;;)
{
if((newfd = accept(sockfd , 0 , 0)) = = -1)
{
perror(accept error);
exit(1);
if((nbyte = readv(newfd , i ,3))<0)
{
perror(read error);
exit(1);
}
if(writev (newfd , i , 3))<0)
{

138
perror(write error);
exit(1);
}
}
}
OUTPUT:
$ cc server.c
$./a.out Any port no
e.g:- ./a.out 8180

/*client side program */


#include<stdio.h>
#include<sys/socket.h>
#include<errno.h>
#include<netinet/in.h>
#include<string.h>
#include<stdlib.h>
#include<sys/uio.h>
short destport;
main(int argc , char *argv[ ])
{
int sockfd , n ,bytes ,nb;
struct sockaddr_in servaddr;
struct iovec i [3], j[3];
char buff[512] = ENTER THE TEXT, buff1[7], buff2[6], buff3[7], buff4[7], buff5[6],
buff6[7];

i[0].iovec_base=buff1;
i[0].iovec_len =7;
i[0].iovec_base=buff2;
i[0].iovec_len =6;

139
i[0].iovec_base=buff3;
i[0].iovec_len =7;
i[0].iovec_base=buff4;
i[0].iovec_len =7;
i[0].iovec_base=buff5;
i[0].iovec_len =7;
i[0].iovec_base=buff6;
i[0].iovec_len =7;
if(argc != 3)
{
perror(INVALID ARGS);
if ((sockfd = socket(AF_INET,SOCK_STREAM,0)) = = -1)
{
perror(UNABLE TO CREATE SOCKET);
exit(1);
}
destport = atoi(argv[1]);
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(argv[2]);
servaddr.sin_port=htons(destport);
bzero(&(servaddr.sin_zero),8);
if((connect (sockfd,(struct sockaddr*)&servaddr, sizeof(serv_addr))) = = -1)
{
perror(CONNECT ERROR);
exit(1);
}
write(1,buff,sizeof(buff));
read(0,buff1,sizeof(buff1));
write(1,buff,sizeof(buff));
read(0,buff1,sizeof(buff2));
write(1,buff,sizeof(buff));

140
read(0,buff1,sizeof(buff3));
if((writev (sockfd, i ,3 ))<0)
{
perror(WRITE ERROR);
exit(1);
}
if((readv (sockfd , j, 3)) <0)
{
perror( READ ERROR);
exit(1);
}
write(1, buff4 , sizeof(buff4));
write(1, buff5 , sizeof(buff5));
write(1, buff6 , sizeof(buff6));
return 0;
}

OUTPUT:
$ cc client.c
$./a.out Any port no (same as in the server program) ipaddress of server
e.g:- ./a.out 8180 135.135.4.4
Enter the message to be sent to the server:
Enter the text
Hi
Enter the text
Hello
Enter the text
Welcome
Same message returns from the server.

141
15.2 AIM: Advance socket system calls: program for select ()
REQUIREMENTS:
HARDWARE

: Pentium II (233 Hz)/32MB RAM /3.2 GB HDD

SOFTWARE

: Red Hat Linux server v.7.0,c

THEORY:
#include<sys/types.h>
#include<sys/time.h>
int select (int maxfdpl , fd_set *readfds , fd_set *writefds , fd_set *exceptfds , struct
timeval *timeout);
FD_ZERO (fd_set *fdset) ;

//clear all the bits in fdset

FD_SET (int fd , fd_set *fdset) ;

//turn the bit for fd on in fdset

FD_CLR (int fd , fd_set *fdset) ;

//turn the bit for fd off in fdset

FD_ISSET (int fd , fd_set *fdset) ;

//test the bit for fd in fdset

The structure pointed to by the timeout argument is defined in <sys/time.h> as


struct timeval{
long tv_sec;

//seconds

long tv_usec;

// micro seconds

};

Ex:- 1. FD_ZERO(&fdvar);
2. FD_SET(1, &fdvar);

SOURCE CODE:
#include<stdio.h>
#include<sys/time.h>
#include<sys/types.h>
#include<unistd.h>
int main(void)
{

// initialize the set-all bits off


//turn on bit for fd 1

142
fd_set rfds;
struct timeval tv;
int retval;
/*watch stdin (fd 0) to see when it has input*/
FD_ZERO(&rfds);
FD_SET(0,&rfds);
/*wait up to five seconds*/
tv.tv_sec=5;
tv.tv_usec=0;
retval=select(l, &rfds, NULL, NULL, &tv);
/*Dont rely on the value of tv now!*/
if(retval==-1)
perror(select( ));
else if(retval>( ))
printf(Data is available now.\n);
/*FD ISSET(0,&rfds)will be true*/
else
printf(No data within five seconds\n);
return 0;
}

OUTPUT:
$ cc sel.c
$./a.out aaa
Data available now

143
15.3 AIM: Advance socket system calls: program for getsockname ()
REQUIREMENTS:
HARDWARE

: Pentium II (233 Hz)/32MB RAM /3.2 GB HDD

SOFTWARE

: Red Hat Linux server v.7.0,c

THEORY:
Getsockname get the socket name , included in sys/socket.h file
int

getsockname (int

socket , struct sockaddr

*address , socklen _t

*address_len);
The getsockname () function retrieves the locally bound name of the specified socket
,stores address in the sockaddr structure pointed to by the address argument and stores
the length of this address in the object pointed to by the address_len argument.

If the actual length of the address is greater than the length of the supplied sockaddr
structure, the stored address will be truncated.

If the socket has not been bound to a local name the value stored in the object pointed to
by address is unspecified. upon successful completion ,0 is returned the address argument
points to the address of the socket and the address_len argument points to the length of
the address.otherwise,-1 is returned and errno is set to indicate the error.
SOURCE CODE:
/* server side program*/
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<stdio.h>
int main()
{
int server_sockfd , client_sockfd ;

144
int server_len , client_len;
struct sockaddr_in server_address , client_address;

server_sockfd = socket (AF_INET , SOCK_STREAM , 0);

server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr(135.135.4.4);
server_address.sin_port=7991;

server_len = sizeof ( server_address);

bind(server_sockfd , (struct sockaddr*)&server_address , server_len);

if((getsockname ( server_sockfd, (struct sockaddr*)&server_address, ,&server_len))<0)


printf(error);

printf(\n socket has port %d \n, ntohs(server_address.sin_port));

listen (server_sockfd , 5 );
while(1)
{
char ch;
printf(server is waiting \n);
client_len = sizeof(client_address);
client_sockfd =accept( server_sockfd , (struct sockaddr*)&client_address, &client_len);
printf(\n %s \n,inet_ntoa(client_address.sin_addr));
printf(\n %u \n, client_address.sin_port);
read(client_sockfd, &ch , 1);
prinf( I AM THE SERVER PROGRAM just received a character from the client..it is %c \n,
ch);

145
printf( I AM THE SERVER PROGRAM I am giving back the same character back to the
client.\n\n\n);
write(client_sockfd , &ch , 1);
close(client_sockfd);
}
}

OUTPUT:

I AM SERVER PROGRAM just received a character from the client. it is A.

I AM SERVER PROGRAM I am giving back the same character back to the client.

/* client side program*/


#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<stdio.h>
int main()
{
int sockfd , len , na;
char str[80];
struct sockaddr_in address , name;
int result;
char sent = A;
char received;

sockfd = socket (AF_INET ,SOCK_STREAM , 0);

146
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(135.135.4.4);
address.sin_port=7991;

len = sizeof(address);

result = connect(sockfd , (struct sockaddr*)&address , len);


if(result = = -1)
{
perror(client);
exit(1);
}
na = sizeof(name);
printf( \n output of connect system call is %d \n\n , result);
write(sockfd, &sent , 1);
read(sockfd , ,&received , 1);
printf(char from server = %c \n, received);

getpeername(sockfd,(struct sockaddr*)&name , &na);


inet_ntop(AF_INET, &name.sin_addr.s_addr, str, sizeof(str));
printf( the port is %d \n, htons(name.sin_port));
printf( the peername is %s \n,str);
close(sockfd);
exit(0);
}

OUTPUT:

Char form server A


The port no is 7991
The peername is 135.135.4.4

147

15.4 AIM: Advance socket system calls: program for getpeername ()


REQUIREMENTS:
HARDWARE

: Pentium II (233 Hz)/32MB RAM /3.2 GB HDD

SOFTWARE

: Red Hat Linux server v.7.0,c

THEORY:
This function will tell you who is at all other end of a connected stream socket. this is
define din #include<sys/socket.h>.
int gerpeername ( int sockfd , struct sockaddr *addr, int * addrlen);

SOURCE CODE:
/* server side program*/
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<stdio.h>
int main()
{
int server_sockfd , client_sockfd ;
int server_len , client_len;
struct sockaddr_in server_address , client_address;
server_sockfd = socket (AF_INET , SOCK_STREAM , 0);
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr(135.135.4.4);
server_address.sin_port=7058;

server_len = sizeof ( server_address);

148
bind(server_sockfd , (struct sockaddr*)&server_address , server_len);
listen (server_sockfd , 5 );
while(1)
{
char ch;
printf(server is waiting \n);
client_len = sizeof(client_address);
client_sockfd =accept( server_sockfd , (struct sockaddr*)&client_address, &client_len);
read(client_sockfd, &ch , 1);
prinf( I AM THE SERVER PROGRAM just received a character from the client..it is
%c \n, ch);
printf( I AM THE SERVER PROGRAM I am giving back the same character back to
the client.\n\n\n);
write(client_sockfd , &ch , 1);
close(client_sockfd);
}
}

OUTPUT:
Server is waiting
I AM SERVER PROGRAM just received a character from the client. it is A.

I AM SERVER PROGRAM I am giving back the same character back to the client

. /* client side program*/


#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>

149
int main()
{
int sockfd , len , na;
char str[80];
struct sockaddr_in address , name;
int result;
char sent = A;
char received;

sockfd = socket (AF_INET ,SOCK_STREAM , 0);

address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(135.135.4.4);
address.sin_port=7058;

len = sizeof(address);

result = connect(sockfd , (struct sockaddr*)&address , len);


if(result = = -1)
{
perror(client);
exit(1);
}
na = sizeof(name);
printf( \n output of connect system call is %d \n\n , result);
write(sockfd, &sent , 1);
read(sockfd , ,&received , 1);
printf(char from server = %c \n, received);

getpeername(sockfd,(struct sockaddr*)&name , &na);


inet_ntop(AF_INET, &name.sin_addr.s_addr, str, sizeof(str));

150
printf( the port is %d \n, htons(name.sin_port));
printf( the peername is %s \n,str);
close(sockfd);
exit(0);
}

OUTPUT:

Char form server A


The port no is 7991
The peername is 135.135.4.4

15.5 AIM: Advance socket system calls: program for setsockopt (), getsockopt ()
REQUIREMENTS:
HARDWARE

: Pentium II (233 Hz)/32MB RAM /3.2 GB HDD

SOFTWARE

: Red Hat Linux server v.7.0,c

THEORY:
c)

int getsockopt ( int s , int level , int optname , void *optval , socklen_t
*optlen);

d)

int setsockopt ( int s , int level ,int optname , const void *optval , socklen_t
optlen);

getsockpot and setsockopt manipulate the options associated with a socket.options may
exit at multiple protocol levels; they are always present at the uppermost socket level.
When manipulating socket options the level at which the options reside and the name of
the options must be specified .to manipulate the options at the socket level, level is
specified as SOL_SOCKET. To manipulate at any other level the protocol number of the
appropriate protocol controlling the options is supplied. for example ,to indicate that an
option is to be interpreted by the TCP protocol ,level should be set to the protocol number
of TCP: see getprotoent(3).

151

The parameters optval and optlen are used to access option values for setsockopt. For
getsockopt they identify a buffer the value for the requested options(s) are to be returned.
For getsockopt ,optlen is a value result parameter ,initially containing the size of the
buffer pointed to by optval and modified on return to indicate the actual size of the value
returned .if no option value is to be supplied or returned ,optval may be NULL.

optname and any specified options are passed interpreted to the appropriate protocol
module for interpretation. The include file <sys/socket.h> contains definitions for socket
level options.

Most socket level options unitize an int parameter for optval.for setsockpot, the parameter
should be non zero to enable a Boolean option,or zero if the option is to be disabled .
For a description of the available socket options see socket(7) and the appropriate
protocol man pages.

Return value: on success zero is returned. on error,-1 is returned and errno is set
appropriately.

SOURCE CODE:
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/uio.h>
#include<netinet/tcp.h>
main()
{
int sfd,cl,sendbuff,maxseg;
sfd=socket(AF_INET,SOCK_STREAM,0);
if(sfd<0)

152
{
perror(Socket error);
exit(1);
}
cl=sizeof(maxseg);
if(getsockopt(sfd, IPPROTO_TCP,TCP_MAXSEG,(char *)&maxseg, &cl)<0)
{
perror("getsockopt error");
exit(1);
}
printf("TCP maxseg=%d\n",maxseg);
sendbuff=1045;

if(setsockopt(sfd,SOL_SOCKET,SO_SNDBUF,(char*)&sendbuff,sizeof(sendbuff))<0)
{
perror("setsockopt error");
exit(1);
}
cl=sizeof(sendbuff);
if(getsockopt(sfd,SOL_SOCKET,SO_SNDBUF,(char *)&sendbuff,&cl)<0)
{
perror("getsockopt error");
exit(1);
}
printf("send buffer size=%d\n",sendbuff);
}
OUTPUT:
$ cc sockopt.c
$ ./a.out
TCP maxseg=536
send buffer size=2090

153
15.6 AIM: Program using Remote Procedure Call (RPC)
REQUIREMENTS:
HARDWARE

: Pentium II (233 Hz)/32MB RAM /3.2 GB HDD

SOFTWARE

: Red Hat Linux server v.7.0,c

THEORY:
RPC is to call the process which resides in another machine, the process do no share the
address space, the called remote procedure executes within the environment of the server
process.

Sun micro system specific form of RPC SUNRPC has wide acceptance and many
applications like NFS. Defines the format of messages and arguments. The protocol used
is TCP (or) UDP.

Data representation is done in the form of XDR. Uses structures instead of multiple
arguments. At most one remote procedure in a remote program can be invoked at a give
time automatic mutual exclusion.

A compiler tool helps programmers to build distributed programs automatically


RPCGEN.

The application programmer writes the interface definition file and generates the stubs
using rpcgen. The application programmer manually writes the client program and the
server program for the application. The client program is compiled to get client object
file, server program file is compiled to get the server object file. Client stub file and the
XDR filters are compiled to get client stub object file. Server stub file and the XDR
filters are compiled to get server stub object file.

Client object file, client stub object file and client side runtime library are linked together
to get the clients executable file.

154
Server object file, server stub object file and client side runtime library are linked
together to get the servers executable file.
e.g:- program SAMPLE_PROG {
Version SAMPLE_VERS {
Long SAMPLE_FN (long amt) = 1;
} =1;
} = 0x31234567;

Procedure identification:
Each procedure is identified by: hostname (IP address), program identifier (32 bit
integer), procedure identifier (32 bit integer), and program version identifier.

Program identifier; each remote program has a unique ID, SUN divided up the IDs:
0x00000000 - 0x1fffffff
0x20000000- 0x3fffffff

sun sys admin transient reserved

0x40000000- 0x5fffffff
0x60000000-0xffffffff

Procedure identifier and program version identifier:


Procedure identifiers usually start at 1 and are numbered sequentially. Version numbers
typically start at 1 and are numbered sequentially.
The input to rpcgen is the protocol definition (.X file) in the form of remote procedures
and parameter types.

155
RPCGEN

Input file

rpcgen

Client stubs

XDR filters

Header file

Server skeleton

SOURCE CODE:
RPC program to find server time and date
/* date.x*/

Program dateprg
{
Version datever
{
String date (void) = 1;
} =1;
} = 0x9876544;

/* procedure number = 1*/


/* version number = 1 */
/* program number = 0x9876544 */
/*Server.c*/

#includedate.h
#include<time.h>

156
Char **date_1_svc(void *argp,struct svc_req *rqstp)
{
static char *result;
char msg[500];
time_tt = time(NULL);
// is used to convert result into a text string
snprintf(msg , 500 , %s, ctime(&t));
/* formatted output conversion*/
result = msg;
return &result;
}

/* client.c*/

#include date.h

Void dateprg_1(char *host)


{
CLIENT *clnt;
Char **result_1;
/* create the client handle*/
clnt = clnt_create(host , dateprg , datever , UDP);

if(clnt = = NULL)
{
clnt_pcreateerror(host);
exit(1);
}

157
result_1 = date_1(NULL, clnt);

if (result_1 = (char**) NULL)


{
clnt_perror(clnt , call failed);
}
Printf(\n the message is %s , *result_1);
}

int main(int argc,char *argv[])


{
char *host;
if(argc<2)
{
printf(usage %s server_host \n, argv[0]);
exit(1);
}
host = argv[1];
dateprg_1(host);
exit(0);
}

Steps to execute RPC program:


d) write your own RPC specification file date.x
$ ls
Client.c server.c date.x
e) use RPC gen to generate the files you need(i.e date.h , date_svc, and date_clnt.c
$ rpgen date.x
$ls
Client.c date_clnt.c date.h date_svc.c date.x server.c

158

f) Use cc to compile your server program


$ cc date_clnt.c date_svc.c server.c lrpcsvc o s
g) Use cc to compile your client program
$ cc date_clnt.c client.c lrpcsvc o c
h) Run your server program
$./ s
or put server to run in the background
$ ./s&
i) Run your client program
$./c <ipaddress>
$./c 135.135.4.4

OUTPUT:
The message is sat dec 29 17:53:42 2012

15.7 AIM: Advance socket system calls: program for gethostname ()


REQUIREMENTS:
HARDWARE

: Pentium II (233 Hz)/32MB RAM /3.2 GB HDD

SOFTWARE

: Red Hat Linux server v.7.0,c

THEORY:
gethostname ()-------------- who am I?
defined in #include<unistd.h> .
int gethostname( char *hostname , size_t size);

hostname is a pointer to an array pf chars that will contain the hostname upon function
return and size is the length in bytes of the hostname array.
Hostent:

159
The hostent structure is used by function to store information about a given host, such as
host name ipaddress and so forth. An application should never attempt to modify this
structure or to free any of its components .furthermore ,only one copy of the hostent
structure is allocated per thread, and an application should therefore copy any
information that it needs before issuing any other windows sockets API calls.

typedef struct hostent{


char FAR *h_name;
char FAR FAR **h_aliases;
short h_addrtype;
short h_lenght;
char FAR FAR **h_addr_list;
}hostent;

Members:
h_name : official name of the host(PC) .if using the DNS or similar resolution system, it
is fully qualification domain name(FQDN) that caused the server to return a reply .if
using a local hosts file,it is the first entry after the IP address.
h_aliases: null terminated array of alternate names.
h_length: length of each address, in bytes.
h_addr_list: null terminated list of address for the host . addresses are returned in the
network byte order. The macro h_addr is defined to be h_addr_list[0[ for compatibility
with older software.

SOURCE CODE:
/*gethostname*/
#include<sys/socket.h>
#include<stdlib.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdio.h>

160
int main( void )
{
Char host_name[50] = {0};
int ccode;
if((ccode = gethostname(host_name, sizeof ( host_name)))! = 0)
{
Printf(get host name failed ccode = %d \n, ccode);
Return EXIT_FAILURE;
}
Printf(host name &s \n,host_name);
Return EXIT_SUCCESS;
}

OUTPUT:
$ cc hst.c
$ ./a.out host name : linuxstuserver.

/* gethostbyname*/
#include<sys/socket.h>
#include<stdlib.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdio.h>
#include<errno.h>
#include<netdb.h>
#include<sys/types.h>

int main( int argc , char *argv[] )


{
struct hostent *h;

161
if (argc!= 2) // error check the command line
{
fprintf(stderr, usage: getip address \n);
exit(1);
}
if((h = gethostbyname(argv[1] = = NULL)
{
herror(gethostbyname);
exit(1);
}
printf(Host name : %s \n , h -> name);
printf(IP address : %s \n, inet_ntoa(*((struct in_addr*) h->addr)));
return 0;
}
OUTPUT:
$ cc hstby.c
$ ./a.out linux stuserver
Host name: linux stuserver
IP address: 127.0.0.1

15.8 AIM: Program using Remote Procedure Call (RPC)


REQUIREMENTS:
HARDWARE

: Pentium II (233 Hz)/32MB RAM /3.2 GB HDD

SOFTWARE

: Red Hat Linux server v.7.0,c

SOURCE CODE:
/* sample.x*/
Program SAM_PROG
{
Version SAM_VERS
{

162
long SAM_FN(long amt) = 1
} =1;
} = 0x31234567;

/*sample_Server.c*/
#include sam.h

long *sam_fn_1_svc(void *argp, struct svc_req *rqstp)


{
static long result;
/* insert server code here*/
result = *result +1;
return &result;
}
/*sample_client.c*/
#include sam.h
Void sam_prog_1(char *host , long n)
{
CLIENT *clnt;
long *result_1;
long sam_fn_1_arg = n;
#ifndef DEBUG
clnt = clnt_create ( host , SAM_PROG , SAM_VERS , udp);
if(clnt = = NULL){
clnt _pcreateerror(host);
exit(1);
}
#endif /*DEBUG*/
result_1 = sam_fn_1(&sam_fn_1_arg , clnt);
if(result_1 = = (long *)NULL) {
clnt_perror(clnt , call failed);

163
}
Printf(result &ld, *result_1);
#ifndef DEBUG
Clnt_destory(clnt);
#ebdif /*DEBUG*/
}
int main( int argc , char *argv[ ])
{
char *host;
if(argc<3){
printf(Usage :%s server_host number \n,argv[0]);
exit(1);
}
host = argv[1];
sam_prog_1(host , atoll(argv[2]);
exit(0);
}

Steps to execute RPC program:


1. Write your own RPC specification file sample.x
$ ls
Client.c server.c date.x
2. Use RPC gen to generate the files you need (i.e sample.h , sample_svc.c, and
sample_clnt.c
$ rpgen sample.x
3. Use rpcgen to generate sample server program
$ rpcgen Ss sample.x >sample_server.c
4. Use rpcgen to generate sample client program
$ rpcgen Sc sample.x >sample_client.c
5. Use cc to compile your server program (sample_server.c)
$ cc o sample_server sample_server.c sample_svc.c - lnsl

164
6. Use cc to compile your client program (sample_client.c)
$ cc o sample_client sample_client.c sample_clnt.c - lnsl
j)

Run your server program


$./ sample_server
or put server to run in the background
$ ./sample_server&

k) Run your client program


$./sample_client <ipaddress> <amount>

15.9 AIM: Program using Remote Procedure Call (RPC) (GCD)


REQUIREMENTS:
HARDWARE

: Pentium II (233 Hz)/32MB RAM /3.2 GB HDD

SOFTWARE

: Red Hat Linux server v.7.0,c

SOURCE CODE:
/* gcd.x*/
struct num
{

long a;
long b;

};
program gcd_prog
{
version gcd_vers
{
long gcd_fn(num) = 1
} =1;
} = 0x30000001;

/*gcd_Server.c*/
#include gcd.h
int gcd(int a ,int b)
{

165
if(b= = 0)
return a;
return gcd(b,a % b)
}
long *gcd_fn_1_svc(num *argp, struct svc_req *rqstp)
{
static long result;

/* insert server code here*/


result = gcd((*argp).a , (*argp).b);
return &result;
}
/*gcd_client.c*/
#include gcd.h
Void gcd_prog_1(char *host , num number)
{
CLIENT *clnt;
long *result_1;
num gcd_fn_1_arg ;
gcd_fn_1_arg.a = number.a;
gcd_fn_1_arg.b = number.b ;
#ifndef DEBUG
clnt = clnt_create ( host , GCD_PROG , GCD_VERS , udp);
if(clnt = = NULL){
clnt _pcreateerror(host);
exit(1);
}
#endif /*DEBUG*/
result_1 = gcd_fn_1(&gcd_fn_1_arg , clnt);
if(result_1 = = (long *)NULL) {

166
clnt_perror(clnt , call failed);
}
Printf(gcd is %d, *result_1);
#ifndef DEBUG
clnt_destory(clnt);
#ebdif /*DEBUG*/
}
int main( int argc , char *argv[ ])
{
char *host;
num n;
if(argc<4){
printf(Usage :%s server_host num1 num2 \n,argv[0]);
exit(1);
}
n.a =atoll( argv[2]);
n.b =atoll( argv[3]);
host = argv[1];
gcd_prog_1(host , n);
exit(0);
}
Steps to execute RPC program:
1. Write your own RPC specification file gcd.x
$ ls
Client.c server.c date.x
2. Use RPC gen to generate the files you need (i.e gcd.h , gcd_svc.c,gcd_xdr.c and
gcd_clnt.c
$ rpgen gcd.x
3. Use rpcgen to generate sample server program
$ rpcgen Ss gcd.x >gcd_server.c
4. Use rpcgen to generate sample client program

167
$ rpcgen Sc gcd.x >gcd_client.c
5. Use cc to compile your server program (gcd_server.c)
$ cc o gcd_server gcd_server.c gcd_svc.c gcd.xdr.c - lnsl
6. Use cc to compile your client program (sample_client.c)
$ cc o gcd_client gcd_client.c gcd_clnt.c gcd_xdr.c - lnsl
l)

Run your server program


$./ gcd_server
or put server to run in the background
$ ./gcd_server&

m) Run your client program


$./gcd_client <ipaddress> <number1 > <number 2>

168

16. Implement A Concurrent Chart Server That Allows Currently


Logged In Users To Communicate With One Another
AIM: Program for concurrent chart server with multiple users communicating with each
other
REQUIREMENTS:
HARDWARE

: Pentium II (233 Hz)/32MB RAM /3.2 GB HDD

SOFTWARE

: Red Hat Linux server v.7.0,c

SOURCE CODE:
/* server side program*/
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>
#include<errno.h>
#include<stdlib.h>
short myport;
main(int argc,char *argv[])
{
int sockfd , newfd , nbyte , n , p;
struct sockaddr_in myaddr , claddr;
char buff[512] , buff1[512];
if(argc!=2)
{
perror(invalid no of arguments);
exit(1);
}
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))= = -1)
{
perror(unable to create socket );
exit (1);

169
}
myport=atoi(argv[1]);
myaddr.sin_family=AF_INET;
myaddr.sin_port=htons(myport);
myaddr.sin_addr.s_addr=INADDR_ANY;
bzero(&(myaddr.sin_zero),8);
if((bind(sockfd,(struct sockaddr *)&myaddr,sizeof(myaddr)))== -1)
{
perror(bind error);
exit(1);
}
write(1,\n waiting for Client,sizeof(\n Wait for Client));
newfd=sizeof(claddr);
if((n=recvfrom(sockfd,buff1,sizeof(uff1),0,(struct sockaddr *)&claddr,&newfd)))==-1)
{
perror(RECEIVE ERROR);
exit(1);
}
printf(\n CLIENT CONNECTED..);
write(1,\n Client : ,10) ;
write(1,buff1,n);
// for(;;)
if(p=fork())<0)
{
perror(CHILD CANNOT BE CREATED.);
exit(1);
}
if(p<0)
{
for(;;)
{

170
write(1,\n Server : ,10);
n=read(0,buff,512);
if((sendto(sockfd,buff,n,0,(struct sockaddr *)&claddr,newfd))==-1)
{
perror(SEND ERROR);
exit(1);
}
}
}
else
{
for(;;)
{
n=recvfrom(sockfd,buff1,sizeof(buff1),0,(struct sockaddr *)&claddr,&newfd);
write(1,\rClient :,10);
write(1,buff1,n);
write(1,\nServer : ,sizeof(\nServer:));
}
}
}

OUTPUT:

$cc chatserver.c
$./a.out 7756

/* client side program*/


#include<stdio.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>

171
#include<errno.h>
#include<stdlib.h>
short myport,destport;
main(int argc,char *argv[])
{
int sockfd , newfd , nbyte , n ,na, p;
struct sockaddr_in myaddr , servaddr;
char buff[512] , buff1[512];
if(argc!=4)
{
perror(invalid no of arguments);
exit(1);
}
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))= = -1)
{
perror(unable to create socket );
exit (1);
}
myport=atoi(argv[1]);
myaddr.sin_family=AF_INET;
myaddr.sin_port=htons(myport);
myaddr.sin_addr.s_addr=INADDR_ANY;

bzero(&(myaddr.sin_zero),8);

destport=atoi(argv[2]);
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(destport);
servaddr.sin_addr.s_addr=inet_addr(argv[3]);
bzero(&(myaddr.sin_zero),8);
if(bind(sockfd,(struct sockaddr *)&myaddr,sizeof(myaddr)))==-1)

172
{
perror(bind error);
exit(1);
}
newfd=sizeof(servaddr);
write(1,\n ENTER MESSAGE TO CONNECT TO THE SERVER.. : ,57) ;
for(;;)
if(p=fork())<0)
{
perror(CHILD CANNOT BE CREATED.);
exit(1);
}
if(p<0)
{
for(;;)
{
write(1,\n Client : ,sizeof(\nClient : ));
na=read(0,buff,512);
if((sendto(sockfd,buff,na,0,(struct sockaddr *)&servaddr,newfd))==-1)
{
perror(SEND ERROR);
exit(1);
}
}
}
else
{
for(;;)
{
If((n=recvfrom(sockfd,buff1,sizeof(buff1),0,(struct sockaddr*)&servaddr,&newfd)))==-1);
{

173
perror(RECEIVE ERROR);
exit(1);
}
write(1,\rServer :,10);
write(1,buff1,n);
write(1,\nClient : ,10);
}
}
}

OUTPUT:
$cc chartcli.c
$./a.out 7786 7756 135.135.4.4

ENTER MESSAGE TO CONNECT TO THE SERVER..


Client : hi
Server : hi
Client : how r u
Server : fine
Client : ok bye
Server : bye

174

17.Implementation of Remote files Access using RPC.


AIM: Program for Remote files access using RPC
REQUIREMENTS:
HARDWARE

: Pentium II (233 Hz)/32MB RAM /3.2 GB HDD

SOFTWARE

: Red Hat Linux server v.7.0,c

SOURCE CODE:
struct num
{

char *a;
// long b;

};
program rfa_prog
{
version rfa_vers
{
long rfa_fn(num) = 1
} =1;
} = 0x30000001;

/*rfa_Server.c*/
#include rfa.h
char* rfa(char *f)
{
//if(b= = 0)
//

return a;

int id,n ;
char buff[100];
id=open(f,0);
n=read(id,buff,sizeof(buff));
return buff;

175

//

return rfa(b,a % b)

}
long *rfa_fn_1_svc(num *argp, struct svc_req *rqstp)
{
static char *result;
/* insert server code here*/
result = rfa((*argp).a );
return &result; // return result;
}
/*rfa_client.c*/
#include rfa.h
Void rfa_prog_1(char *host , num number)
{
CLIENT *clnt;
char *result_1;
num rfa_fn_1_arg ;
rfa_fn_1_arg.a = number.a;
// rfa_fn_1_arg.b = number.b ;
#ifndef DEBUG
clnt = clnt_create ( host , RFA_PROG , RFA_VERS , udp);
if(clnt = = NULL){
clnt _pcreateerror(host);
exit(1);
}
#endif /*DEBUG*/
result_1 = rfa_fn_1(&rfa_fn_1_arg , clnt);
if(result_1 = = (char *)NULL) {
clnt_perror(clnt , call failed);
}

176
Printf(rfa is %s, *result_1);
#ifndef DEBUG
clnt_destory(clnt);
#ebdif /*DEBUG*/
}
int main( int argc , char *argv[ ])
{
char *host;
num n;
if(argc<4){
printf(Usage :%s server_host num1 num2 \n,argv[0]);
exit(1);
}
n.a = argv[2];
host = argv[1];
rfa_prog_1(host , n);
exit(0);
}
Steps to execute RPC program:
1. Write your own RPC specification file rfa.x
$ ls
Client.c server.c date.x
2. Use RPC gen to generate the files you need (i.e rfa.h , rfa_svc.c,rfa_xdr.c and
rfa_clnt.c
$ rpgen rfa.x
3. Use rpcgen to generate sample server program
$ rpcgen Ss rfa.x >rfa_server.c
4. Use rpcgen to generate sample client program
$ rpcgen Sc rfa.x >rfa_client.c
5. Use cc to compile your server program (rfa_server.c)
$ cc o rfa_server server.c rfa_svc.c rfa.xdr.c - lnsl

177
6. Use cc to compile your client program (sample_client.c)
$ cc o rfa_client

client.c rfa_clnt.c rfa_xdr.c - lnsl

7. Run your server program


$./ rfa_server
or put server to run in the background
$ ./rfa_server&
8 .Run your client program
$./rfa_client <ipaddress> <filename>

Você também pode gostar