WP LAB Manual 12 13 Vinay Balaji T
WP LAB Manual 12 13 Vinay Balaji T
WP LAB Manual 12 13 Vinay Balaji T
2
17. Implementation of Remote files Access using RPC.
Page No.
12
20
25
30
43
49
55
64
74
80
127
130
135
168
174
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<stdio.h>
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 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
SOURCE CODE:
catalog.xml
12
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)
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)
15
<xsl:for-each select="catalog/cd">
<xsl:if test="year > 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>
16
<xsl:for-each select="catalog/cd">
<xsl:choose>
<xsl:when test="year > 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
20
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*:
emailvalidate();"/> <br>
Course*:
J2EE
23
<input type="checkbox" name="c" value="javascript"
/>VB.Net
<input type="checkbox" name="c" value="html" checked="checked"
/>C#
<input type="checkbox" name="c" value="css" />Oracle<br><br>
<input type=submit value="Send" name="send" />
<input type=reset />
</form>
</body>
</html>
OUTPUT:
24
25
26
SOURCE CODE:
form.html
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
<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
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");
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
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");
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>");
}}*/
<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
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.
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;
45
sc = f.getServletContext();
}
46
sc.getRequestDispatcher(login_page).forward(request, response);
sc.log("after forwarding request to login page");
return;
}
}
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
48
OUTPUT:
49
USER AGENT :
<%=request.getHeader("User-Agent")%>
web.xml
<?xml version="1.0" encoding="UTF-8" ?>
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" ?>
<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
SOURCE CODE:
default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
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;
}
}
57
addnewrecord.aspx
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;
oracon.Open();
string qrystaffinsert = "insert into emp_details values(" + strempid + ",'" +
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.
OUTPUT:
63
64
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);
}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
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
76
OUTPUT:
77
78
79
80
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
-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.
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
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
-E
-F
the local credentials to be forwarded to the remote system,including any credentials that
have already been forwarded into the local environment.
-K
-L
-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
-d
-e escapechar
Sets the initial telnet escape character to escape char. If escape char is omitted,
then there will be no escape character.
-f
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
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
-v
Verbose option forces ftp to show all responses from the remote
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
`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
86
-v
-g
-m
-p
-s
-i
Show the state of the interfaces that are used for TCP/IP traffic.
-r
-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
For
the
AF_INET
address
family
- I interface
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.
-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
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.
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
-s
-v
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:
#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>
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_INET6
PF_IPX
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
95
family.
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.
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>
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
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>
DESCRIPTION:
The file descriptor sockfd must refer to a socket.
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,
Each
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.
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>
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.
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
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.
100
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
2.ssize_t
102
SOFTWARE
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 ()
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
MSB
LSB
16 bit value
Increasing memory
addresses
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.
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
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];
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);
107
fflush(stdout);
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)
{
108
fflush(stdout);
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..
109
/* client side program*/
#include<sys/socket.h>
#include<sys/types.h>
#include<strings.h>
#include<stdio.h>
#include<netinet/in.h>
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));
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*/
110
{
perror("client: cant connect to server\n");
exit(1);
}
printf("\n enter the message to be sent\n");
fflush(stdout);
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);
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);
}
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
Client 2 :
$ cc tcpcli2.c
$ ./a.out
112
113
12.2 AIM: Program for connection-oriented (TCP) service with server as iterative
server
REQUIREMENTS:
HARDWARE
SOFTWARE
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;
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
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
SOFTWARE
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
2.ssize_t
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;
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
#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));
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
SOFTWARE
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
{
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
SOFTWARE
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");
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.
129
#include<netinet/in.h>
main()
{
char buff[512];
int n,i,sockfd,newsockfd;
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
SOFTWARE
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
Socket
SOFTWARE
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
struct iovec {
void *iov_base; /* starting base address*/
size_t iov_len;
/* number of bytes*/
};
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
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
SOFTWARE
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) ;
//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)
{
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
SOFTWARE
THEORY:
Getsockname get the socket name , included in sys/socket.h file
int
getsockname (int
*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_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr(135.135.4.4);
server_address.sin_port=7991;
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 I am giving back the same character back to the client.
146
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(135.135.4.4);
address.sin_port=7991;
len = sizeof(address);
OUTPUT:
147
SOFTWARE
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;
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
149
int main()
{
int sockfd , len , na;
char str[80];
struct sockaddr_in address , name;
int result;
char sent = A;
char received;
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(135.135.4.4);
address.sin_port=7058;
len = sizeof(address);
150
printf( the port is %d \n, htons(name.sin_port));
printf( the peername is %s \n,str);
close(sockfd);
exit(0);
}
OUTPUT:
15.5 AIM: Advance socket system calls: program for setsockopt (), getsockopt ()
REQUIREMENTS:
HARDWARE
SOFTWARE
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
SOFTWARE
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.
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
0x40000000- 0x5fffffff
0x60000000-0xffffffff
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;
#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
if(clnt = = NULL)
{
clnt_pcreateerror(host);
exit(1);
}
157
result_1 = date_1(NULL, clnt);
158
OUTPUT:
The message is sat dec 29 17:53:42 2012
SOFTWARE
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.
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>
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
SOFTWARE
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
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);
}
164
6. Use cc to compile your client program (sample_client.c)
$ cc o sample_client sample_client.c sample_clnt.c - lnsl
j)
SOFTWARE
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;
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)
168
SOFTWARE
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
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
174
SOFTWARE
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