wp lab manual 12 13 vinay balaji t
DESCRIPTION
WP LAB Manual 12 13 Vinay Balaji TTRANSCRIPT
-
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 4
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. 168
17. Implementation of Remote files Access using RPC. 174
-
3
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 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 tag. A table is divided into rows (with the
tag), and each row is divided into data cells (with the 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
tag. The type of input is specified with the type attribute.
The following UI screens correspond to a sample website.
-
4
SOURCE CODE:
index.html
Frames
Format.html
Formatting Tags This is the text This is the text This is the text This is the text This is the text This is the text This is the text
-
5
X2 X2 This is the text This is the text #include main() { printf("Hello World!"); } Anchor.html
Anchor tags Format Tags Tables Lists.html
Lists
-
6
Java C Python C++ Java C Python C++ Scala Scala C This is a programming language C This is a programming language Tables.html
Tables Student marks M1 M2 M3
-
7
100 65 82 98 53 35 45 Forms.html
Forms Username Password M F Copy.html
-
8
Copy Right Reserved to S.Vinay kumar Logo.html
New Document WebSite 1 Leftframe.html
Anchor tags Format Tags Lists Tables Anchor tags Form
-
9
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
Lord of the rings
Kate
US
Warner Bros
250
2006
Quantum of Solace
James Bond
US
Para Mount
250
2007
Slumdog Millionaire
Anil Kapoor
India
Warner Bros
250
2009
-
13
cd.xsl( To display title and artist from a catalog)
CD collection
Title
Artist
cd1.xsl( To display in sorted order on artist)
-
14
CD collection
Title
Artist
cd2.xsl( To display data of catalog for year greater than2007)
CD collection
Title
Artist
Year
-
15
cd3.xsl ( To demonstrate for-each element)
CD collection
Title
Artist
Year
-
16
sorry year cannot be permitted
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:
Form Validation
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
-
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
UserName*:
Email-Id*:
Course*:
J2EE
-
23
VB.Net
C#
Oracle
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
UserName:
Password:
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("Invalid UserName or Password");
//Display form following errors
out.println("html code for displaying form");
/*OR
out.println("Go Back");
*/
/*OR
ServletConfig config=getServletConfig();
ServletContext application=getServletContext();
RequestDispatcher rd=application.getRequestDispatcher("/form.html");
rd.include(req,resp);
*/
}
}
}
-
28
web.xml
valserv
Authenticate
valserv
/auth
-
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
UserName
Age
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("");
out.println("");
out.println("qualification");
out.println("company");
out.println("" );
out.println("");
}
}
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
-
34
web.xml
session
SessionServlet
result
Result
session
/serv1
result
/serv2
index.jsp
index.html
index.htm
-
35
OUTPUT:
-
36
-
37
b) SOURCE CODE:
index.html
UserName
Age
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("");
out.println("");
out.println("qualification");
out.println("company");
out.println("" );
out.println("");
}
}
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
-
40
Result
session
/serv1
result
/serv2
index.jsp
index.html
index.htm
-
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
UserName
Password
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()+"");
}
}
-
47
web.xml
session
AuthFilter
< servlet >
result
Result
< filter-name>session
/*
result
/serv1
index.jsp
index.html
index.htm
-
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 :
web.xml
-
50
OUTPUT:
-
51
b) SOURCE CODE:
index.jsp
UN
PWD
auth.jsp
error.jsp
-
52
web.xml
valserv
/jsp/auth.jsp
error
/jsp/error.jsp
valserv
/auth
error
/error.jsp
-
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
Employee Details
-
56
Employee Details
Add New Record
Delete
Modify
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
Untitled Page
Add New Record
Employee Id :
Employee Name :
Date Of Birth :
Gender :
Male
Female
-
58
Department :
Address1 :
Phone No.:
EMail :
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
-
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
-->
-
62
to be displayed in place of a error stack trace.
-->
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
UserName:
-
65
Password:
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("Invalid UserName");
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("Invalid UserName & Password");
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
-
67
valserv
Authenticate
valserv
/auth
OUTPUT:
Database(MySQL) Console
-
68
-
69
-
70
b) SOURCE CODE:
form.html
Enter Dept:
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("Data related to student in"+dept+"department:");
out.println("");
while(rs.next()){
out.println("");
out.println(""+rs.getString(1)+"");
out.println(""+rs.getString(2)+"");
out.println(""+rs.getString(3)+"");
out.println("");
}
out.println("");
}catch(Exception ex)
{System.out.println("Exception"+ex);}
}
}
-
72
web.xml
valserv
Authenticate
valserv
/auth
-
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
-
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 TELNET
protocol. If telnet is invoked without the host argument, it 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 turn off interactive prompting during multiple file transfers.
-n 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 command interpreter and await
instructions from the user. When ftp is 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:
This header file contains declaration used in most input and output functions and is
typically included in all c programs.
#includes:
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:
This header file includes a number of definitions of structures needed for sockets.
#includes: This header file contains constants and structures needed for internet domain address
SOCKET: socket - create an endpoint for communication
#include
#include
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 . 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 .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
#include
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 connection-
oriented, 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
#include
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
#include
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 #include
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
-
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
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
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.
socket ()
bind ()
listen ()
socket ()
bind ()
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
Little-endian byte order
Increasing memory
addresses
big-endian byte order
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:-
d) uint16_t htons(uint16_t host16bitvalue);
e) uint32_t htonl(uint32_t 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
High order byte low order byte
High order byte low order byte
MSB 16 bit value LSB
-
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
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
#include
#include
#include
#include
#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))
-
107
fflush(stdout);
/*accept takes the first connection request*/
newsockfd=accept(sockfd,(struct sockaddr *)&cli_addr,&chilen);
if(newsockfd
-
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
#include
#include
#include
#include
#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))
-
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))
-
111
if((n=read(sockfd,buff2,MAX))
-
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
#include
#include
#include
#include
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))
-
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))
-
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
#include
#include
#include
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))
-
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))
-
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.