Sei sulla pagina 1di 208

B. P.

PODDAR INSTITUTE OF MANAGEMENT & TECHNOLOGY


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
ACADEMIC YEAR: 2017-2018 [ODD SEMESTER]

INTERNET TECHNOLOGY LAB


CS 795A
LAB MASTER MANUAL

LAB MANUAL PREPARED BY


PHULTULI SARKHEL
B. P. PODDAR INSTITUTE OF MANAGEMENT & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
ACADEMIC YEAR: 2017-2018 [ODD SEMESTER]
LAB MASTER MANUAL

Course: Internet Technology Lab


Code: CS795A
Branch & Sec: CSE (Sec-A,Sec-B)

Applet

1. Create a banner using Applet


2. Display clock using Applet
3. Create different shapes using Applet
4. Fill colors in shapes using Applet
5. Goto a link using Applet
6. Create an event listener in Applet
7. Display image using Applet
8. Open a link in a new window using Applet
9. Play sound using Applet
10. Read a file using Applet
11. Write to a file using Applet JavaScript
12. Validate the fields of a form using JavaScript.
13. Guess a number based on user input.

JavaScript
14. Program on image rollover using JavaScript.
15. Display clock using JavaScript.
16. Prompt, alert, array, looping in JavaScript.
17. Calculator using JavaScript.
18. Validate e-mail, phone no. using reg-ex in JavaScript.

Perl
19. Write a perl script to implement associative array.
20. Write a perl script to implement the regular expression as follows:
a). If a string contains any vowel, count the total number of vowels.
b). If a string starts with MCA and end with bw, print 1 else 0.
c). If string starts with 0 or any no. a’s, then print 1 else 0.
21. Write an html code to call a perl script from cgi-bin.
22. Implement the following with regular expression in Perl:
a). a*bc
b). a* at least 2 b’s
c). a*exactly 3 b’s
23. A simple File operation using Perl

1
Client Server Programming

24. Write a socket program to get the current date and time from the server.
25. Write a socket program where the client will send lowercase letters and the server will
return uppercase letter.
26. Write a server and a client program to implement TCP chat server-client.
27. Create a simple calculator application using Java RMI.

HTML

1. Start your web page with an <html> tag


i) Add a heading.
ii) Add a title.
iii) Start the <body> section.
iv) Add the following text using <H1> and </H1> tags:
This Web page was designed by (your name)
v) Add the following text using <H2> and </H2> tags: My HTML assignment
vi) Add a horizontal line
vii) Insert an image to your web page.
Note: You should then refer to your image with just the filename, and NOT the entire
pathname to the file.
viii) Add another horizontal line.
ix) Enter a paragraph of text.
Write about things you have learned in html.
Make sure the text in this paragraph is a color other than black, but something one can see.
Add a link that takes you to your favorite webpage.
x) Start a new paragraph. Add a three item ordered list. Make it creative (don’t just say item
1, item 2, etc… and keep it clean)!
xi) Close out your body and html tags.

2. Start your web page with an <html> tag


i) Add a heading.
ii) Add a title.
iii) Start the <body> section.
iv) Start a new paragraph.
Use alignment attribute,
Use bold, italic, underline tags,
Use font tag and associated attributes,
Use heading tags,
Use preserve tag,
Use non breaking spaces (escape character).

2
3. Start your web page with an <html> tag
i) Add a heading.
ii) Add a title.
iii) Start the <body> section.
iv) Start a new paragraph.
Create Hyperlinks:
(a) Within the HTML document.
(b) To another URL.
(c) To a file that can be rendered in the browser.

4. Start your web page with an <html> tag


i) Add a heading.
ii) Add a title.
iii) Start the <body> section.
Create an unordered list,
Create an ordered list,
Use various bullet styles,
Created nested lists,
Use the font tag in conjunction with lists,
Create definition lists,
Use graphics as bullets.

5. Start your web page with an <html> tag


i) Add a heading.
ii) Add a title.
iii) Start the <body> section.
a) Create a simple table
Create borders and adjust border size.
Adjust table cell spacing.
Change border color.
Change table background color.
b) Align a new table on HTML page.
Perform cell text alignment,
Create multi-column tables,
Display information about your academic qualification into this table.

6. Start your web page with an <html> tag


i) Add a heading.
ii) Add a title.
iii) Start the <body> section.
Create a frameset:
Use frame tags,
Create vertical (column) frames,
Create horizontal (row) frames,
Create complex framesets,
3
Use the hyperlink tag to target displaying an HTML page to another frame.

7. Start your web page with an <html> tag


i) Add a heading.
ii) Add a title.
iii) Start the <body> section.
Create a simple HTML form.
Use the input tag to create a: text box; text area box; check box; list box; radio button;
password field; popup menu; hidden field. Use submit and reset buttons. Create an
admission form using the above information.

8. Create a web page that will include an image. Then create image map to watch different
parts of that image closely.

9. Using frames as an interface, create a series of web pages where the theme is to provide
resources (internet, intranet, static HTML pages) pertaining to the subject of HTML. Ideally,
your goal is to create a resource that you can use long after this module when needing
information on HTML. As a minimum requirement to this assignment your webpage should:

• Consist of at least 3 frames.


• Contain at least 5 URLs to internet and/or intranet sites that you can reference as part of
your job.
• Contain at least 5 references to documents that you have created that you use on a regular
basis.
• Contain at least 5 references to documents others have created that you use on a regular
basis.
• Be organized in a fashion that is logical and intuitive to you.
• Is done with enough quality that you would not be opposed to it being a link at another
site.

10. Create a web page as you wish and the html elements of the page will be styled by CSS.
XML

1. Write a XML program that will create an XML document which contains your mailing
address.

2. Write a XML program that will create an XML document which contains description of three
book category.

3. Create an XML document that contains the name and price per pound of coffee beans.
i) In your XML document mention all properties of XML declaration.
ii) The root element has name <coffee_bean>
iii) Create nested elements for different types of coffee.
iv) Validate the document and if any parsing error is present, fix them.

4
4. Create an XML document that contains airline flight information.

i) In your XML document mention all properties of XML declaration.


ii) The root element has name <airlines>
iii) Create three nested <carrier> elements for three separate airlines. Each element should
include a name attribute.
iv) Within each <carrier> nest at least two <flight> ,each of which contains departure_city,
destination_ city, fl_no, dept_time.
v) Validate the document and if any parsing error is present fix them.

5. Create an XML version of your resume. Include elements such as your name and position
desired. Nest each of your former employers within an <employer> element. Also, nest your
educational experience within an <education> element. Create any other nested elements that
you deem appropriate, such as <references> or <spcl_skills> elements.

6. Create a DTD on product catalogue

5
Applet
Programming

6
Problem Description
How to create a banner using Applet?

Solution
Following example demonstrates how to play a sound using an applet image using Thread class. It
also uses drawRect(), fillRect(), drawString() methods of Graphics class.

import java.awt.*;

import java.applet.*;

public class SampleBanner extends Applet implements Runnable {


String str = "This is a simple Banner ";
Thread t ;
boolean b;

public void init() {


setBackground(Color.gray);

setForeground(Color.yellow);

}
public void start() {

t = new Thread(this);
b = false;

t.start();

}
public void run () {
char ch;
for( ; ; ) {

try {

repaint();
Thread.sleep(250);
ch = str.charAt(0);
str = str.substring(1, str.length());

str = str + ch;


}

catch(InterruptedException e) {}
7
}

}
public void paint(Graphics g) {

g.drawRect(1,1,300,150);
g.setColor(Color.yellow);
g.fillRect(1,1,300,150);
g.setColor(Color.red);

g.drawString(str, 1, 150);
}

Result
The above code sample will produce the following result in a java enabled web browser.

View in Browser.

The following is an another sample example to create a banner using Applet.

import java.awt.*;
import java.applet.*;

public class NewApplet extends Applet implements Runnable {


String msg = " It is a moving Banner. ";
char cha;
boolean stopFlag = true;

Thread t = null;

public void start() {


t = new Thread(this);

stopFlag = false;

t.start();
}

public void run() {


for(;;) {
try {
repaint();
Thread.sleep(250);
cha = msg.charAt(0);

8
msg = msg.substring(1,msg.length());

msg = msg + cha;


if(stopFlag) break;

}
catch(InterruptedException e) {}
}
}

public void stop(){


stopFlag = true;

t = null;
}
public void paint(Graphics g) {
g.drawString(msg,60,30);

Problem Description
How to display clock using Applet?

Solution
Following example demonstrates how to display a clock using valueOf() methods of String Class.
& using Calender class to get the second, minutes & hours.

9
import java.awt.*;
import java.applet.*;
import java.applet.*;
import java.awt.*;
import java.util.*;

public class ClockApplet extends Applet implements Runnable {


Thread t,t1;
public void start() {
t = new Thread(this);
t.start();
}
public void run() {
t1 = Thread.currentThread();
while(t1 == t) {
repaint();
try {
t1.sleep(1000);
}
catch(InterruptedException e){}
}
}
public void paint(Graphics g) {
Calendar cal = new GregorianCalendar();
String hour = String.valueOf(cal.get(Calendar.HOUR));
String minute = String.valueOf(cal.get(Calendar.MINUTE));
String second = String.valueOf(cal.get(Calendar.SECOND));
g.drawString(hour + ":" + minute + ":" + second, 20, 30);
}
}

Result
The above code sample will produce the following result in a java enabled web browser.

View in Browser.

The following is an another sample example to display clock using Applet.

import java.applet.*;
10
import java.awt.*;
import java.util.*;
import java.text.*;

public class javaApplication6 extends Applet implements Runnable {


Thread t1 = null;
int hours = 0, minutes = 0, seconds = 0;
String time = "";

public void init() {


setBackground( Color.green);
}
public void start() {
t1 = new Thread( this );
t1.start();
}
public void run() {
try {
while (true) {
Calendar cal = Calendar.getInstance();
hours = cal.get( Calendar.HOUR_OF_DAY );
if ( hours > 12 ) hours -= 12;
minutes = cal.get( Calendar.MINUTE );
seconds = cal.get( Calendar.SECOND );

SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");


Date d = cal.getTime();
time = formatter.format( d );

repaint();
t1.sleep( 1000 );
}
}
catch (Exception e) { }
}
public void paint( Graphics g ) {
g.setColor( Color.blue );
11
g.drawString( time, 50, 50 );
}
}

Problem Description
How to create different shapes using Applet?

Solution
Following example demonstrates how to create an applet which will have a line, an Oval & a
Rectangle using drawLine(), drawOval(, drawRect() methods of Graphics clas.

import java.applet.*;
import java.awt.*;

public class Shapes extends Applet {


int x = 300, y = 100, r = 50;

public void paint(Graphics g) {


g.drawLine(30,300,200,10);
g.drawOval(x-r,y-r,100,100);
g.drawRect(400,50,200,100);

Result
The above code sample will produce the following result in a java enabled web browser.

A line , Oval & a Rectangle will be drawn in the browser.

12
Problem Description
How to fill colors in shapes using Applet?

Solution
Following example demonstrates how to create an applet which will have fill color in a rectangle
using setColor(), fillRect() methods of Graphics class to fill color in a Rectangle.

import java.applet.*;
import java.awt.*;

public class fillColor extends Applet {


public void paint(Graphics g) {
g.drawRect(300,150,200,100);
g.setColor(Color.yellow);
g.fillRect( 300,150, 200, 100 );
g.setColor(Color.magenta);
g.drawString("Rectangle",500,150);
}
}

Result
The above code sample will produce the following result in a java enabled web browser.

A Rectangle with yellow color filled in it will be drawn in the browser.

Problem Description
How to goto a link using Applet?

Solution
Following example demonstrates how to go to a particular webpage from an applet using
showDocument() method of AppletContext class.

import java.applet.*;
import java.awt.*;
import java.net.*;
13
import java.awt.event.*;
public class tesURL extends Applet implements ActionListener {
public void init() {
String link = "yahoo";
Button b = new Button(link);
b.addActionListener(this);
add(b);
}
public void actionPerformed(ActionEvent ae) {
Button src = (Button)ae.getSource();
String link = "http://www."+src.getLabel()+".com";
try {
AppletContext a = getAppletContext();
URL u = new URL(link);
a.showDocument(u,"_self");
} catch (MalformedURLException e){
System.out.println(e.getMessage());
}
}
}

Result
The above code sample will produce the following result in a java enabled web browser.

View in Browser.

Problem Description
How to create an event listener in Applet?

Solution
Following example demonstrates how to create a basic Applet having buttons to add & subtract
two nos. Methods used here are addActionListener() to listen to an event(click on a button) &
Button() construxtor to create a button.

import java.applet.*;
import java.awt.event.*;
import java.awt.*;

14
public class EventListeners extends Applet implements ActionListener {
TextArea txtArea;
String Add, Subtract;
int i = 10, j = 20, sum = 0, Sub = 0;

public void init() {


txtArea = new TextArea(10,20);
txtArea.setEditable(false);
add(txtArea,"center");
Button b = new Button("Add");
Button c = new Button("Subtract");
b.addActionListener(this);
c.addActionListener(this);
add(b);
add(c);
}
public void actionPerformed(ActionEvent e) {
sum = i + j;
txtArea.setText("");
txtArea.append("i = "+ i + "\t" + "j = " + j + "\n");
Button source = (Button)e.getSource();

if(source.getLabel() == "Add") {
txtArea.append("Sum : " + sum + "\n");
}
if(i >j) {
Sub = i - j;
} else {
Sub = j - i;
}
if(source.getLabel() == "Subtract") {
txtArea.append("Sub : " + Sub + "\n");
}
}
}

Result
15
The above code sample will produce the following result in a java enabled web browser.

View in Browser.

Problem Description
How to display image using Applet?

Solution
Following example demonstrates how to display image using getImage() method. It also uses
addImage() method of MediaTracker class.

import java.applet.*;
import java.awt.*;

public class appletImage extends Applet {


Image img;
MediaTracker tr;
public void paint(Graphics g) {
tr = new MediaTracker(this);
img = getImage(getCodeBase(), "demoimg.gif");
tr.addImage(img,0);
g.drawImage(img, 0, 0, this);
}
}

Result
The above code sample will produce the following result in a java enabled web browser.

View in Browser.

Problem Description
How to open a link in a new window using Applet?

Solution
Following example demonstrates how to go open a particular webpage from an applet in a new
window using showDocument() with second argument as "_blank".

import java.applet.*;
16
import java.awt.*;
import java.net.*;
import java.awt.event.*;
public class testURL_NewWindow extends Applet implements ActionListener {
public void init() {
String link_Text = "google";
Button b = new Button(link_Text);
b.addActionListener(this);
add(b);
}
public void actionPerformed(ActionEvent ae) {
Button source = (Button)ae.getSource();
String link = "http://www."+source.getLabel()+".com";
try {
AppletContext a = getAppletContext();
URL url = new URL(link);
a.showDocument(url,"_blank");
} catch (MalformedURLException e) {
System.out.println(e.getMessage());
}
}
}

Problem Description
How to play sound using Applet?

Solution
Following example demonstrates how to play a sound using an applet image using getAudioClip(),
play() & stop() methods of AudioClip() class.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class PlaySoundApplet extends Applet implements ActionListener {

17
Button play,stop;

AudioClip audioClip;

public void init() {


play = new Button(" Play in Loop ");
add(play);
play.addActionListener(this);

stop = new Button(" Stop ");


add(stop);

stop.addActionListener(this);
audioClip = getAudioClip(getCodeBase(), "Sound.wav");
}
public void actionPerformed(ActionEvent ae) {

Button source = (Button)ae.getSource();

if (source.getLabel() == " Play in Loop ") {

audioClip.play();
} else if(source.getLabel() == " Stop "){
audioClip.stop();

Problem Description
How to read a file using Applet?

Solution
Following example demonstrates how to read a file using an Applet using openStream() method of
URL.

import java.applet.*;

import java.awt.*;
import java.io.*;

import java.net.*;

public class readFileApplet extends Applet {


String fileToRead = "test1.txt";

18
StringBuffer strBuff;

TextArea txtArea;
Graphics g;

public void init() {


txtArea = new TextArea(100, 100);
txtArea.setEditable(false);

add(txtArea, "center");
String prHtml = this.getParameter("fileToRead");

if (prHtml != null) fileToRead = new String(prHtml);


readFile();
}

public void readFile(){

String line;

URL url = null;


try {
url = new URL(getCodeBase(), fileToRead);

catch(MalformedURLException e){}

try { InputStream in = url.openStream();


BufferedReader bf = new BufferedReader(new InputStreamReader(in));
strBuff = new StringBuffer();

while((line = bf.readLine()) != null) {

strBuff.append(line + "\n");
}

txtArea.append("File Name : " + fileToRead + "\n");

txtArea.append(strBuff.toString());
} catch(IOException e) {
e.printStackTrace();

}
}

// All programs sourced from https://www.tutorialspoint.com

19
20
Javascript

12. Validate the fields of a form using JavaScript

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Can Validate Input</h2>

<p>Please input a number between 1 and 10:</p>

<input id="numb">

<button type="button" onclick="myFunction()">Submit</button>

<p id="demo"></p>

<script>
function myFunction() {
21
var x, text;

// Get the value of the input field with id="numb"


x = document.getElementById("numb").value;

// If x is Not a Number or less than one or greater than 10


if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("demo").innerHTML = text;
}
</script>

</body>
</html>

/* Alternative */
/* IsEmpty Java Script Function */

function IsEmpty(objectfield,stringfield)
{
objectvalue = objectfield.value.length;
if(objectvalue=="")
{
alert("Oops.. Please fill out the value of "+stringfield);
objectfield.style.background = 'Yellow';
return false;
}
else
return true;
}

/*Alternative*/
/* validateUsername JavaScript Function*/

function validateUsername(fld) {
var error = "";
var illegalChars = /\W/; // allow letters, numbers, and underscores

if (fld.value == "") {
fld.style.background = 'Yellow';
error = "You didn't enter a username.\n";
alert(error);
return false;

} else if ((fld.value.length < 5) || (fld.value.length > 15)) {


fld.style.background = 'Yellow';
error = "The username is the wrong length.\n";
22
alert(error);
return false;

} else if (illegalChars.test(fld.value)) {
fld.style.background = 'Yellow';
error = "The username contains illegal characters.\n";
alert(error);
return false;

} else {
fld.style.background = 'White';
}
return true;
}

/*Alternative*/
/*validatePassword JavaScript Function */

function validatePassword(fld) {
var error = "";
var illegalChars = /[\W_]/; // allow only letters and numbers

if (fld.value == "") {
fld.style.background = 'Yellow';
error = "You didn't enter a password.\n";
alert(error);
return false;

} else if ((fld.value.length < 7) || (fld.value.length > 15)) {


error = "The password is the wrong length. \n";
fld.style.background = 'Yellow';
alert(error);
return false;

} else if (illegalChars.test(fld.value)) {
error = "The password contains illegal characters.\n";
fld.style.background = 'Yellow';
alert(error);
return false;

} else if ( (fld.value.search(/[a-zA-Z]+/)==-1) || (fld.value.search(/[0-9]+/)==-1) ) {


error = "The password must contain at least one numeral.\n";
fld.style.background = 'Yellow';
alert(error);
return false;

} else {
fld.style.background = 'White';
}
return true;
}

23
13. Guess a number based on user input

<html>
<body>
<script>
var x = Math.floor(Math.random() * 100) + 1;
var turns = 5;
var hint = 'Guess my number, 1-100!';

while (turns > 0) {


var guess = prompt(hint +
' You have ' + turns + ' guesses left.');
if (!guess) break;
guess = Number(guess);
if (guess == x) {
document.write('<p>YOU WIN!</p>' +
'<p><img src="/images/photo/gold_trophy.jpg">');
turns = 0;
} else {
hint = 'Nope.';
if (guess < x) hint += ' Too small!';
if (guess > x) hint += ' Too big!';
turns = turns - 1;
}
}
alert('The secret number was ' + x + '.');
</script>
</body>
</html>

14. Program on image rollover using JavaScript.

<!DOCTYPE html>
<html>
<body>

<p>This example uses the addEventListener() method to attach a "mouseover" and "mouseout"
event to a h1 element.</p>

<h1 id="demo">Mouse over me</h1>

<script>
document.getElementById("demo").addEventListener("mouseover", mouseOver);
document.getElementById("demo").addEventListener("mouseout", mouseOut);

function mouseOver() {
document.getElementById("demo").style.color = "red";
}

function mouseOut() {
document.getElementById("demo").style.color = "black";
}
</script>

</body>

24
</html>

15. Display clock using JavaScript.

<!DOCTYPE html>
<html>
<head>
<script>
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
</head>

<body onload="startTime()">

<div id="txt"></div>

</body>
</html>

16. Prompt, alert, array, looping in JavaScript.

PROMPT

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Prompt</h2>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var txt;
var person = prompt("Please enter your name:", "Harry Potter");
if (person == null || person == "") {
25
txt = "User cancelled the prompt.";
} else {
txt = "Hello " + person + "! How are you today?";
}
document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>

ALERT

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Alert</h2>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
alert("I am an alert box!");
}
</script>

</body>
</html>

ARRAY

html>

<head>
<title>Basic Javascript Array Example</title>

<script language="javascript">
// Empty array
var empty = [];

// Array containing initial elements.


var fruits = ['apple', 'orange', 'kiwi'];

alert(fruits[1]);
</script>
</head>

<body>

26
</body>

</html>

LOOP
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Loops</h2>

<p id="demo"></p>

<script>
var text = "";
var i;
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

17. Calculator using JavaScript

<h1>JavaScript Calculator</h1>
<p class="warning">Don't divide by zero</p>

<div id="calculator" class="calculator">

<button id="clear" class="clear">C</button>

<div id="viewer" class="viewer">0</div>

<button class="num" data-num="7">7</button>


<button class="num" data-num="8">8</button>
<button class="num" data-num="9">9</button>
<button data-ops="plus" class="ops">+</button>

<button class="num" data-num="4">4</button>


<button class="num" data-num="5">5</button>
<button class="num" data-num="6">6</button>
<button data-ops="minus" class="ops">-</button>

<button class="num" data-num="1">1</button>


<button class="num" data-num="2">2</button>
<button class="num" data-num="3">3</button>
<button data-ops="times" class="ops">*</button>
27
<button class="num" data-num="0">0</button>
<button class="num" data-num=".">.</button>
<button id="equals" class="equals" data-result="">=</button>
<button data-ops="divided by" class="ops">/</button>
</div>

<button id="reset" class="reset">Reset Universe?</button>

18. Validate e-mail, phone no. using reg-ex in JavaScript.

/ validatePhone JavaScript Function /

function validatePhone(fld) {
var error = "";
var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');

if (fld.value == "") {
error = "You didn't enter a phone number.\n";
fld.style.background = 'Yellow';
alert(error);
return false;
}

/* validate_email Java Script Function */

function validate_email(field,alerttxt)
{
with (field)
{
apos=value.indexOf("@");
dotpos=value.lastIndexOf(".");
if (apos<1||dotpos-apos<2){
alert(alerttxt);return false;
}
else {
return true;
}
}
}

28
29
PERL

Learn Perl by Example - Perl Handbook


for Beginners - Basics of Perl Scripting
Language
www.freebsdonline.com
Copyright © 2006 - 2008 www.freebsdonline.com
2008/01/29
This course is about Perl Programming Language. It is for beginners and it explain Perl
basics in a easy to learn way. If you are a sysadmin and you learn Linux or UNIX this is
what you need to be able to write Perl scripts, to know a language every sysadmin must
know.
PERL is a powerful scripting language, very popular among UNIX/Linux admins. This
tutorials will try to cover everything you need to know in order to program in Perl. Perl

30
stands for Practical Extraction an Report Language, it was first used as text processor, it
borrows features from C, shell scripting (UNIX sh), sed, awk, Lisp, Pascal. It can be used
also for developing dyamic web applications as CGIs.
This tutorial was provided by http://www.freebsdonline.com
You may freely distribute this document in any form without changing the text or
removing copyright notice.
1
Learn Perl by Example - Perl Handbook for Beginners - Basics of Perl Scripting Language
Table of Contents
1 Introduction
PERL is a powerful scripting language, very popular among UNIX/Linux admins. This tutorials
will try to cover everything you need to know in order to program in Perl. Perl stands for
Practical Extraction an Report Language, it was first used as text processor, it borrows features
from C, shell scripting (UNIX sh), sed, awk, Lisp, Pascal. It can be used also for developing
dyamic web applications as CGIs.
1.1 Few things to know before start programming in Perl
Perl code is portable. Most scripts are written for version 5.8 or higher. When start programming
in Perl first you might want to find the path of Perl binary. On most UNIX/Linux systems you can
do that with whereis command:
whereis perl
As a result of this command you might have: /usr/bin/perl. So your scripts must have first line of
code with this value:
#!/usr/bin/perl
# rest of code # will be used for comments.
On first line of sourcecode this line will help shell in finding what binary to use when running the
script.
2
Learn Perl by Example - Perl Handbook for Beginners - Basics of Perl Scripting Language
In order to properly run the script your source code must also have executable flag for the user
you use to run the script. This can be achieved for example for file prog1.pl adding executable
flag from command line:
chown u+x progr1.pl
So, to start your Perl script you will follow:
a) Create an empty file:
touch program.pl
b) Add executable flag to that file:
chown u+x program.pl
c) Find where your Perl binary is:
whereis perl
(you will get something like /usr/bin/perl).
c) Edit that file with your text editor, and add perl path with this syntax: #!/usr/bin/perl (not that #
on first line of your code will not be seen as comment)
edit program.pl
and put there: #!/usr/bin/perl.
Note: For Linux you can use nano, pico or mcedit. Edit is your default text editor in FreeBSD. If you have installed
Midnight Commander package, you can use mcedit, which is nice.
Note: use strict; put in perl sourcecode will force us to declare variables in a more safe (proper) way. All
variables must be declared with my prefix.
Note: By adding -w to #!/usr/bin/perl it will activate perl warnings, very usefull for debugging.
#!/usr/bin/perl -w
3
Learn Perl by Example - Perl Handbook for Beginners - Basics of Perl Scripting Language
2 Perl Variables
31
Perl has 3 types of variables:
• scalars;
• arrays;
• hashes;
2.1 Scalars
Example on how to define a scalar variable in Perl:
$var1 = "value" # a scalar variable var1 is defined and a string
# "value" is assigned to that variable;
$var2 = 100 # a scalar variable var2 is defined, and an
#integer value is assigned.
Example: To print a scalar value we will use:
print "$var1";
2.2 Arrays
Example on how to define an array in Perl:
@array1 = ( "Value1", "Value2", Value3");
Example on how to print an array:
print "Our array variable contains: @array1\n";
In our example we’ve used \n escape char to insert a new line (escape chars can be used the same
way are used in C language).
The previous example will display all values from array1 array.
To display one element of the array:
4
Learn Perl by Example - Perl Handbook for Beginners - Basics of Perl Scripting Language
print "First element of the array is: $array1[0]";
As you might notice we’ve defined array with @ but printed a single value of that array using $.
This is correct because we want to print a single value.
It is also possible to print multiple values from an array:
print "Our array contains: @array1[0..2]";
Previous example will print elements from 0 to element nr.2 from array1.
You can also print multiple distinct elements from array:
print "Our array contains: @array1[0,4,7]";
The previous example will print only values for element 0, 4 and 7. Note that in perl first value of
an array is number 0.
That is fine but how do we find the number of elements of an array?
print "Number of elements of an array: $#array1";
Note that $#array1 in our example is number of elements, but because elements from an array in
Perl starts with value 0, the real number of elements of an array is $#array + 1.
There is another method to define an array:
@array2 = qw(Value1 Value2 Value3 Value4);
Perl functions for working with arrays:
• pop - remove last element of an array:
• push - add an element to the end of array;
• shift - removes first element of an array;
• unshift - add an element to the beginning of array;
5
Learn Perl by Example - Perl Handbook for Beginners - Basics of Perl Scripting Language
• sort - sort an array.
Let’s see some examples:
Pop Function (remove last element of an array):
#!/usr/bin/perl -w
@array1 = ("Data1", "Data2", "Data3");
print "Array1 values: @array1[0..$#array1]\n";
pop @array1;

32
print "Array1 after applying pop function: @array1[0..$#array1]\n";
Push Function (add an element to the end of array):
#!/usr/bin/perl -w
@array1 = ("Data1", "Data2", "Data3");
print "Array1 values: @array1[0..$#array1]\n";
push @array1, "Data4";
print "Array1 after applying push function: @array1[0..$#array1]\n";
Shift Function (removes first element of an array):
#!/usr/bin/perl -w
@array1 = ("Data1", "Data2", "Data3");
print "Array1 values: @array1[0..$#array1]\n";
shift @array1;
print "Array1 after applying shift function: @array1[0..$#array1]\n";
6
Learn Perl by Example - Perl Handbook for Beginners - Basics of Perl Scripting Language
The same principle apply for unshift and sort functions. Sort functions works best with strings.
2.3 Hashes
Hashes are types of variables defined as key - value pair.
Example of defining a hash variable:
%name_email = ("John", "john@example.com" , "George", "george@example.com");
Another way to define a has variable:
%name_email = (
John => "john@example.com",
George => "george@example.com",
);
Example of using hash variables:
#!/usr/bin/perl -w
%name_email = ( "John", "john@example.com", "George", "george@example.com");
print $name_email{"John"};
Note: Note: We’ve used escape character to preserver @. Also note that printing a hash variable means to print
a scalar with value key between braces { }.
3 Perl control structures
3.1 Conditionals
For testing conditionals within Perl if it is used. To better illustrates, see the following example:
#!/usr/bin/perl -w
$var1 = 100;
7
Learn Perl by Example - Perl Handbook for Beginners - Basics of Perl Scripting Language
$var2 = 200;
if ($var1 < $var2) {
print "$var1 < $var2\n";
}
Note: When evaluating expressions if variables are numbers we will use mathematical operators ( < > = <= >=
==). When we use string variables we use string evaluation operators like gt (greater then) eq (equal) and so on.
Note: When we evaluate two numbers to be identical, we use == operator (not = which is used for assigning
values.
Another example follows:
#!/usr/bin/perl -w
$var1 = 400;
$var2 = 200;
if ($var1 < $var2) {
print "$var1 < $var2\n";
}
elsif ($var1 > var2) {
print "$var1 > $var2\n";
}
33
elsif function as a nested if.
The inverse test of if is unless function:
unless ($var1 == $var2) {
print "$var1";
8
Learn Perl by Example - Perl Handbook for Beginners - Basics of Perl Scripting Language
3.2 Loops
3.2.1 For Loops
In Perl sometimes are many way to solve a problem. We will show 3 ways to construct a loop
using for.
Example 1: For loop using C style:
#!/usr/bin/perl -w
# for loop example 1
for ($i = 1; $i < 100; $i++) {
print "$i\n";
}
Example 2: for loops using ranges:
#!/usr/bin/perl -w
# for loop example 2
$var1 = 1;
$var2 = 100;
$i = 1;
for ($var1..$var2) {
print "$i\n";
$i+=1;
}
Example 3: loop using foreach:
#!/usr/bin/perl -w
# for loop example 3
@array1 = ( "Val1", "Val2", "Val3", "Val4", "Val5");
foreach (@array1) {
print "$_\n";
}
9
Learn Perl by Example - Perl Handbook for Beginners - Basics of Perl Scripting Language
Note: $_ will print the current value of an array.
3.2.2 While Loops
An example is presented next:
#!/usr/bin/perl -w
$var1 = 1;
$var2 = 8;
while ($var1 < $var2) {
print "$var1\n";
$var1 += 1;
}
3.2.3 Until Loops
Until is negation of while. Here is an example:
#!/usr/bin/perl -w
$var1 = 1;
$var2 = 8;
until ($var2 < $var1) {
print "$var2\n";
$var2 -= 1;
}
4 Defining and using subroutines
34
Subroutines allow us to better structure our code, organize it and reuse it.
A subrutine will start with keyword sub. The following example shows how to define a
subroutine which calculates sum of two numbers:
10
Learn Perl by Example - Perl Handbook for Beginners - Basics of Perl Scripting Language
#!/usr/bin/perl -w
$var1 = 100;
$var2 = 200;
$result = 0;
$result = my_sum();
print "$result\n";
sub my_sum {
$tmp = $var1 + $var2;
return $tmp;
}
Note: Subroutines might have parameters. When passing parameters to subroutines, it will be stored in @_ array.
Do not confuse it with $_ which stores elements of an array in a loop.
5 Using file parameters (positional parameters)
Sometimes we need to transmit parameters to our script files.
@ARGV is an array reserved for parameters transmitted to files (default value of number of
arguments is set -1 if no parameters are transmitted.
#!/usr/bin/perl -w
if ($#ARGV < 2) {
print "You must have at least 3 parameters.\n";
}
else {
print "Your parameters are: @ARGV[0..$#ARGV]\n";
}
11
Learn Perl by Example - Perl Handbook for Beginners - Basics of Perl Scripting Language
6 Perl Regular Expressions
Perl Regular Expressions are a strong point of perl. You can ease your sysadmin job by learning
and using Perl Regex.
6.1 Searching for a string
The following example will search for This string in expresion $exp.
#!/usr/bin/perl -w
$exp = "This is a string";
if ($exp =~ /This/) {
print ("String Matches!\n");
}
6.2 Searching for a string using case insensitive
The next example will search for string this in expresion $exp using case insensitive (case will be
ignored in search).
#!/usr/bin/perl -w
$exp = "This is a string";
if ($exp =~ /tHis/i) {
print ("String Matches!\n");
}
6.3 Searching for a digit
The next example shows how to search for a digit in a string.
#!/usr/bin/perl -w
$exp = "This is 8 string";
if ($exp =~ /\d/) {
print ("String Matches!\n");
}
35
12
Learn Perl by Example - Perl Handbook for Beginners - Basics of Perl Scripting Language
6.4 Searching for 2 digits
The next example shows how to search for two digits in a string.
#!/usr/bin/perl -w
$exp = "This is 88 string";
if ($exp =~ /\d\d/) {
print ("String Matches!\n");
}
6.5 Searching for whitespaces
The next example shows you how to use regular expresions to search for whitespaces in a string.
#!/usr/bin/perl -w
$exp = "This is string";
if ($exp =~ /\s/) {
print ("String Matches!\n");
}
6.6 Searching for a string that begins with a pattern
The following example shows you how to use regular expressions to check if a string begins with
a keyword/string.
#!/usr/bin/perl -w
$exp = "This is string";
if ($exp =~ /^This/) {
print ("String Matches!\n");
}
6.7 Searching for a string that ends with a pattern
The following example shows you how to use regular expressions to check if a string ends with a
keyword/string.
13
Learn Perl by Example - Perl Handbook for Beginners - Basics of Perl Scripting Language
#!/usr/bin/perl -w
$exp = "This is string";
if ($exp =~ /string$/) {
print ("String Matches!\n");
}
6.8 Search for a digit with white space in front and after it
The next example shows how to use perl regex to search for a digit with white space in front and
after it.
#!/usr/bin/perl -w
$exp = "This 1 is string";
if ($exp =~ /\s\d\s/) {
print ("String Matches!\n");
}
6.9 Search for a blank line
The next example shows how to use Perl regex to search for a blank line.
#!/usr/bin/perl -w
$exp = "";
if ($exp =~ /^$/) {
print ("String Matches!\n");
}
6.10 Replace a pattern
The next example shows you how to use Perl regex to replace a text with a pattern.
#!/usr/bin/perl -w
$exp = "This is a string";
14

36
Learn Perl by Example - Perl Handbook for Beginners - Basics of Perl Scripting Language
if ($exp =~ s/This is/Test/) {
print ("$exp\n");
}

19. Write a perl script to implement associative array.

Perl Hashes -- A Guide to Associative


Arrays in Perl
Perl Articles
Hashes (associative arrays) are an extremely useful data structure in the Perl programming
language. A hash is a way of associating one set of values ("keys") with another set of values
("values"); forming a set of key-value pairs.

Let's take a simple example. Suppose we want a Perl structure to associate a collection of
people's names with their favorite hobbies.

We'll initialize the hash with some values, add another value, delete a value, access a key-value
pair and finally print the whole hash.

use strict;
use warnings;

sub main
{
# Declare and initialize a hash.
# In this example, both the keys
# and values are strings. But
# either or both could be numbers.
my %hobbies = (
'Roger' => 'hang gliding',
'Penny' => 'diving',
'Peter' => 'bus surfing',
'Richard' => 'collects spores and fungi',
'Clare' => 'competitive drinking',
'Lisa' => 'pole vaulting',
);

# Add another value to the hash.


37
$hobbies{'John'} = 'running';

# Delete a key-value pair from the hash.


delete $hobbies{'Peter'};

# Access a value.
print "Richard's hobby: ", $hobbies{'Richard'}, "\n";

# Let's print (display) the entire hash, just


# for fun. Note that we use a backslash on the
# hash's name. This gives us a reference to
# the hash, which we pass to Dumper() to
# format the hash as a string for display.
use Data::Dumper;
print Dumper(%hobbies);
}

main();

Richard's hobby: collects spores and fungi


$VAR1 = {
'Richard' => 'collects spores and fungi',
'John' => 'running',
'Lisa' => 'pole vaulting',
'Clare' => 'competitive drinking',
'Penny' => 'diving',
'Roger' => 'hang gliding'
};

Notice that when we access an individual (scalar) element of a hash, the % (hash) prefix
changes to a $ (scalar) prefix.
38
Iterating Over Hash Elements in Perl

Often we want to iterate through the different elements of a hash. There are two main ways to
do this.

 1. use while with each

 2. use foreach with keys

The first method is generally more efficient, but sometimes the second method leads to clearer
code.

It's very important to remember that the order of hash key-value pairs is not guaranteed to
remain constant. The key-value pairs could appear in any order at any time and could change
between runs of your program.

my %hobbies = (
'Roger' => 'hang gliding',
'Penny' => 'diving',
'Peter' => 'bus surfing',
'Richard' => 'collects spores and fungi',
'Clare' => 'competitive drinking',
'Lisa' => 'pole vaulting',
);

# Iterate over the hash using each.

print "nUsing each: \n";


while( my ($name, $hobby) = each %hobbies ) {
print "$name: $hobbyn";

39
}

print "nUsing keys:\n";

foreach my $name(keys %hobbies) {


my $hobby = $hobbies{$name};

print "$name: $hobby\n";


}

Using each:
Richard: collects spores and fungi
Lisa: pole vaulting
Clare: competitive drinking
Penny: diving
Peter: bus surfing
Roger: hang gliding

Using keys:
Richard: collects spores and fungi
Lisa: pole vaulting
Clare: competitive drinking
Penny: diving
Peter: bus surfing
Roger: hang gliding

40
Mainaining Order In Perl Hashes

Since hashes do not maintain an internal order for their contents, if we want an ordered hash,
we have to do some extra work.

The easiest option is often just to sort the hash's keys before we use them. Here's an example
using first a hash with strings for keys, then a hash with numbers for keys.

my %hobbies = (
'Roger' => 'hang gliding',
'Penny' => 'diving',
'Peter' => 'bus surfing',
'Richard' => 'collects spores and fungi',
'Clare' => 'competitive drinking',
'Lisa' => 'pole vaulting',
);

# Iterate over the hash keys. Use keys to get the


# keys as an array, sort the array,
# then iterate over the array with foreach.

foreach my $name(sort {$a cmp $b} keys %hobbies) {


my $hobby = $hobbies{$name};

print "$name: $hobby\n";


}

print "n"; # print a blank line.

# If the hash keys are numbers, you need


# to use <=> and not cmp to sort.

my %numbers = (
3 => 'three',
0 => 'zero',
2 => 'two',
1 => 'one',
41
);

foreach my $digit(sort {$a <=> $b} keys %numbers) {


my $number = $numbers{$digit};

print "$digit: $number\n";


}

Clare: competitive drinking


Lisa: pole vaulting
Penny: diving
Peter: bus surfing
Richard: collects spores and fungi
Roger: hang gliding

0: zero
1: one
2: two
3: three

Find Out How Many Entries Are In a Hash

You can get all the keys in a hash using keys, which returns all hash keys in an array.

If you want to know how many keys a hash has, just use this array as a scalar value (see Perl
Array: Size of an Array for more explanation).

The following displays the number of entries in a hash.

my %sky = (
42
'blue' => 'sun',
'grey' => 'rain',
'black' => 'night',
'yellow' => 'storm',
);

print "Entries: ", scalar(keys(%sky)), "\n";

20. Write a perl script to implement the regular expression as follows:


a). If a string contains any vowel, count the total number of vowels.
b). If a string starts with MCA and end with bw, print 1 else 0.
c). If string starts with 0 or any no. a’s, then print 1 else 0.

A regular expression is a string of characters that defines the pattern or patterns you are viewing.
The syntax of regular expressions in Perl is very similar to what you will find within other regular
expression.supporting programs, such as sed, grep, and awk.

The basic method for applying a regular expression is to use the pattern binding operators =~
and !~. The first operator is a test and assignment operator.

There are three regular expression operators within Perl.

 Match Regular Expression - m//

 Substitute Regular Expression - s///

 Transliterate Regular Expression - tr///

43
The forward slashes in each case act as delimiters for the regular expression (regex) that you are
specifying. If you are comfortable with any other delimiter, then you can use in place of forward
slash.

The Match Operator


The match operator, m//, is used to match a string or statement to a regular expression. For
example, to match the character sequence "foo" against the scalar $bar, you might use a statement
like this −
Live Demo

#!/usr/bin/perl

$bar = "This is foo and again foo";

if ($bar =~ /foo/) {

print "First time is matching\n";

} else {

print "First time is not matching\n";

$bar = "foo";

if ($bar =~ /foo/) {

print "Second time is matching\n";

} else {

print "Second time is not matching\n";

When above program is executed, it produces the following result −


First time is matching
Second time is matching

44
The m// actually works in the same fashion as the q// operator series.you can use any combination
of naturally matching characters to act as delimiters for the expression. For example, m{}, m(), and
m>< are all valid. So above example can be re-written as follows −

#!/usr/bin/perl

$bar = "This is foo and again foo";

if ($bar =~ m[foo]) {

print "First time is matching\n";

} else {

print "First time is not matching\n";

$bar = "foo";

if ($bar =~ m{foo}) {

print "Second time is matching\n";

} else {

print "Second time is not matching\n";

You can omit m from m// if the delimiters are forward slashes, but for all other delimiters you must
use the m prefix.

Note that the entire match expression, that is the expression on the left of =~ or !~ and the match
operator, returns true (in a scalar context) if the expression matches. Therefore the statement −

$true = ($foo =~ m/foo/);

will set $true to 1 if $foo matches the regex, or 0 if the match fails. In a list context, the match
returns the contents of any grouped expressions. For example, when extracting the hours, minutes,
and seconds from a time string, we can use −
45
my ($hours, $minutes, $seconds) = ($time =~ m/(\d+):(\d+):(\d+)/);

Match Operator Modifiers


The match operator supports its own set of modifiers. The /g modifier allows for global matching.
The /i modifier will make the match case insensitive. Here is the complete list of modifiers

Sr.No. Modifier & Description

1
i

Makes the match case insensitive.

2
m

Specifies that if the string has newline or carriage return characters, the ^ and $ operators will
now match against a newline boundary, instead of a string boundary.

3
o

Evaluates the expression only once.

4
s

Allows use of . to match a newline character.

5
x

Allows you to use white space in the expression for clarity.

6
g

Globally finds all matches.

7
cg

Allows the search to continue even after a global match fails.

Matching Only Once


There is also a simpler version of the match operator - the ?PATTERN? operator. This is basically
identical to the m// operator except that it only matches once within the string you are searching
between each call to reset.

For example, you can use this to get the first and last elements within a list −

46
Live Demo

#!/usr/bin/perl

@list = qw/food foosball subeo footnote terfoot canic footbrdige/;

foreach (@list) {

$first = $1 if /(foo.*?)/;

$last = $1 if /(foo.*)/;

print "First: $first, Last: $last\n";

When above program is executed, it produces the following result −


First: food, Last: footbrdige

Regular Expression Variables


Regular expression variables include $, which contains whatever the last grouping match
matched; $&, which contains the entire matched string; $`, which contains everything before the
matched string; and $', which contains everything after the matched string. Following code
demonstrates the result −
Live Demo

#!/usr/bin/perl

$string = "The food is in the salad bar";

$string =~ m/foo/;

print "Before: $`\n";

print "Matched: $&\n";

print "After: $'\n";

When above program is executed, it produces the following result −


47
Before: The
Matched: foo
After: d is in the salad bar

The Substitution Operator


The substitution operator, s///, is really just an extension of the match operator that allows you to
replace the text matched with some new text. The basic form of the operator is −
s/PATTERN/REPLACEMENT/;

The PATTERN is the regular expression for the text that we are looking for. The
REPLACEMENT is a specification for the text or regular expression that we want to use to replace
the found text with. For example, we can replace all occurrences of dog with cat using the
following regular expression −
Live Demo

#/user/bin/perl

$string = "The cat sat on the mat";

$string =~ s/cat/dog/;

print "$string\n";

When above program is executed, it produces the following result −


The dog sat on the mat

Substitution Operator Modifiers


Here is the list of all the modifiers used with substitution operator.

Sr.No. Modifier & Description

1
i

Makes the match case insensitive.

2
m

Specifies that if the string has newline or carriage return characters, the ^ and $ operators
will now match against a newline boundary, instead of a string boundary.

48
3
o

Evaluates the expression only once.

4
s

Allows use of . to match a newline character.

5
x

Allows you to use white space in the expression for clarity.

6
g

Replaces all occurrences of the found expression with the replacement text.

7
e

Evaluates the replacement as if it were a Perl statement, and uses its return value as the
replacement text.

The Translation Operator


Translation is similar, but not identical, to the principles of substitution, but unlike substitution,
translation (or transliteration) does not use regular expressions for its search on replacement
values. The translation operators are −

tr/SEARCHLIST/REPLACEMENTLIST/cds

y/SEARCHLIST/REPLACEMENTLIST/cds

The translation replaces all occurrences of the characters in SEARCHLIST with the corresponding
characters in REPLACEMENTLIST. For example, using the "The cat sat on the mat." string we
have been using in this chapter −
Live Demo

#/user/bin/perl

$string = 'The cat sat on the mat';

$string =~ tr/a/o/;

49
print "$string\n";

When above program is executed, it produces the following result −


The cot sot on the mot.

Standard Perl ranges can also be used, allowing you to specify ranges of characters either by letter
or numerical value. To change the case of the string, you might use the following syntax in place
of the uc function.

$string =~ tr/a-z/A-Z/;

Translation Operator Modifiers


Following is the list of operators related to translation.

Sr.No. Modifier & Description

1
c

Complements SEARCHLIST.

2
d

Deletes found but unreplaced characters.

3
s

Squashes duplicate replaced characters.

The /d modifier deletes the characters matching SEARCHLIST that do not have a corresponding
entry in REPLACEMENTLIST. For example −
Live Demo

#!/usr/bin/perl

$string = 'the cat sat on the mat.';

$string =~ tr/a-z/b/d;

50
print "$string\n";

When above program is executed, it produces the following result −


b b b.

The last modifier, /s, removes the duplicate sequences of characters that were replaced, so −
Live Demo

#!/usr/bin/perl

$string = 'food';

$string = 'food';

$string =~ tr/a-z/a-z/s;

print "$string\n";

When above program is executed, it produces the following result −


fod

More Complex Regular Expressions


You don't just have to match on fixed strings. In fact, you can match on just about anything you
could dream of by using more complex regular expressions. Here's a quick cheat sheet −

Following table lists the regular expression syntax that is available in Python.

Sr.No. Pattern & Description

1
^

Matches beginning of line.

2
$

Matches end of line.

3
.

Matches any single character except newline. Using m option allows it to match newline as

51
well.

4
[...]

Matches any single character in brackets.

5
[^...]

Matches any single character not in brackets.

6
*

Matches 0 or more occurrences of preceding expression.

7
+

Matches 1 or more occurrence of preceding expression.

8
?

Matches 0 or 1 occurrence of preceding expression.

9
{ n}

Matches exactly n number of occurrences of preceding expression.

10
{ n,}

Matches n or more occurrences of preceding expression.

11
{ n, m}

Matches at least n and at most m occurrences of preceding expression.

12
a| b

Matches either a or b.

13
\w

Matches word characters.

14
\W

52
Matches nonword characters.

15
\s

Matches whitespace. Equivalent to [\t\n\r\f].

16
\S

Matches nonwhitespace.

17
\d

Matches digits. Equivalent to [0-9].

18
\D

Matches nondigits.

19
\A

Matches beginning of string.

20
\Z

Matches end of string. If a newline exists, it matches just before newline.

21
\z

Matches end of string.

22
\G

Matches point where last match finished.

23
\b

Matches word boundaries when outside brackets. Matches backspace (0x08) when inside
brackets.

24
\B

Matches nonword boundaries.

53
25
\n, \t, etc.

Matches newlines, carriage returns, tabs, etc.

26
\1...\9

Matches nth grouped subexpression.

27
\10

Matches nth grouped subexpression if it matched already. Otherwise refers to the octal
representation of a character code.

28
[aeiou]

Matches a single character in the given set

29
[^aeiou]

Matches a single character outside the given set

The ^ metacharacter matches the beginning of the string and the $ metasymbol matches the end of
the string. Here are some brief examples.

# nothing in the string (start and end are adjacent)

/^$/

# a three digits, each followed by a whitespace

# character (eg "3 4 5 ")

/(\d\s) {3}/

# matches a string in which every

# odd-numbered letter is a (eg "abacadaf")

/(a.)+/

54
# string starts with one or more digits

/^\d+/

# string that ends with one or more digits

/\d+$/

Lets have a look at another example.


Live Demo

#!/usr/bin/perl

$string = "Cats go Catatonic\nWhen given Catnip";

($start) = ($string =~ /\A(.*?) /);

@lines = $string =~ /^(.*?) /gm;

print "First word: $start\n","Line starts: @lines\n";

When above program is executed, it produces the following result −


First word: Cats
Line starts: Cats When

Matching Boundaries
The \b matches at any word boundary, as defined by the difference between the \w class and the
\W class. Because \w includes the characters for a word, and \W the opposite, this normally means
the termination of a word. The \Bassertion matches any position that is not a word boundary. For
example −

/\bcat\b/ # Matches 'the cat sat' but not 'cat on the mat'

/\Bcat\B/ # Matches 'verification' but not 'the cat on the mat'

/\bcat\B/ # Matches 'catatonic' but not 'polecat'

/\Bcat\b/ # Matches 'polecat' but not 'catatonic'

Selecting Alternatives
55
The | character is just like the standard or bitwise OR within Perl. It specifies alternate matches
within a regular expression or group. For example, to match "cat" or "dog" in an expression, you
might use this −

if ($string =~ /cat|dog/)

You can group individual elements of an expression together in order to support complex matches.
Searching for two people’s names could be achieved with two separate tests, like this −

if (($string =~ /Martin Brown/) || ($string =~ /Sharon Brown/))

This could be written as follows

if ($string =~ /(Martin|Sharon) Brown/)

Grouping Matching
From a regular-expression point of view, there is no difference between except, perhaps, that the
former is slightly clearer.

$string =~ /(\S+)\s+(\S+)/;

and

$string =~ /\S+\s+\S+/;

However, the benefit of grouping is that it allows us to extract a sequence from a regular
expression. Groupings are returned as a list in the order in which they appear in the original. For
example, in the following fragment we have pulled out the hours, minutes, and seconds from a
string.

my ($hours, $minutes, $seconds) = ($time =~ m/(\d+):(\d+):(\d+)/);

As well as this direct method, matched groups are also available within the special $x variables,
where x is the number of the group within the regular expression. We could therefore rewrite the
preceding example as follows −
56
Live Demo

#!/usr/bin/perl

$time = "12:05:30";

$time =~ m/(\d+):(\d+):(\d+)/;

my ($hours, $minutes, $seconds) = ($1, $2, $3);

print "Hours : $hours, Minutes: $minutes, Second: $seconds\n";

When above program is executed, it produces the following result −


Hours : 12, Minutes: 05, Second: 30

When groups are used in substitution expressions, the $x syntax can be used in the replacement
text. Thus, we could reformat a date string using this −
Live Demo

#!/usr/bin/perl

$date = '03/26/1999';

$date =~ s#(\d+)/(\d+)/(\d+)#$3/$1/$2#;

print "$date\n";

When above program is executed, it produces the following result −


1999/03/26

The \G Assertion
The \G assertion allows you to continue searching from the point where the last match occurred.
For example, in the following code, we have used \G so that we can search to the correct position
and then extract some information, without having to create a more complex, single regular
expression −
57
Live Demo

#!/usr/bin/perl

$string = "The time is: 12:31:02 on 4/12/00";

$string =~ /:\s+/g;

($time) = ($string =~ /\G(\d+:\d+:\d+)/);

$string =~ /.+\s+/g;

($date) = ($string =~ m{\G(\d+/\d+/\d+)});

print "Time: $time, Date: $date\n";

When above program is executed, it produces the following result −


Time: 12:31:02, Date: 4/12/00

The \G assertion is actually just the metasymbol equivalent of the pos function, so between regular
expression calls you can continue to use pos, and even modify the value of pos (and therefore \G)
by using pos as an lvalue subroutine.

Regular-expression Examples
Literal Characters
Sr.No. Example & Description

1
Perl

Match "Perl".

Character Classes
Sr.No. Example & Description

1
[Pp]ython

58
Matches "Python" or "python"

2
rub[ye]

Matches "ruby" or "rube"

3
[aeiou]

Matches any one lowercase vowel

4
[0-9]

Matches any digit; same as [0123456789]

5
[a-z]

Matches any lowercase ASCII letter

6
[A-Z]

Matches any uppercase ASCII letter

7
[a-zA-Z0-9]

Matches any of the above

8
[^aeiou]

Matches anything other than a lowercase vowel

9
[^0-9]

Matches anything other than a digit

Special Character Classes


Sr.No. Example & Description

1
.

Matches any character except newline

2
\d

59
Matches a digit: [0-9]

3
\D

Matches a nondigit: [^0-9]

4
\s

Matches a whitespace character: [ \t\r\n\f]

5
\S

Matches nonwhitespace: [^ \t\r\n\f]

6
\w

Matches a single word character: [A-Za-z0-9_]

7
\W

Matches a nonword character: [^A-Za-z0-9_]

Repetition Cases
Sr.No. Example & Description

1
ruby?

Matches "rub" or "ruby": the y is optional

2
ruby*

Matches "rub" plus 0 or more ys

3
ruby+

Matches "rub" plus 1 or more ys

4
\d{3}

Matches exactly 3 digits

5
\d{3,}

60
Matches 3 or more digits

6.
\d{3,5}

Matches 3, 4, or 5 digits

Nongreedy Repetition
This matches the smallest number of repetitions −

Sr.No. Example & Description

1
<.*>

Greedy repetition: matches "<python>perl>"

2
<.*?>

Nongreedy: matches "<python>" in "<python>perl>"

Grouping with Parentheses


Sr.No. Example & Description

1
\D\d+

No group: + repeats \d

2
(\D\d)+

Grouped: + repeats \D\d pair

3
([Pp]ython(, )?)+

Match "Python", "Python, python, python", etc.

Backreferences
This matches a previously matched group again −

Sr.No. Example & Description

1
([Pp])ython&\1ails

Matches python&pails or Python&Pails

61
2
(['"])[^\1]*\1

Single or double-quoted string. \1 matches whatever the 1st group matched. \2 matches
whatever the 2nd group matched, etc.

Alternatives
Sr.No. Example & Description

1
python|perl

Matches "python" or "perl"

2
rub(y|le))

Matches "ruby" or "ruble"

3
Python(!+|\?)

"Python" followed by one or more ! or one ?

Anchors
This need to specify match positions.

Sr.No. Example & Description

1
^Python

Matches "Python" at the start of a string or internal line

2
Python$

Matches "Python" at the end of a string or line

3
\APython

Matches "Python" at the start of a string

4
Python\Z

Matches "Python" at the end of a string

5
\bPython\b

62
Matches "Python" at a word boundary

6
\brub\B

\B is nonword boundary: match "rub" in "rube" and "ruby" but not alone

7
Python(?=!)

Matches "Python", if followed by an exclamation point

8
Python(?!!)

Matches "Python", if not followed by an exclamation point

Special Syntax with Parentheses


Sr.No. Example & Description

1
R(?#comment)

Matches "R". All the rest is a comment

2
R(?i)uby

Case-insensitive while matching "uby"

3
R(?i:uby)

Same as above

4
rub(?:y|le))

Group only without creating \1 backreference

21. Write an html code to call a perl script from cgi-bin.

What is Perl/CGI? Perl is a simple programming language. It doesn't have to be used on the web, it can run
locally on your computer, but it's popular for use on the web. When it's used on the web the programs are called Perl
CGI, because CGI is the way that Perl talks to your web browser. Perl can be used to do things like rotate banners,
generate text & HTML on the fly, set cookies, and provide shopping carts.

In theory it's pretty simple:

1. Write your Perl program in a text editor, and save it with a .cgi or .pl extension.

63
2. Upload it to your web server.

3. Run it in one of three ways:

o Link to it. (e.g., <a href=myscript.cgi>Click to run my program</a>)

o Embed it into your HTML file (e.g, <p><!--#include virtual="myscript.cgi"-->)

o Use it as the action item of a form (e.g., <form action=myscript.cgi>)

But if you tried this already it probably didn't work, which is probably why you're here. That's good, we'll show you a
whole bunch of ways you could have gone wrong, and then you'll be able to get your script working. When I started out
I had a hard time finding good resources. If I had found a page as useful as this one I wouldn't have had to write it. Most
of the Perl tutorials I found omitted crucial information, failed to give an overview or put things into context, had
explanations that were either too long or not long enough, spread out the information over several pages instead of
putting everything in one spot, and had all manner of annoying blinking advertisements, I wrote this tutorial to provide
an alternative, and I wrote it to answer the question, "What kind of resource do I wish I had when I was starting out?"
So I think you're in good hands.

By the way, I use the terms "program" and "script" in this tutorial interchangeably. They're the same thing.

And now for the good stuff.

Steps to creating a successful Perl CGI script

1. Get some info from your webhost. Your webhost is the company that has your website on their servers. Having a webhost which
properly supports Perl is half the battle. We use Dreamhost, and if you use them then everything on this page should work well for
you, and you can skip this step and go to the next one. If your host isn't Dreamhost then you'll need to ask them some questions:

 Do you support Perl? (If not, stop here and get another host that does, like Dreamhost.)

 Can I use the standard shebang line? #!/usr/bin/perl

 Can I use the .cgi extension or do I have to use .pl?

 Can my files go anywhere, or do they have to go in a cgi-bin directory?

 What permissions do I need to set for the script and for the directory it's in?

 Where are my server error logs located?

We'll use the answers to these questions in the steps below.

2. Write your script with a text editor. Many Windows text editors put carriage returns at the ends of lines which can cause Perl
scripts to fail. Any of these will solve that problem:

 Use Unix. Use a text editor in the Unix shell such as pico

 Use a Mac. On Mac OS X, use TextEdit (and choose Format > Make Plain Text) and make sure to save your file without
the ".txt" on the end. Or, use the built-in editor in the Transmit FTP/SFTP file transfer software.

 Windows: Neither NotePad nor WordPad saves in the proper format, even if you choose Text. (It's not the right kind of
Text.) You'll need to either log into the Unix shell and use an editor like pico, or find some other text editor for Windows
that saves in the right format, such as TextPad.

3. Your first script. Type this in (or copy & paste it) into a new file:
#!/usr/bin/perl -w

print "Content-type: text/html\n\n";

64
print "Hello, world";
4. Save your file with a .cgi extension (e.g., "hello.cgi"). Some webhosts might require a .pl extension, check with them to find out.
With Dreamhost you can use either .cgi or .pl.

5. Upload your file. Check with your webhost to see if you have to put it in a special place. Some hosts require that it go in the cgi-
bin directory. If your host is Dreamhost you can put it anywhere.

6. Use ASCII mode for the upload. If you upload in binary mode it won't work.

7. Set permissions. You need to set permissions, which is a fancy way of telling the server that you're authorizing the program to run
there. You do this with the Unix command line. (See more about the Unix command line below if it's unfamiliar to you.) Check with
your webhost to see what permissions they require. At Dreamhost you set permissions with chmod 755 for both your file and the
directory it's in. If you rename the file you need to set its permissions again. If you delete the file from the server and then upload a
fresh copy you need to set its permissions again. If you move it to another directory, you have to set the permissions at that new
directory.

9. Run the script. There are four different ways to do this:

 As a url (link to the file, e.g., http://mydomain.com/hello.cgi, or type it into a browser window)

 Embedded anywhere in a web page: <!--#include virtual="hello.cgi"-->


See note below.

 As the action for a FORM: <FORM ACTION="hello.cgi" METHOD=POST>

 At the Unix command line: perl hello.cgi

Notes:
If your script is in a cgi-bin directory, don't forget to include that when typing the url.
If this didn't work then see our troubleshooting section.
Embedding the reference in a web page:
The whole page might look like this:
<HTML>
<BODY>
<P>Here's the output from my program:
<!--#include virtual="hello.cgi"-->
</P>
</BODY>
</HTML>
To get the server to run the CGI from your HTML page you also have to do one of the following:

 Title the page with a .shtml extension (e.g., hello.shtml), OR

 Add this line to the .htaccess file that goes at the top level of your website (same level as your index.html file):

o AddHandler server-parsed .html

If you don't already have an .htaccess file, then create one and have the AddHandler bit be the only line.

22. Implement the following with regular expression in Perl:


a). a*bc
b). a* at least 2 b’s
c). a*exactly 3 b’s

65
23. A simple File operation using Perl.
Summary: in this tutorial, you will learn how to write text to file using the print() function. We will
give you several examples of writing to files.
Before going forward with this tutorial, you need to know how to open a file in Perl. If you want to read
from a file, follow the reading from a file tutorial.

In order to write to a file, first you need to open the file for writing as follows:

1 open(FH, '>', $filename) or die $!;


If the file with filename $filename does not exist, the new file will be created.
Next, you use the print() function to write data into file as follows:
1 print FH $str;
You must put space between print() , filehandle FH and $str variable. The $str variable holds data that is
written to the file. Notice that if you write to a file that contains content, Perl will truncate its content.
As always, you should close the filehandle when you are no longer use it.

1 close(FH);
Putting it all together.

1 #!/usr/bin/perl
2 use warnings;
3 use strict;
4
5 my $str = <<END;
6 This is the sample text
7 that is used to write to file
8 END
9
10 my $filename = 'c:\temp\test3.txt';
11
12 open(FH, '>', $filename) or die $!;
13
14 print FH $str;
15
16 close(FH);
17
18 print "Writing to file successfully!\n";
The following example demonstrates how to read the content of one file and write it another file.

1 #!/usr/bin/perl
2 use warnings;
3 use strict;
4
5 my $src = 'C:\temp\test3.txt';
6 my $des = 'C:\temp\test4.txt';
7
8 # open source file for reading
9 open(SRC,'<',$src) or die $!;
10
11 # open destination file for writing
12 open(DES,'>',$des) or die $!;
13
14 print("copying content from $src to $des\n");
15
16 while(<SRC>){
17 print DES $_;
18 }
19
20 # always close the filehandles
66
21 close(SRC);
22 close(DES);
23
24 print "File content copied successfully!\n";
How it works.

 We copied content from the file source file c:\temp\test3.txt to destination file c:\temp\test4.txt .
 First, we opened source file c:\temp\test3.txt for reading and destination file c:\temp\test4.txt for
writing using the open() function.
 Second, we read the source file line by line. For each line we read from the source file, we used
the print() function to write it to the destination file.
 Third, we closed the filehandles using the close() function.
Here is the output of the program.

If you want to pass arguments to the program via command-line, just replace the code at line 6 and 7 by
the following code:

1 my $src = shift @ARGV;


2 my $des = shift @ARGV;
When the program is invoked, the command-line arguments are stored in a special array @ARGV . We
used the shift() function to get the source and destination files from the array @ARGV .
Now, you can call the program and pass the command-line arguments as follows:

1 C:\>perl c:\perlws\perl-write-file2.pl c:\temp\test3.txt c:\temp\test4.txt


2 copying content from c:\temp\test3.txt to c:\temp\test4.txt
3 File content copied successfully!
4
5 C:\>
The perl-write-file2.pl is the name of the Perl program.
In this tutorial, we have shown you step by step how to write data to file by using the print() function

67
68
Client Server
Programming

Q 1 A. IPv4 Addressing and Subnetting


Given an IP address and network mask, determine other information about the IP address
such as:
• Network address
• Network broadcast address
• Total number of host bits
• Number of hosts
Given : IP Address :- 70.12.100.132
Network Mask :- 255.255.255.192
To find: Network address :-First address = (any address) AND (network mask)
= 70.12.100.132 AND 255.255.255.192
= 70.12.100.128
Network broadcast address :-Last address = (any address) OR [NOT (network mask)]
= 70.12.100.132 OR 0.0.0.63
= 70.12.100.191
Total number of host bits:- 32-26 = 6 bits
Number of hosts :-N 232- nin which n is the prefix length and N is the number of addresses in the block.
= 26= 64 hosts
Q 1 B. Given an IP address, network mask, and subnetwork mask, determine other information
about the IP address such as:
• The subnet address of this subnet
• The broadcast address of this subnet
• The range of host addresses for this subnet
• The maximum number of subnets for this subnet mask
• The number of hosts for each subnet
• The number of subnet bits
• The number of this subnet
Example:--
69
Consider class a ip address 10.0.0.0 the its default subnet mask is 255.0.0.0 which means we can represent it
by
10.0.0.0/8 the “/” factor indicates the CIDR value
If we decide to block some of the bits to minimize no of host in any given subnet then that technique is
called as
variable length subnet masking (VLSM)
Let us see the example where we borrow some bits from host part and minimize the count to an extent and
create small independent N/W’s of big N/W .Or even we can say that we want 8 N/W out of 1 big n/w then
we
will observer following N/W created with their VLSM 255.224.0.0 and no of hosts per subnet 221=2097152 -
2=2097150
ID Subnetwork Broadcast First Host Last Host
1 10.0.0.0 10.31.255.255 10.0.0.1 10.31.255.254
2 10.32.0.0 10.63.255.255 10.32.0.1 10.63.255.254
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 3
3 10.64.0.0 10.95.255.255 10.64.0.1 10.95.255.254
4 10.96.0.0 10.127.255.255 10.96.0.1 10.127.255.254
5 10.128.0.0 10.159.255.255 10.128.0.1 10.159.255.254
6 10.160.0.0 10.191.255.255 10.160.0.1 10.191.255.254
7 10.192.0.0 10.223.255.255 10.192.0.1 10.223.255.254
8 10.224.0.0 10.255.255.255 10.224.0.1 10.255.255.254
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 4

Practical No.2
Q2) USE OF PING AND TRACERT / TRACEROUTE AND ARP UTILITIES
Diagnostic commands help you detect TCP/IP networking problems. Some of the diagnostic
commandsarearp,
hostname,ipconfig,,netstat, ping, route, and tracert .
i) arp
This diagnostic command displays and modifies the IP-to-Ethernet or Token Ring physical address
translation
tables used by the Address Resolution Protocol (ARP).
Syntax
arp -a [inet_addr] [-N [if_addr]]
arp -dinet_addr [if_addr]
arp -sinet_addrether_addr [if_addr]
Parameters
-a Displays current ARP entries by querying TCP/IP. If inet_addr is specified, only the IP and physical
addresses for the specified host are displayed.
-d Deletes the entry specified by inet_addr
-s Adds an entry in the ARP cache to associate the IP address inet_addrwith the physical address ether_addr.
The physical address is given as 6 hexadecimal bytes separated by hyphens. The IP address is specified using
dotted decimal notation. The entry is static. It will not be automatically removed from the cache after the
timeout expires and will not exist after a reboot of your computer.
-N [if_addr] Displays the ARP entries for the network interface specified by if_addr. ether_addr Specifies a
physical address. if_addr Specifies, if present, the IP address of the interface whose address translation table
should be modified. If not present, the first applicable interface will be used. inet_addr Specifies an IP
address
in dotted decimal notation.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 5
ii) hostname
70
This diagnostic command prints the name of the host on which the command is used.
Syntax
hostname -- This command has no parameters.
iii) ipconfig
This diagnostic command displays all current TCP/IP network configuration values. This command is useful
on
computers running DHCP because it enables users to determine which TCP/IP configuration values have
been
configured by DHCP. If you enter only ipconfigwithout parameters, the response is a display of all of the
current TCP/IP configuration values, including IP address, subnet mask, and default gateway.
Syntax
ipconfig [/all | /renew [adapter] | /release [adapter]]
Parameters
all Produces a full display. Without this switch, ipconfig displays only the IP address, subnet mask, and
default
gateway values for each network card.
renew [adapter] Renews DHCP configuration parameters. This option is available only on computers
running
the DHCP Client service. To specify an adapter name, type the adapter name that appears when you use
ipconfig without parameters.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 6
release [adapter] Releases the current DHCP configuration. This option disables TCP/IP on the local
computer
and is available only on DHCP clients. To specify an adapter name, type the adapter name that appears when
you use ipconfig without parameters.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 7
iv) netstat
This diagnostic command displays protocol statistics and current TCP/IP network connections.
Syntax
netstat [-a] [-e][-n][-s] [-p protocol] [-r] [interval]
Parameters
-a Displays all connections and listening ports; server connections are usually not shown. -e Displays
Ethernet
statistics. This can be combined with the -s option. -n Displays addresses and port numbers in numerical
form
(rather than attempting name lookups). -s Displays per-protocol statistics. By default, statistics are shown for
TCP, UDP, ICMP, and IP; the -p option can be used to specify a subset of the default.
-p protocol Shows connections for the protocol specified.
-r Displays the contents of the routing table.
Interval Redisplays selected statistics, pausing interval seconds between each display.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 8
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 9
v) ping
This diagnostic command verifies connections to one or more remote computers.
Syntax
ping [-t] [-a] [-n count] [-l length] [-f] [-i ttl] [-v tos] [-r count] [-s count]
[[-j host-list] | [-k host-list]] [-w timeout] destination-list
Parameters
-t Pings the specified host until interrupted.
-a Resolves addresses to host names.
-n count Sends the number of ECHO packets specified by count. The default is 4.
-l length Sends ECHO packets containing the amount of data specified by length. The default is 64 bytes; the
71
maximum is 8192.
-f Sends a Do Not Fragment flag in the packet. The packet will not be fragmented by gateways on the route.
-ittl Sets the time to live field to the value specified by ttl.
-v tos Sets the type of service field to the value specified by tos.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 10
-r count Records the route of the outgoing packet and the returning packet in the record route field. A
minimum
of 1 to a maximum of 9 hosts must be specified by count.
-s count Specifies the timestamp for the number of hops specified by count.
-j host-list Routes packets via the list of hosts specified by host-list. Consecutive hosts can be separated by
intermediate gateways (loose source routed). The maximum number allowed by IP is 9.
-k host-list Routes packets via the list of hosts specified by host-list. Consecutive hosts cannot be separated
by
intermediate gateways (strict source routed). The maximum number allowed by IP is 9.
-w timeout Specifies a timeout interval in milliseconds.
destination-list Specifies the remote hosts to ping.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 11
vi) route
This diagnostic command manipulates network routing tables.
Syntax
route [-f] [command [destination] [MASK netmask] [gateway] [METRIC metric]]
Parameters
-f Clears the routing tables of all gateway entries. If this parameter is used in conjunction with one of the
commands, the tables are cleared prior to running the command.
command Specifies one of four commands.
Command Purpose
print Prints a route
add Adds a route
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 12
Command Purpose
delete Deletes a route
change Modifies an existing route
destination Specifies the host to send command.
MASK Specifies, if present, that the next parameter be interpreted as the netmask parameter.
netmask Specifies, if present, the subnet mask value to be associated with this route entry. If not present, this
parameter defaults to 255.255.255.255.
gateway Specifies the gateway.
METRIC Specifies the route metric (cost) for the destination.
vii ) tracert
This diagnostic utility determines the route taken to a destination by sending Internet Control Message
Protocol
(ICMP) echo packets with varying time-to-live (TTL) values to the destination. Each router along the path is
required to decrement the TTL on a packet by at least 1 before forwarding it, so the TTL is effectively a hop
count. When the TTL on a packet reaches 0, the router is supposed to send back an ICMP Time Exceeded
message to the source computer.
Tracert determines the route by sending the first echo packet with a TTL of 1 and incrementing the TTL by
1
on each subsequent transmission until the target responds or the maximum TTL is reached. The route is
determined by examining the ICMP Time Exceeded messages sent back by intermediate routers. Notice that
some routers silently drop packets with expired TTLs and will be invisible to tracert.
Syntax
tracert[-d] [-h maximum_hops] [-j host-list] [-w timeout] target_name
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
72
Page | 13
Parameters
-d Specifies not to resolve addresses to host names.
-h maximum_hops Specifies maximum number of hops to search for target.
-j host-list Specifies loose source route along host-list.
-w timeout Waits the number of milliseconds specified by timeout for each reply.
target_name Name of the target host.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 14
Practical No.3
Q3) Configure IP static routing.
Static Route Configuration
Static Route
1.Static routing method is most trusted by a router.
2.Static routing is not really a routing protocol.
3.Static routes do not dynamically adapt to network changes, are not particularly scalable,
and require manual updating to reflect changes.
Static routing has the following advantages
1. There is no bandwidth usage between routers, which means you could possibly save
money on WAN links.
2. There is no overhead on the router CPU, which means you could possibly buy a cheaper
router than you would use if you were using dynamic routing.
3. It adds security because the administrator can choose to allow routing access to certain
networks only.
Static routing has the following disadvantages
1. Static routes don’t dynamically adapt to network change.
2. If a network is added to the internetwork, the administrator has to add a route to it on
all routers—by hand.
3. It’s not feasible in large networks because maintaining it would be a full-time job in
itself.
4. With static routing, as your network grows, it can be difficult just keep adding static
routes makes sure everybody can still get everything.
5. The administrator must really understand the internetwork and how each router is
connected in order to configure routes correctly.
There are two different styles to configure an “ip route” command:
1. Using a next hop IP address
2. Using an outgoing interface
Syntax:
ip route [destination_network] [mask] [next_hop_address or
exit_interface][administrative_distance][permanent]
We can break the above syntax:
ip route [destination_network] [mask] [next_hop_address]
ip route [destination_network] [mask] [exit_interface/next_hop_address]
network - the destination network
mask - is the subnet mask for that network
address - IP address of the next hop router
interface - the interface the traffic is to leave by
distance - (optional) the administrative distance of the route
Example: 1
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 15
Router(config)#ip route 10.0.0.0 255.0.0.0 131.108.3.4 110
10.0.0.0 is the destination network/remote destination network/final destination.
255.0.0.0 is the subnet mask for that network and 131.108.3.4 is the next hop ip.
110 is the administrative distance.
The AD is the trustworthiness of a route, where 0 is best and 255 is worst.
The default administrative distance of static route is 1.
Example: 2
Router0(config)#ip route 10.10.3.0 255.255.255.0 10.10.0.3(using next hop ip)
Router0(config)#ip route 10.10.3.0 255.255.255.0 fa0/1(using exit interface)
We can use the exit interface instead of next hop ip address. Functionally, next hop ip and
exit interface work exactly the same. But, it is preferred to use next_hop_ip_address for
troubleshoot easier way.
Why Static Route Need Tutorial
73
There is a golden rule of routing: If the router cannot find the route, it will drop the packet and send
an
ICMP "Destination Unreachable" message to the original sender.
The only way a router knows about a route (destination network) is one of 3 ways:
1.It is directly connected to that network
2.It learns about the remote (not directly connected) route from another router - it does this by both
routers speaking the same routing protocol.
3.An administrator MANUALLY enters a static route in the router. The problem with #3 is that you
have to enter EVERY route on EVERY router. This very quickly becomes tedious and is prone to
error.
Static routing is a good choice IF the following are true:
1.You only have a few routers.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 16
2.You have NO redundant paths (routes).
3.You don't want the routers to use up precious bandwidth by using routing protocols.
Above discussion taken from "Chrys Thorsen", from facebook of "Zambia CCNA Study
Group".
Putting two IP addresses, subnet mask and default gateway to PC1 and PC2.
Click PC1/ Desktop/IP Configuration /Static
Click PC2/ Desktop/IP Configuration /Static
In this scenario, PC1 can ping router R1’s f0/0(10.1.0.1/24) interface and f0/1(10.2.0.1/24)
interface.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 17
But PC1 can not ping router R2’s f0/1(10.2.0.2/24) interface.
Configure R1 rourer.
Router>enable
Router#conf t
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#host R1
R1(config)#int f0/0
R1(config-if)#ip addess 10.1.0.1 255.255.255.0
R1(config-if)#no shut
R1(config-if)#int f 0/1
R1(config-if)#ip add 10.2.0.1 255.255.255.0
R1(config-if)#no shut
R1(config-if)#^Z
R1#
Configure R2 rourer.
Router>en
Router>enable
Router#conf t
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#host R2
R2(config)#int f0/1
R2(config-if)#ip address 10.2.0.2 255.255.255.0
R2(config-if)#no shut
R2(config-if)#int f0/0
R2(config-if)#ip address 10.3.0.1 255.255.255.0
R2(config-if)#no shut
R2(config-if)#^Z
74
R2#
Let's ping from PC1 to R1’s interfaces.
PC>ping 10.1.0.1
Pinging 10.1.0.1 with 32 bytes of data:
Reply from 10.1.0.1: bytes=32 time=40ms TTL=255
Reply from 10.1.0.1: bytes=32 time=20ms TTL=255
Reply from 10.1.0.1: bytes=32 time=20ms TTL=255
Reply from 10.1.0.1: bytes=32 time=20ms TTL=255
PC>
PC>ping 10.2.0.1
Pinging 10.2.0.1 with 32 bytes of data:
Reply from 10.2.0.1: bytes=32 time=20ms TTL=255
Reply from 10.2.0.1: bytes=32 time=20ms TTL=255
Reply from 10.2.0.1: bytes=32 time=12ms TTL=255
Reply from 10.2.0.1: bytes=32 time=4ms TTL=255
PC>
Let's ping from PC1 to R2's interfaces.
Let's ping from PC1 to R2's interfaces.PC>ping 10.2.0.2
Pinging 10.2.0.2 with 32 bytes of data:
Request timed out.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 18
Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),
PC>
Ping is a echo request goes to the router and then router sends the echo reply back to the pc.
Why PC1 can not ping router R2?
Let’s see R1’s routing table.
R1#sh ip rou
Gateway of last resort is not set
10.0.0.0/24 is subnetted, 2 subnets
C 10.1.0.0 is directly connected, FastEthernet0/0
C 10.2.0.0 is directly connected, FastEthernet0/1
R1#
Let's see R2's routing table.
R2#sh ip route
Gateway of last resort is not set
10.0.0.0/24 is subnetted, 2 subnets
C 10.2.0.0 is directly connected, FastEthernet0/1
C 10.3.0.0 is directly connected, FastEthernet0/0
R2#
This R1 router knows about two routes. It knows about the 10.1.0.0/24 and 10.2.0.0/24 networks.
When pings from PC1, router R1 knows how to send packet to router R2’s interface
f0/1(10.2.0.2/24).
So, packet actually arrives at router R2’s f0/1 interface. The problem is, echo-reply never returns.
Router R2 knows about 10.2.0.0.0/8 and 10.3.0.0/8 networks. When router R2 tries to send packet
back to 10.1.0.1/24 network, to PC1(10.1.0.2), he does not has 10.1.0.0/24 network in his routing
table. So R2 has no idea about 10.1.0.0/24 network.
So, if we put a static route(10.1.0.0/24) to router R2, whole thing start working.
R2#conf t
R2(config)#ip route 10.1.0.0 255.255.255.0 10.2.0.1
R2(config)#
Now ping will work.
75
Let's ping from PC1 to R2's interfaces.
PC>ping 10.2.0.2
Pinging 10.2.0.2 with 32 bytes of data:
Reply from 10.2.0.2: bytes=32 time=40ms TTL=254
Reply from 10.2.0.2: bytes=32 time=40ms TTL=254
Reply from 10.2.0.2: bytes=32 time=40ms TTL=254
Reply from 10.2.0.2: bytes=32 time=40ms TTL=254
PC>
Static Route Lab with Packet Tracer Tutorial
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 19
Static Route Lab with Packet Tracer
Configure Static Route on Cisco Routers with following information:
Network: 172.16.0.0/16, 192.168.0.0/24, 10.0.0.0/8
Gateway Address: 172.16.0.1/16, 192.168.0.1/24, 10.0.0.1/8
Putting three IP addresses, subnet mask and default gateway to three PCs.
Click PC1/ Desktop/IP Configuration /Static
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 20
Click PC2/ Desktop/IP Configuration /Static
Click PC3/ Desktop/IP Configuration /Static
Configure Router R1
Router>en
Router#conf t
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#host R1
R1(config)#int fa 0/1
R1(config-if)#ip address 172.16.0.1 255.255.0.0
R1(config-if)#no shut
R1(config-if)#int fa 1/0
R1(config-if)#ip address 192.168.0.1 255.255.255.0
R1(config-if)#no shut
R1(config)#int fa 0/0
R1(config-if)#ip address 100.0.0.1 255.255.255.252
R1(config-if)#no shut
R1(config-if)#exit
R1(config)#
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 21
Configure Router R2
Router>en
Router#conf t
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#host R2
R2(config)#int fa 0/0
R2(config-if)#ip address 100.0.0.2 255.255.255.252
R2(config-if)#no shut
R2(config)#int fa 0/1
R2(config-if)#ip address 10.0.0.1 255.0.0.0
R2(config-if)#no shut
R2(config-if)#exit
R2(config)#
Configure Static Route to router R1
Go to config mode, type ip route command, the subnet number, followed by the mask, and next hop ip
address.
R1#conf t
76
Enter configuration commands, one per line. End with CNTL/Z.
R1(config)#ip route 10.0.0.0 255.0.0.0 100.0.0.2
R1(config)#^Z
See routing table of router R1
R1#show ip route
Gateway of last resort is not set
S 10.0.0.0/8 [1/0] via 100.0.0.2
100.0.0.0/30 is subnetted, 1 subnets
C 100.0.0.0 is directly connected, FastEthernet0/0
C 172.16.0.0/16 is directly connected, FastEthernet0/1
C 192.168.0.0/24 is directly connected, FastEthernet1/0
R1#
Note a static route added to the routing table. The character S means static route.
It references 10.0.0.0 subnet and it says to get there via100.0.0.2. via means that
the next hop router’s IP address.
Now check IP connectivity
Click PC-1/ Desktop/Command Prompt
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 22
PC>ping 10.0.0.2
Pinging 10.0.0.2 with 32 bytes of data:
Request timed out.
Request timed out.
Request timed out.
Request timed out.
Ping statistics for 10.0.0.2:
Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),
PC>
However PC-1 can’t ping PC-3 right now, the ping fails.
See routing table of router R2
R2#show ip route
Gateway of last resort is not set
C 10.0.0.0/8 is directly connected, FastEthernet0/1
100.0.0.0/30 is subnetted, 1 subnets
C 100.0.0.0 is directly connected, FastEthernet0/0
R2#
The output confirms that R2 does not have route to reach subnet 172.16.0.2/16, 192.168.0.2/24 or PC-1, PC-
2.
As a result, if PC-1 tries to ping PC-3 or PC-3 tries to ping PC-1 right now, the
ping will fail.
So, we have to add a routing protocol(in this case, static route) that points PC-3’s
subnet namely 10.0.0.0/8.
In this way we will tell R1 how to forward packet to 10.0.0.0/8 subnet.
The packet arrives at R2, R2 has a directly connected route PC-3’s subnet.
Configure Static Route to router R2
R2#conf t
Enter configuration commands, one per line. End with CNTL/Z.
R2(config)#ip route 172.16.0.0 255.255.0.0 100.0.0.1
R2(config)#ip route 192.168.0.0 255.255.255.0 100.0.0.1
R2(config)#^Z
R2#
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 23
Now,see routing table of router R2
R2#show ip route
Gateway of last resort is not set
C 10.0.0.0/8 is directly connected, FastEthernet0/1
77
100.0.0.0/30 is subnetted, 1 subnets
C 100.0.0.0 is directly connected, FastEthernet0/0
S 172.16.0.0/16 [1/0] via 100.0.0.1
S 192.168.0.0/24 [1/0] via 100.0.0.1
R2#
Now check IP connectivity
Click PC-1/ Desktop/Command Prompt
PC>ping 10.0.0.2
Pinging 10.0.0.2 with 32 bytes of data:
Reply from 10.0.0.2: bytes=32 time=12ms TTL=126
Reply from 10.0.0.2: bytes=32 time=13ms TTL=126
Reply from 10.0.0.2: bytes=32 time=12ms TTL=126
Reply from 10.0.0.2: bytes=32 time=20ms TTL=126
Ping statistics for 10.0.0.2:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 12ms, Maximum = 20ms, Average = 14ms
PC>
We can reach 10.0.0.0 network.
Click PC-2/ Desktop/Command Prompt
PC>ping 10.0.0.2
Pinging 10.0.0.2 with 32 bytes of data:
Reply from 10.0.0.2: bytes=32 time=12ms TTL=126
Reply from 10.0.0.2: bytes=32 time=14ms TTL=126
Reply from 10.0.0.2: bytes=32 time=24ms TTL=126
Reply from 10.0.0.2: bytes=32 time=11ms TTL=126
Ping statistics for 10.0.0.2:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 24
Approximate round trip times in milli-seconds:
Minimum = 11ms, Maximum = 24ms, Average = 15ms
PC>
We can reach 10.0.0.0 network.
Click PC-3/ Desktop/Command Prompt
PC>ping 172.16.0.2
Pinging 172.16.0.2 with 32 bytes of data:
Reply from 172.16.0.2: bytes=32 time=10ms TTL=126
Reply from 172.16.0.2: bytes=32 time=11ms TTL=126
Reply from 172.16.0.2: bytes=32 time=12ms TTL=126
Reply from 172.16.0.2: bytes=32 time=16ms TTL=126
Ping statistics for 172.16.0.2:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 10ms, Maximum = 16ms, Average = 12ms
PC>
We can reach 172.16.0.0 network.
PC>ping 192.168.0.2
Pinging 192.168.0.2 with 32 bytes of data:
Reply from 192.168.0.2: bytes=32 time=12ms TTL=126
Reply from 192.168.0.2: bytes=32 time=11ms TTL=126
Reply from 192.168.0.2: bytes=32 time=22ms TTL=126
Reply from 192.168.0.2: bytes=32 time=10ms TTL=126
Ping statistics for 192.168.0.2:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 10ms, Maximum = 22ms, Average = 13ms
78
PC>
We can reach 192.168.0.0 network.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 25
Practical No.4
Q4) Configure IP routing using RIP.
Routing Information Protocol - RIP
There are two versions of RIP: RIPv1 and RIPv2.
Comparing between RIPv1 and RIPv2
1.Both RIPv1 and RIPv2 have the Administrative distance 120.
2.Both RIPv1 and RIPv2 are distance vector routing protocol.
Both RIPv1 and RIPv2’s metric is hop count.
Maximum hop count = 15. Max routers = 16.
For example, all routers are running RIP and network 10.0.0.0 goes down.
After hold timer expires, that network will be advertised by metric 16 and everyone will know that the
network is down and that network will be seen in routing table as possibly down.
4.Both RIPv1 and RIPv2 send routing updates or complete routing table or broadcast every 30 seconds. i.e.
The
default routing update period for both version of RIP is 30 seconds. i.e. Both have the same timers.
5.Both RIPv1 and RIPv2 use split horizon to prevent routing loops.
6.Both RIPv1 and RIPv2 are configured with router rip.
7.network command tells both RIPv1 and RIPv2 to send hellos, out an interface, to find neighbors and to
advertise routes.
R1(config-router)#network ?
A.B.C.D Network number
R1(config-router)#network 172.16.0.0 ?
<cr>
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 26
R1(config-router)#^Z
R1#
8.Both RIPv1 and RIPv2 are verified with show ip protocols.
Router#show ip protocols
R 10.0.0.10[120/3] via 20.0.0.7, 00:00:15, Serial0/0
The first number in the brackets is the administrative distance of the information source.
The second number is the metric for the route.
In this case, the administrative distance is 120, default AD for RIP routes, and the 3 represents the metric,
which is the number of router hops in RIP.
Difference
1. RIPv1 used broadcast. RIPv2 used multicast(224.0.0.9).
2. RIPv1 is a classful.(Classful: all subnet mask must be the same in the network.) RIPv2 is a classless.
3. RIPv1 does not support VLSM. RIPv2 supports VLSM. subnet mask field was added to the RIPv2
message
header by RFC 1723 to add support for VLSM and CIDR.
4. RIPv1 does not allow authentication. RIPv2 allows MD5 authentication
5. RIP enabled interfaces send version 1(RIPv1) updates.Do not send version 2(RIPv2) updates.
RIP enabled interfaces receive any version(RIPv1 and RIPv2).
6. RIPv2 sends the subnet mask in updates and RIPv1 does not. i.e. Subnet mask information is included in
RIPv2 routing updates that is not included in RIPv1.
Advantage of RIPv2 over RIPv1
1. RIPv2 supports MD5 authentication for routing updates. i.e. RIP version 2 supports routing update
authentication.
2. RIPv2 used multicast(224.0.0.9) rather than broadcast.
3. RIPv2 auto summarize advertised routes across classful boundaries.
To disable this behavior, should apply no auto-summary command under the RIP process.
4. RIPv2 is classless routing protocol means that it sends subnet mask information when updates.

79
By sending the subnet mask information with the updates, RIPv2 can support Variable Length
Subnet Mask(VLSMs) as well as the summarization of network boundaries.
Disadvantage of RIPv1 and RIPv2
1.Both RIPv1 and RIPv2 send full routing tables out every 30 seconds. It’s a lot of overhead, require too
much
bandwidth. Sending full routing table is unnecessary.
2.RIPv1 and RIPv2 does not form adjacency.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 27
3.RIPv1 and RIPv2 work only on hop count(not consider the bandwith).
4.RIPv1 and RIPv2 have slow convergence.
5.Not scalable, because hop count is only 15.
RIPv1 Lab with Packet Tracer Tutorial
RIPv1 Lab with Packet Tracer
Configure RIPv1 on Cisco Routers with following information:
Network: 172.16.0.0/16, 192.168.0.0/24, 10.0.0.0/8
Gateway Address: 172.16.0.1/16, 192.168.0.1/24, 10.0.0.1/8
Putting three IP addresses, subnet mask and default gateway to three PCs.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 28
Click PC1/ Desktop/IP Configuration /Static
Click PC2/ Desktop/IP Configuration /Static
Click PC3/ Desktop/IP Configuration /Static
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 29
Configure Router R1
Router>en
Router#conf t
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#host R1
R1(config)#int fa 0/1
R1(config-if)#ip address 172.16.0.1 255.255.0.0
R1(config-if)#no shut
R1(config-if)#int fa 1/0
R1(config-if)#ip address 192.168.0.1 255.255.255.0
R1(config-if)#no shut
R1(config)#int fa 0/0
R1(config-if)#ip address 100.0.0.1 255.255.255.252
R1(config-if)#no shut
R1(config-if)#exit
R1(config)#
Configure Router R2
Router>en
Router#conf t
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#host R2
R2(config)#int fa 0/0
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 30
R2(config-if)#ip address 100.0.0.2 255.255.255.252
R2(config-if)#no shut
R2(config)#int fa 0/1
R2(config-if)#ip address 10.0.0.1 255.0.0.0
R2(config-if)#no shut
R2(config-if)#exit
R2(config)#
80
Configure RIPv1 to router R1Here we put all three network those are connected to R1 router.
A numeric value is required for EIGRP, OSPF. With EIGRP, AS number, with OSPF, the process
number, but
RIP, there is no number.
R1(config)#router rip
R1(config-router)#network ?
A.B.C.D Network number
R1(config-router)#network 172.16.0.0 ?
<cr>
R1(config-router)#network 172.16.0.0
R1(config-router)#network 192.168.0.0
R1(config-router)#network 100.0.0.0
R1(config-router)#^Z
R1#
Configure RIPv1 to router R2
Here we put two network those are connected to R2 router.
R2(config)#router rip
R2(config-router)#network ?
A.B.C.D Network number
R2(config-router)#network 100.0.0.0
R2(config-router)#network 10.0.0.0
R2(config-router)#^Z
R2#
See routing table of router R1
R1#show ip route
Gateway of last resort is not set
R 10.0.0.0/8 [120/1] via 100.0.0.2, 00:00:20, FastEthernet0/0
100.0.0.0/30 is subnetted, 1 subnets
C 100.0.0.0 is directly connected, FastEthernet0/0
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 31
C 172.16.0.0/16 is directly connected, FastEthernet0/1
C 192.168.0.0/24 is directly connected, FastEthernet1/0
R1#
R1#show ip rip database
10.0.0.0/8
[1] via 100.0.0.2, 00:00:12, FastEthernet0/0
100.0.0.0/30 directly connected, FastEthernet0/0
172.16.0.0/16 directly connected, FastEthernet0/1
192.168.0.0/24 directly connected, FastEthernet1/0
R1#
See routing table of router R2
R2#show ip route
Gateway of last resort is not set
C 10.0.0.0/8 is directly connected, FastEthernet0/1
100.0.0.0/30 is subnetted, 1 subnets
C 100.0.0.0 is directly connected, FastEthernet0/0
R 172.16.0.0/16 [120/1] via 100.0.0.1, 00:00:09, FastEthernet0/0
R 192.168.0.0/24 [120/1] via 100.0.0.1, 00:00:09, FastEthernet0/0
R2#
R2#show ip rip database
10.0.0.0/8 directly connected, FastEthernet0/1
100.0.0.0/30 directly connected, FastEthernet0/0
172.16.0.0/16
[1] via 100.0.0.1, 00:00:19, FastEthernet0/0
192.168.0.0/24
[1] via 100.0.0.1, 00:00:19, FastEthernet0/0
81
R2#
Now check IP connectivity
Click PC-1/ Desktop/Command Prompt
PC>ping 10.0.0.2
Pinging 10.0.0.2 with 32 bytes of data:
Reply from 10.0.0.2: bytes=32 time=12ms TTL=126
Reply from 10.0.0.2: bytes=32 time=13ms TTL=126
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 32
Reply from 10.0.0.2: bytes=32 time=12ms TTL=126
Reply from 10.0.0.2: bytes=32 time=20ms TTL=126
Ping statistics for 10.0.0.2:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 12ms, Maximum = 20ms, Average = 14ms
PC>
We can reach 10.0.0.0 network.
Click PC-2/ Desktop/Command Prompt
PC>ping 10.0.0.2
Pinging 10.0.0.2 with 32 bytes of data:
Reply from 10.0.0.2: bytes=32 time=12ms TTL=126
Reply from 10.0.0.2: bytes=32 time=14ms TTL=126
Reply from 10.0.0.2: bytes=32 time=24ms TTL=126
Reply from 10.0.0.2: bytes=32 time=11ms TTL=126
Ping statistics for 10.0.0.2:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 11ms, Maximum = 24ms, Average = 15ms
PC>
We can reach 10.0.0.0 network.
Click PC-3/ Desktop/Command Prompt
PC>ping 172.16.0.2
Pinging 172.16.0.2 with 32 bytes of data:
Reply from 172.16.0.2: bytes=32 time=10ms TTL=126
Reply from 172.16.0.2: bytes=32 time=11ms TTL=126
Reply from 172.16.0.2: bytes=32 time=12ms TTL=126
Reply from 172.16.0.2: bytes=32 time=16ms TTL=126
Ping statistics for 172.16.0.2:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 10ms, Maximum = 16ms, Average = 12ms
PC>
We can reach 172.16.0.0 network.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 33
PC>ping 192.168.0.2
Pinging 192.168.0.2 with 32 bytes of data:
Reply from 192.168.0.2: bytes=32 time=12ms TTL=126
Reply from 192.168.0.2: bytes=32 time=11ms TTL=126
Reply from 192.168.0.2: bytes=32 time=22ms TTL=126
Reply from 192.168.0.2: bytes=32 time=10ms TTL=126
Ping statistics for 192.168.0.2:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 10ms, Maximum = 22ms, Average = 13ms
PC>
We can reach 192.168.0.0 network.
82
Routing Information Protocol - RIP Command Tutorial
RIP Command
1.The command show ip route followed by the protocol will show that protocol's route from the entire
routing table.
R1#show ip route rip
2.The command show protocols is used to view the RIP routing protocol settings and configuration.
3.The command show ip rip database will display RIP routing updates or RIP routing information as they
are
sent and received. But to see the updates in real time, we need command Debug not Show.
But don't do debug ip rip, don't do debug all. It may crash your router.Because all possible debugs will start
and consume router's whole processing and memory.
4.If The command Router(config-router)# version 2 is entered on the routers, only version 2 updates are
sent
to 224.0.0.9.
5.If The command Router(config-router)# no version 2 is entered on the routers, version 1 and 2 updates
will
be received and the version 2 updates will not be sent.
6.The command debug ip rip shows the routes being advertised in RIP updates and the metrics of these
routes. i.e. debug ip rip will display RIP activity as it occurs on a router.
R1#debug ip rip
7.The command clear ip route * should apply after the command debug ip rip to clear the routing table of
its
dynamic routes.
R1#clear ip route *
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 34
8.The command undebug all turn off all debugs.
R1#undebug all
9.To turn off specific debugs, run the command no debug followed by the type of debug you want to turn
off.
R1#no debug ip rip
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 35
Practical No.5
Q5) Configuring OSPF.
OSPF Terminology
Link: Interface on a router
Link state: Description of an interface and of its relationship to its neighboring routers.
The collection of all the link-states would form a link-state database.
1.OSPF uses cost as a metric, which is the inverse of the bandwidth of a link. OSPF identifies the best route
by
use of cost.
2.OSPF uses Dijkstra or SPF(Shortest Path First) algorithm. Dijkstra or SPF is a same algorithm.
3.OSPF provides a loop free topology.
4.OSPF's administrative distance is 110.
5.Before exchanging routing information, OSPF routers find out neighbors.
OSPF routers exchange LSAs, and the OSPF algorithm uses the contents of those LSAs to build their routing
table. In this way, OSPF allows extensive control of routing updates.
6.OSPF is complex to configure and difficult to troubleshoot.
7.OSPF does not support IPX.
8.OSPF requires more memory and faster processors to handle OSPF than distance vector protocol. i.e.
OSPF is
a CPU-intensive protocol, and very large OSPF networks can experience routing and update traffic problems
that seriously impact network performance.
9.OSPF confines network instability to a single area of the network.
10.OSPF uses WILDCARD MASK instead subnet mask.
83
Advantages of OSPF
1. OSPF is an open-standard, purely link-state protocol.
RIP, IGRP and EIGRP are distance-vector (routing by rumor) routing protocols, susceptible to routing loops,
split-horizon, and other issues.
2. OSPF converges very quickly - from the point of recognizing a failure, it often can converge in less than
10
seconds.
3. OSPF sends updates only changed portion or partial updates of a network when link status changes rather
than the complete routing table. In this way, reduces the usage of bandwidth(BW) and decreases routing
overhead by sending triggered updates to announce changes in the network. RIP and IGRP hold-down timers
can cause slow convergence.
4. OSPF supports VLSM and CIDR. OSPF supports route summarization. RIPv1 and IGRP do not.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 36
5. OSPF is a classless protocol, not classful.
6. OSPF uses the concept of areas to implement hierarchical design, not a flat design like RIP.
7. With OSPF, a router does flood its own LSAs when it age reaches 30 minutes. The flooding, however,
does
not happened all at once, so the overhead is minimal. RIP sends entire routing table every 30 seconds, IGRP
every 90 seconds.
8.Link state protocol like OSPF doesn't have anything like Hop. i.e. Do not use hops to mark networks as
unreachable.
When an OSPF router does not receive a Hello packet for a specified time period, it assumes that the
neighbor
is down. The router then runs the SPF algorithm to calculate new routes.
Routing Overhead
Routing overhead is the amount of information needed to describe the changes in a dynamic network
topology.
All routers in an OSPF area have identical copies of the topology database.
The topology database of one are is hidden from the rest of the areas to reduce routing overhead. Because
fewer routing updates are sent and smaller routing trees are computed.
OSPF Hierarchical Design Tutorial
Hierarchical Design
1.Hierarchical routing speeds up the convergence time for all routers.
2.Hierarchical routing reduces the amount of routing overhead.
3.Hierarchical routing confines network instability to a single area of the network. i.e. Hierarchical routing
hides network instability from routers in other areas.
4.OSPF network can be divided into areas which is logical segmentation of a large network. OSPF supports a
two-layer hierarchical design: 1. backbone (area 0) and 2. areas off of the backbone. Multiple OSPF areas
must
connect to area 0. All other areas have at least one connection to area 0, either directly or through the use of
virtual links.
If any area does not have a direct connection to the backbone area 0, then an OSPF virtual link must be
configured.
The backbone area is not a network type, but a collection of OSPF networks links. Area 0 is reserved as the
backbone area, and routers within area 0 may or may not go through the DR/BDR election process,
depending
on the network type.
5.If an OSPF network is configured as a single area, then area 0 does not need to be used.
If the network design is hierarchical, then multiple areas do not need. i.e. Hierarchical OSPF network do not
require multiple areas.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 37
6.OSPF allows to summarize networks from one area into another. Instead of routers needing to know about
all the individual networks in another area, they need to know only about the summary route. The fewer
routes result in faster convergence and less routing overhead.
84
7.Loopback interfaces are created on a router, and the highest IP address on a loopback (logical) interface
becomes the RID of the router but has nothing to do with areas.
8.If a network in an area go down, it will not affect routers in other areas. A small change in the topology of
a
single area won't force every router to run the SPF algorithm. Changes in one area are limited to that area
only, not to every router within the entire network.
OSPF Area Tutorial
OSPF Area
1. OSPF uses the concept of areas which helps route summarization.
2.Area 0 is called the backbone area.
3. Multiple OSPF areas must connect to area 0.
4. If you have only one are, it must be called are 0.
5. The area number can be the range from 0 to 4,294,967,295; or 0 to 4.2 million.
6. The backbone area is not a network type, but a collection of OSPF networks links.
Area 0 is reserved as the backbone area, and routers within area 0 may or may not go through the DR/BDR
election process, depending on the network type.
7. If a network in an area goes down, it will not affect routers in other areas.
8. The OSPF command network 0.0.0.0 255.255.255.255 area 0includes all of its interfaces in area 0.
OSPF Adjacency/Neighbor Tutorial
OSPF Adjacency
1.OSPF neighbor relationship table is called an adjacency database.
2.Before exchanging routing information, OSPF routers find out neighbors. Each router discovers its
neighbors
on each interface. The list of neighbors is kept in a neighbor table.
3.Each router uses a reliable protocol to exchange topology information with its neighbors.
4.If OSPF is configured correctly, OSPF form neighbor relationships only with the routers directly connected
to
it.
5.To share information with another router, they must be neighbors: their area numbers and types, timers,
and passwords must match.
To form a neighbor relationship
The following must match before routers become neighbors:
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 38
1. Hello and Dead interval must match on the two routers on the same link or they will not form adjacency.
2. The area type must match on the segments.
i.e.The router that is formed a neighbor relationship must be in the same area.
3. Subnet mask must match on the segments.
4. MTU size must match on the segments.
5. Authentication password.
OSPF Hello
1.OSPF uses Hello packets to create and maintain adjacencies. i.e. A neighbor is discovered dynamically
through reception of Hello packets.
The rules that govern the exchange of OSPF hello packets are called the Hello protocol.
2.the hello packets are addressed to the multicast address 224.0.0.5.
The multicast IP address 224.0.0.5 is known as 'All SPFRouters.'
On point-to-point networks, OSPF hello packets are addressed 224.0.0.5.
Hello packets are always sent to this destination.
Also, certain OSPF protocol packets are sent to this address during the flooding procedure.
RIPv2 multicast to 224.0.0.9
EIGRP multicast to 224.0.0.10
3.Hello packets detect unreachable neighbors.
4.Hello packets ensure two-way communications between neighbors.
5.Hello packets ensure correctness of basic interface parameters between neighbors.
6.Hello packets provide necessary information for the election of the designated router (DR) and a backup
designated router (BDR) on a LAN segment/ On multi-access networks.
85
7.On a broadcast multi-access and point-to-point networks, such as Ethernet, Hello packets go at every 10
seconds.
On a non-broadcast segment, NBMA networks, such as Frame Relay, Hello packets go at every 30 seconds.
8.When an OSPF router does not receive a Hello packet for a specified time period, it assumes that the
neighbor is down. The router then runs the SPF algorithm to calculate new routes.
OSPF Dead Interval
1.The dead time is four times the hello time.
2.If you change the hello time, dead time will change dynamically.
3.Dead time can not be statically set.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 39
4.The OSPF Hello time can be set with the ip ospf hello-timecommand:ip ospf hello-time 20 . As the Dead
time is 4 times the Hello time, Dead time will be 80 seconds.
5.The OSPF Dead time can be set with the ip ospf dead-timecommand:ip ospf dead-time 80 . As the Dead
time is set to 80 seconds, the Hello time will dynamically change to 20 seconds.
OSPF Cost Metric Tutorial
Cost Metric
1.A cost is associated with the output side of each router interface. This cost is configurable by the system
administrator. The lower the cost, the more likely the interface is to be used to forward data traffic.
2.OSPF identifies the best route by use of cost. OSPF route metrics are referred to as cost.
3.OSPF uses cost as a metric, which is the inverse of the bandwidth of a link. OSPF identifies the best route
by
use of cost.
For example,
Above the figure, the value 128 shown in bold is the OSPF cost metric.
4.Cost of a route is the cumulative costs of the outgoing interfaces from this router to the network.
5.Cost is defined as 10^8/bandwidth. i.e. 10^8(100,000,000) is the reference bandwidth.
Cisco's default interface costs:
The cost of a 56 kbps link in OSPF is 1785. 56-kbps serial link = 1785 (10^8/56000)
The cost of a 64k link in OSPF is 1562. 64-kbps serial link = 1562 (10^8/64000)
The cost of a 128k link in OSPF is 781. 128-kbps serial link = 781 (10^8/128000)
The cost of a 1.544 T1 link in OSPF is 64. T1 (1.544-Mbps serial link) = 64 (10^8/1.544*1000000)
The cost of a 2.048-Mbps link in OSPF is 48. E1 (2.048-Mbps serial link) = 48 (10^8/2.048*1000000)
The cost of a 4-Mbps Token Ring in OSPF is 25. 4-Mbps Token Ring = 25 (108/4*1000000)
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 40
The cost of a 10MB link in OSPF is 10. 10MB serial link = 10(108/10000000)
Ethernet = 10
Fast Ethernet = 1
Note:
Both sides of the link should have the same bandwidth value.
Example
Two different ways we can go R3 from R1.
We can go through R4 which involves two 512 cable links.
Or, we can go through R2 which involves two T1 links.
The OSPF can be made easily understand the speeds.
RIP is going to see these paths is being equal, because all RIP understand hop count.
OSPF DR BDR
DR/BDR
Which network types have a DR/BDR election occur:
1. No DR is assigned on any type of point-to-point link. On a point to point link, only two routers exist so
there
is no need for a DR or BDR.
i.e. Point-to-point segments don’t use DR/BDR.
OrOn Point-to-point segment DRs/BDRs are not elected.
2. In a point-to-point and point-to-multipoint OSPF network type, OSPF will establish router adjacencies but
86
not perform the DR/BDR election.
3. No DR/BDR is assigned on the NBMA point-to-multipoint due to the hub/spoke topology.
4. DR and BDR are elected on broadcast and non-broadcast multi-access(NBMA) networks.
Frame Relay is a non-Broadcast Multi-Access (NBMA) network by default.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 41
Some key features of OSPF DR/BDR
1. DRs and BDRs assist in sharing topology information.
2. In a hub and spoke OSPF NBMA network, the hub router should be configured as the Designated
Router(DR).
3. DR is responsible for making adjacencies with all neighbors on a multiaccess network, such as Ethernet or
FDDI.
4. DR represents the multiaccess network, in that it ensures that every router on the link has the same
topology database.
5. BDR is the backup to the designated router (DR), in case the DR fails. BDR performs none of the DR
functions while the DR is operating correctly.
6. A router on an OSPF segment that is neither the DR nor the BDR is called DROTHER.
Lets say an broadcast segment, we have 4 routers. One router can be DR, one router can be BDR and other
two routers would be DROTHERS.
7. To determine manually which router will be the DR, it is necessary to set the priority of the router. A
router
interface can have a priority of 0 to 255. The value of 0 means that the router cannot be a DR or BDR.
Router(config-if)#ip ospf priority <value>
The number in the priority command can be set between 0-255, where the higher the number, the greater the
likelihood that this router will be selected as the DR.
8. DR and BDR election is done via the Hello protocol. Hello packets are exchanged via IP multicast packets
on
each segment.
9. Routers use multicast address 224.0.0.5 to send LSAs to the DR/BDR.
Or
Traffic sent to a DR/BDR pair is multicast to 224.0.0.5.
10. Traffic sent to all routers on a segment has a destination address of 224.0.0.6.
11. Hello messages are sent out every 10 seconds, with a dead interval timer of 40 seconds.
The DR sends a periodic update every 30 minutes.
12.If DR is down and no BDR is configured, then selection of DR starts again automatically.
If there is no BDR, the protocol will restart the process to look for another possible DR in the NBMA
network.
Note
Many administrators prefer to use point-to-point or point-to-multipoint for NMBA to avoid the DR/BDR and
full-mesh issues.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 42
OSPF Router ID Tutorial
OSPF Router ID
Router ID – Used to identify the routers in the OSPF network.
1. Each OSPF router has an ID, which is either the highest IP address on a loopback interface, if one exists,
or
the highest IP address on an active interface.
2. To configure network instability to one area of the network, OSPF uses router ID(RID) or a 32-bit IP
address
selected at the beginning of the OSPF process.
3. If a router’s OSPF RID is hard coded or change a router’s OSPF RID, router reload or clear the OSPF
process is
needed.
Or
Changing the OSPF RID, will require to either reload the router or clear your OSPF process.
87
4. RIDs have no relationship with areas.
Process of selecting RID
1. The highest IP address configured on the router is the router ID, if no loopback exist.
i.e. At the moment of OSPF process startup, the highest IP address on any active interface will be the Router
ID(RID).
2. When loopback interface is created on a router, the IP address of loopback(logical) interface override the
IP
address and becomes the RID(router ID).
3. If multiple loopback interfaces are configured, the highest loopback address becomes the RID.
Advantage of using loopback
1. Loopback address provides stability for the OSPF process on router.
2. Loopback address has the advantage of never going down as long as the router is powered on. It
provides greater stability the OSPF process on router and the routing table ,thus diminishing the possibility
of
having to re-establish adjacencies.
OSPF-Difference Between RIP and EIGRP Tutorial
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 43
1.OSPF is link-state routing protocol.
RIP and EIGRP are distance-vector (routing by rumor) routing protocols, susceptible to routing loops,
splithorizon,
and other issues.
2.OSPF has fast convergence.
RIP use hold-down timers can cause slow convergence.
3.OSPF supports VLSM and CIDR.
RIPv1 does not supports VLSM and CIDR.
4.OSPF metric is based on bandwidth.
RIP metric is based on hop count.
EIGRP metric is based on bandwidth, delay, reliability, load.
5.OSPF only sends out changes when they occur. With OSPF, a router does flood its own LSAs when it age
reaches 30 minutes.
RIP sends entire routing table every 30 seconds, IGRP every 90 seconds.
6.OSPF uses the concept of areas to implement hierarchical routing.
There are no hierarchical concept to RIP and EIGRP.
OSPF Commands Tutorial
OSPF Commands
Enable OSPF process or routing
Syntax
Router(config)#router ospf <process-id>
Note
The command router ospf 100 stand for an Process ID. It is not going be advertised down stream routers.
Router#conf t
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#router ospf ?
<1-65535> Process ID
Router(config)#router ospf
The command router eigrp 100 stand for an Autonomous system number. Logically create group routers
with
AS.
That not only will be advertised to potential neighbor, they have to agree become neighbors.
Router#conf t
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#router eigrp ?
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 44
<1-65535> Autonomous system number
88
Router(config)#router eigrp
Define an interface on which OSPF runs and define the area ID for that interface
Syntax
Router(config-router)#network address <wildcard-mask>< area><area-id>
Configure loopback
Syntax
Router(config)#interface loopback number
DR/BDR election
Syntax
Router(config)#interface <interface>
Router(config-if)#ip ospf priority <0-255>
By default all links are equal with a priority of 1.
In a hub-and-spoke network to become the DR, don’t raise the OSPF interface priority of hub router – lower
the OSPF interface priority of the soke routers.
The command ip ospf priority is commonly used in hub-and-spoke network on the spoke only.
The command ip ospf priority 0 disqualifies from taking part of DR, BDR election for that particular
segment.
For example,
R2#conf t
R2(config)# int so.123
R2(config-subif)# ip ospf priority 0
Modify bandwdth
Syntax
Router(config-if)#bandwidth kbps
Explicitly specify the cost of sending a packet on an OSPF interface
Syntax
Router(config-if)#ip ospf cost <cost>
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 45
Specify or modify Hello/Dead time
Syntax
Router(config-if)#ip ospf hello-interval <seconds>
Router(config-if)#ip ospf dead-interval <seconds>
Specify the authentication type for an interface
Authentication (Plain)
Syntax
Router(config-router)#area <area> authentication
Authentication (md5)
Router(config-router)#area <area> authentication message-digest
Enable OSPF MD5 authentication. Assign a password to be used by neighboring OSPF routers
Syntax
Router(config-if)#ip ospf <authentication-key><passwd>
Router(config-if)#ip ospf <message-digest-key><key-id> <md5><password>
Verify OSPF
To see the detail information of all OSPF routing process enabled on a router
Router#show ip ospf
To display interface-specific OSPF information
Syntax
Router#show ip ospf interface [int]
For example, the command show ip ospf interface serial 0 will display the serial interface of OSPF
information. Such as: Hello and dead interval timers, Priority of the router, Cost of the interface, display the
router ID of both the DR and the BDR on the network segment.
You can not see Process and router ID using the command show ip ospf interface .
Router#show ip ospf database
Router#debug ip ospf packet
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 46
89
Router#debug ip ospf hello
Router#debug ip ospf adj
Display all OSPF neighbors
Router#show ip ospf neighbor
Example:
Router#show ip ospf neighbor
Neighbor ID Pri State Dead Time Address Interface
192.168.1.2 0 FULL/ - 00:00:38 192.168.1.2 Serial1/0
Router#
Neighbor ID: The neighbor ID that is the OSPF RID of the neighbor.
Pri: Short for “priority”, that’s the interface priority of the neighbor.
State: That’s the OSPF adjacency state and role of the router – DR, BDR, or DROTHER.
Dead Time: Time remaining until the adjacency is torn down. Receipt of a valid hello packet will reset this
timer.
Address: The IP address of the neighbor’s interface through which the adjacency has formed. It can be same
as the neighbor ID.
Interface: The interface through which the adjacency has formed.
OSPF ip ospf hello-interval Command Tutorial
ip ospf hello-interval Command
Configure Router R1
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 47
Router>en
Router#conf t
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#host R1
R1(config)#int f0/0
R1(config-if)#ip add 192.168.1.1 255.255.255.252
R1(config-if)#no shut
R1(config-if)#exit
R1(config)#
Configure Router R2
Router>en
Router#conf t
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#host R2
R2(config)#int f0/0
R2(config-if)#ip add
R2(config-if)#ip address 192.168.1.2 255.255.255.252
R2(config-if)#no shut
R2(config-if)#exit
R2(config)#
Configure OSPF on router R1
R1(config)#router ospf 1
R1(config-router)#network 192.168.1.0 0.0.0.3 area 0
R1(config-router)#^Z
R1#
Configure OSPF on router R2
R2(config)#router ospf 1
R2(config-router)#network 192.168.1.0 0.0.0.3 area 0
R2(config-router)#
00:09:35: %OSPF-5-ADJCHG: Process 1, Nbr 192.168.1.1 on FastEthernet0/0 from LOADING to FULL,
Loading
Done
R1#

90
00:09:38: %OSPF-5-ADJCHG: Process 1, Nbr 192.168.1.2 on FastEthernet0/0 from LOADING to FULL,
Loading
Done
R1 and R2 formed adjacency over their fast Ethernet interfaces.
To see the default dead time on the fa0/0 interface of router R1:
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 48
R1#sh ip ospf int fa0/0
FastEthernet0/0 is up, line protocol is up
Timer intervals configured, Hello 10, Dead 40, Wait 40, Retransmit 5
R1#
From the output, we see that the Hello time is 10 seconds, dead time is 40 seconds.
We want to double this Dead value using the command ip ospf dead-interval or ip osfp hello-interval.
By default, the dead time is four times of hello times in ospf.
So, if we double the hello time, dead time will be dynamically be doubled.
Since hello time is 10 seconds on a broadcast segment, we could put 20 here.
R1#conf t
Enter configuration commands, one per line. End with CNTL/Z.
R1(config)#int fa0/0
R1(config-if)#ip ospf hello-interval 20
R1(config-if)#^Z
R1#
R1#sh ip ospf int fa0/0
Timer intervals configured, Hello 20, Dead 80, Wait 80, Retransmit 5
R1#
R2#
00:24:30: %OSPF-5-ADJCHG: Process 1, Nbr 192.168.1.1 on FastEthernet0/0 from FULL to DOWN,
Neighbor
Down: Dead timer expired
00:24:30: %OSPF-5-ADJCHG: Process 1, Nbr 192.168.1.1 on FastEthernet0/0 from FULL to Down:
Interface
down or detached
R2#
From the output, we see that the dead time is double now.
Now we have a problem with adjacency.
R1#sh ip ospf neighbor
R1#
The adjacency went down,because we have configured hello time which effected on router R2.
To see the default dead time on the interface fa0/0 of R2 router:
R2#sh ip ospf int fa0/0
Timer intervals configured, Hello 10, Dead 40, Wait 40, Retransmit 5
R2#
Using the command ip ospf hello on R2’s fa0/0 interface to double the hello time:
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 49
R2#conf t
Enter configuration commands, one per line. End with CNTL/Z.
R2(config)#int fa0/0
R2(config-if)#ip ospf hell
R2(config-if)#ip ospf hello-interval 20
R2(config-if)#^Z
R2#
%SYS-5-CONFIG_I: Configured from console by console
00:35:40: %OSPF-5-ADJCHG: Process 1, Nbr 192.168.1.1 on FastEthernet0/0 from EXCHANGE to FULL,
Exchange Done
R2#
R2#sh ip ospf int fa0/0
91
Timer intervals configured, Hello 20, Dead 80, Wait 80, Retransmit 5
R2#
Note, both hello and dead timer now have changed.
R1#
00:35:44: %OSPF-5-ADJCHG: Process 1, Nbr 192.168.1.2 on FastEthernet0/0 from EXCHANGE to FULL,
Exchange Done
And we see that, adjacency again formed between R1 and R2 routers.
Practical No.6
Q6) Generate Network Traffic and examine the functionality of UDP and TCP.
(Refer to Exploration of TCP and UDP.pdf file)
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 50
Practical No.7
Q7) Run different SCTP commands.
sctp
To enter the Stream Control Transmission Protocol (SCTP) configuration, use the sctp command in
IDSN User Adaptation Layer (IUA) configuration mode. To disable, use the no form of this
command.
sctp [ [ t1-initmilliseconds ] [ t3-rtx-minseconds ] [ t3-rtx-maxmilliseconds ] [ startup-rtxnumber
][
assoc-rtxnumber ] [ path-rtxnumber ] ]
nosctp
Syntax Description
t1 -
initmilliseconds
Timer T1 initiation value in milliseconds. Valid values are from 1000 to
60000. The t1-init configurable option applies only during the creation
of an SCTP instance.
t3 -rtx-min
seconds
Timer T3 retransmission minimum timeout in seconds. Valid values are
from 1 to 300.
t3 -rtx-max
milliseconds
Timer T3 retransmission maximum timeout in milliseconds. Valid
values are from 1000 to 60000.
startup -rtx
number
Maximum startup retransmissions. The startup-rtx configurable option
applies only during the creation of an SCTP instance. Valid values are
from 2 to 20.
assoc -rtx number Maximum association retransmissions. Valid values are from 2 to 20.
path-rtx number Maximum path retransmissions. Valid values are from 2 to 20.
Command Default
SCTP configuration commands cannot be entered.
Command Modes
IUA configuration (config-iua)
To enter SCTP configuration commands, you must first enter IUA configuration mode and then
enter
sctp at the Router(config-iua)# prompt to enter SCTP configuration mode.

92
Examples
The following example shows how to enter IUA configuration mode:
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 51
Router# configure terminal
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)# iua
Router(config-iua)#
The following is an example of how to set failover time (in milliseconds) between 1 and 10 seconds
as
part of SCTP configuration of the T1 initiation timer. This example uses the lowest failover timer
value allowed (1 second):
Router(config-iua)# as as5400-3 fail-over 1000
The following is an example of how to set SCTP maximum startup retransmission interval. This
example uses the maximum startup retransmission interval value allowed:
Router(config-iua)# as as5400-3 sctp-startup 20
The following is an example of how to configure the number of SCTP streams for this AS. This
example uses the maximum SCTP streams allowed:
Router(config-iua)# as as5400-3 sctp-streams 57
The following is an example of how to configure the SCTP T1 initiation timer (in milliseconds).
This
example uses the maximum timer value allowed:
Router(config-iua)# as as5400-3 sctp-t1init 60000
Related Commands
Command Description
pri-group (pri-slt) Specifies an ISDN PRI on a channelized T1 or E1 controller.
show debugging
To display information about the types of debugging that are enabled for your router, use the show
debugging command in privileged EXEC mode.
showdebugging
Syntax Description
This command has no arguments or keywords.
Command Modes
Privileged EXEC (#)
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 52
Use this command to display the current SCTP association and instance identifiers, the current state
of
SCTP associations, and the local and remote port numbers and addresses that are used in the
associations.
Examples
The following is sample output from this command for three association identifiers:
Router# show ipsctp association list
*** SCTP Association List ****
AssocID:0, Instance ID:0
Current state:ESTABLISHED
Local port:8989, Addrs:10.1.0.2 10.2.0.2
Remote port:8989, Addrs:10.6.0.4 10.5.0.4
AssocID:1, Instance ID:0
Current state:ESTABLISHED
Local port:8989, Addrs:10.1.0.2 10.2.0.2
Remote port:8990, Addrs:10.6.0.4 10.5.0.4

93
AssocID:2, Instance ID:0
Current state:ESTABLISHED
Local port:8989, Addrs:10.1.0.2 10.2.0.2
Remote port:8991, Addrs:10.6.0.4 10.5.0.4
The table below describes the significant fields shown in the display.
Table 11 show ipsctp association list Field Descriptions
Field Description
Assoc ID SCTP association identifier.
Instance ID SCTP association instance identifier.
Current state SCTP association state, which can be ESTABLISHED, CLOSED,
COOKIE-WAIT, and COOKIE-ECHOED.
Local port,
Addrs
Port and IP address for the local SCTP endpoint.
Remote port,
Addrs
Port and IP address for the remote SCTP endpoint.
Related Commands
Command Description
clear ipsctp statistics Clears statistics counts for SCTP.
debug ipsctpapi Reports SCTP diagnostic information and messages.
show ipsctp association
parameters
Displays the parameters configured for the association defined
by the association identifier.
show ipsctp association
statistics
Displays the current statistics for the association defined by the
association identifier.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 53
Command Description
show ipsctp errors Displays error counts logged by SCTP.
show ipsctp instances Displays the currently defined SCTP instances.
show ipsctp statistics Displays the overall statistics counts for SCTP.
show iua as Displays information about the current condition of an
application server.
show iua asp Displays information about the current condition of an
application server process.
showipsctp association parameters
To display configured and calculated parameters for the specified Stream Control Transmission
Protocol (SCTP) association, use the show ipsctp association parameters command in privileged
EXEC mode.
showipsctpassociationparametersassoc-id
Syntax Description
assoc-id Association identifier. Shows the associated ID statistics for the SCTP association.
Command Modes
Privileged EXEC (#)
The following sample output shows the statistics accumulated for SCTP association 0:
Router# show ipsctp association statistics 0
** SCTP Association Statistics **
94
AssocID/InstanceID: 0/1
Current State: ESTABLISHED
Control Chunks
Sent: 623874 Rcvd: 660227
Data Chunks Sent
Total: 14235644 Retransmitted: 60487
Ordered: 6369678 Unordered: 6371263
Avg bundled: 18 Total Bytes: 640603980
Data Chunks Rcvd
Total: 14496585 Discarded: 1755575
Ordered: 6369741 Unordered: 6371269
Avg bundled: 18 Total Bytes: 652346325
Out of Seq TSN: 3069353
ULP Dgrams
Sent: 12740941 Ready: 12740961 Rcvd: 12740941
The table below describes the significant fields shown in the display.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 54
Table 13 show ipsctp association statistics Field Descriptions
Field Description
AssocID/InstanceID SCTP association identifier and instance identifier.
Current State State of SCTP association.
Control Chunks SCTP control chunks sent and received.
Data Chunks Sent SCTP data chunks sent, ordered and unordered.
Data Chunks Rcvd SCTP data chunks received, ordered and unordered.
ULP Dgrams Number of datagrams sent, ready, and received by the Upper-Layer
Protocol (ULP).
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 55
Practical No.8
Q8) Configure DHCP and DNS.(Using Packet Tracer/LINUX/Windows)
Four steps occur sequentially when a client requests addressing information:
1. When client wants to get ip address via DHCP, it generates dhcp discover.
The client broadcasts a DHCPDISCOVER message on its local physical subnet.
The DHCPDISCOVER message may include options that suggest values for the network address and lease
duration.
DHCPDISCOVER is a UDP broadcast message type.
2. One or more servers may answer on it with dhcp offer.
Each server may respond with a DHCPOFFER message that includes an available network address in the
"ipaddr" field (and other configuration parameters in DHCP options).
The server unicasts the DHCPOFFER message to the client (using the DHCP/BOOTP relay agent if
necessary) if possible, or may broadcast the message to a broadcast address (preferably 255.255.255.255)
on the client's subnet.
3. When client choice from what server it want ip address, and generate dhcp request, in which set ip address
selected server.
The client chooses one reply and responds to the server with aDHCPREQUEST.
DHCPREQUEST is a UDP broadcast message type.
4. The server acknowledges the request with a DHCPACK.
Features of DHCP:
1. DHCP messages from a client to a server are sent to the DHCP server port (UDP port 67), and DHCP
messages from a server to a client are sent to the DHCP client port (UDP port 68).
2. DHCP is used to provide IP information to hosts on your network. DHCP can provide a lot of information,
but the most common is IP address, subnet mask, default gateway, and DNS information.
3. The DHCP Discover message uses UDP as it is the transport layer protocol. i.e. DHCP is connectionless.
4. DHCP also called the Host-to-Host layer.
5. The DHCP Discover message uses FF-FF-FF-FF-FF as the Layer 2 destination address.

95
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 56
6. A client that sends out a DHCP Discover message in order to receive an IP address sends out a broadcast
at
both layer 2 and layer 3. The layer 2 broadcast is all Fs in hex, or FF:FF:FF:FF:FF:FF. The layer 3
broadcast is 255.255.255.255, which means all networks and all hosts.
7. DHCP clients lease their IP addresses from DHCP servers. When this lease expires, that IP address can no
longer be utilized by the DHCP client. For that reason, DHCP client must periodically renew their IP
address leases, preferably before the lease has expired or is about to expire.
The default lease period is 30 days.The default ping timeout is 500 milliseconds.
8. DHCP allows for both private and public addressing.
9. A DHCP server uses a ping to detect address conflicts.
DHCP Commands:
1. ipdhcp pool command creates a DHCP address pool.
Or
To create a DHCP server pool, use the ipdhcp pool command.
2. network command is used to specify the range of addresses.
3. ip address dhcp command is used to acquire a DHCP address on a router’s interface.
4. showipdhcp binding command is used to see the assigned DHCPaddresses.
5. clearipdhcp binding * command is used to clear DHCPaddresses on the server.
6. DHCP's other commands domain-name, dns-server, netbios-name-server,defaultrouter, and lease.
7. ipconfig/release command is used to terminate a PC’s DHCP-assigned lease.
DHCP Lab with Packet Tracer
Configure DHCP services on a Cisco Router with following information
Network: 192.168.10.0 255.255.255.0
Gateway Address: 192.168.10.1
DNS Server: 4.2.2.2
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 57
DHCP pool: 192.168.10.2 to 192.168.10.4
Excluded Address: 192.168.10.5 to 192.168.10.80
Configure router
Router>en
Router#conf t
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#intfa 0/0
Router(config-if)#ip address 192.168.10.1 255.255.255.0
Router(config-if)#no shut
Router(config-if)#exit
Configure DHCP
Router(config)#ipdhcp ?
excluded-address Prevent DHCP from assigning certain addresses
pool Configure DHCP address pools
Router(config)#ipdhcp pool ?
WORD Pool name
Router(config)#ipdhcp pool mypool
Router(dhcp-config)# network 192.168.10.0 255.255.255.0
Router(dhcp-config)#default-router ?
A.B.C.D Router's IP address
Router(dhcp-config)#default-router 192.168.10.1 ?
<cr>
Router(dhcp-config)#default-router 192.168.10.1
Router(dhcp-config)#dns-server ?
A.B.C.D Setip address of DNS server
Router(dhcp-config)#dns-server 4.2.2.2
Router(dhcp-config)#exit

96
Router(config)#ipdhcp ?
excluded-address Prevent DHCP from assigning certain addresses
pool Configure DHCP address pools
Router(config)#ipdhcp excluded-address ?
A.B.C.D Low IP address
Router(config)#ipdhcp excluded-address 192.168.10.1
Router(config)#ipdhcp excluded-address 192.168.10.5 ?
A.B.C.D High IP address
<cr>
Router(config)#ipdhcp excluded-address 192.168.10.5 192.168.10.80
Router(config)#^Z
Router#
View the assigned DHCP addresses
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 58
Router#showipdhcp binding
IP address Client-ID/ Lease expiration Type
Hardware address
192.168.10.2 00E0.F9BE.AD2D -- Automatic
192.168.10.3 0090.2185.88DD -- Automatic
192.168.10.4 0001.6450.50D8 -- Automatic
Router#
Click PC1/ IP Configuration /DHCP
Click PC2/ IP Configuration /DHCP
Click PC3/ IP Configuration /DHCP
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 59
Click PC1/ Command Prompt
PC>ipconfig /all
Physical Address................: 00E0.F9BE.AD2D
IP Address......................: 192.168.10.2
Subnet Mask.....................: 255.255.255.0
Default Gateway.................: 192.168.10.1
DNS Servers.....................: 4.2.2.2
PC>
Click PC2/ Command Prompt
PC>ipconfig /all
Physical Address................: 0090.2185.88DD
IP Address......................: 192.168.10.3
Subnet Mask.....................: 255.255.255.0
Default Gateway.................: 192.168.10.1
DNS Servers.....................: 4.2.2.2
PC>
Click PC3/ Command Prompt
PC>ipconfig /all
Physical Address................: 0001.6450.50D8
IP Address......................: 192.168.10.4
Subnet Mask.....................: 255.255.255.0
Default Gateway.................: 192.168.10.1
DNS Servers.....................: 4.2.2.2
PC>
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 60
Domain Name Server (DNS) Configuration and Administration using LINUX
Domain Name System
The Domain Name System (DNS) is the crucial glue that keeps computer networks in harmony by
97
converting human-friendly hostnames to the numerical IP addresses computers require to
communicate with each other. DNS is one of the largest and most important distributed databases
the
world depends on by serving billions of DNS requests daily for public IP addresses. Most public
DNS
servers today are run by larger ISPs and commercial companies but private DNS servers can also be
useful for private home networks.
To Check IP
[root@www Desktop]# ifconfig
eth0 Link encap:Ethernet HWaddr 00:0C:29:84:6D:8C
inet addr:10.90.12.1 Bcast:10.90.12.255 Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:fe84:6d8c/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:6624 errors:0 dropped:0 overruns:0 frame:0
TX packets:1474 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:442710 (432.3 KiB) TX bytes:1901220 (1.8 MiB)
Interrupt:19 Base address:0x2000
eth1 Link encap:Ethernet HWaddr 00:0C:29:84:6D:96
inet addr:10.23.151.66 Bcast:10.23.159.255 Mask:255.255.224.0
inet6 addr: fe80::20c:29ff:fe84:6d96/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:13927 errors:0 dropped:0 overruns:0 frame:0
TX packets:7518 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:9215651 (8.7 MiB) TX bytes:948169 (925.9 KiB)
Interrupt:19 Base address:0x2080
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:8 errors:0 dropped:0 overruns:0 frame:0
TX packets:8 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:480 (480.0 b) TX bytes:480 (480.0 b)
To Set DNS Server IP
vi /etc/sysconfig/network-scripts/ifcfg-eth0
EVICE=eth0
HWADDR=00:0c:29:84:6d:8c
NM_CONTROLLED=no
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 61
ONBOOT=yes
IPADDR=10.90.12.1
BOOTPROTO=none
NETMASK=255.255.255.0
DNS=10.90.12.1
TYPE=Ethernet
IPV6INIT=no
USERCTL=no
save :wq
To Set Host Name
98
[root@station Desktop]# vim /etc/sysconfig/network
NETWORKING=yes
HOSTNAME=station.example.com
save :wq
[root@station Desktop]# vim /etc/hosts
0.90.12.1 station.example.com station
save :wq
[root@station Desktop]# vim /etc/resolv.conf
search station.example.com
nameserver 10.90.12.1
save :wq
[root@station Desktop]# hostname station.example.com
[root@station Desktop]# hostname
station.example.com
To Install Package
[root@station Desktop]# yum install bind*
Loaded plugins: fastestmirror, refresh-packagekit, security
Repository 'yum' is missing name in configuration, using id
Loading mirror speeds from cached hostfile
Setting up Install Process
Package 32:bind-utils-9.7.3-8.P3.el6.i686 already installed and latest version
Package 32:bind-libs-9.7.3-8.P3.el6.i686 already installed and latest version
Resolving Dependencies
--> Running transaction check
---> Package bind.i686 32:9.7.3-8.P3.el6 will be installed
---> Package bind-chroot.i686 32:9.7.3-8.P3.el6 will be installed
---> Package bind-dyndb-ldap.i686 0:0.2.0-7.el6 will be installed
--> Finished Dependency Resolution
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 62
Dependencies Resolved
=======================================================================
=
Package Arch Version Repository Size
=======================================================================
=
Installing:
bind i686 32:9.7.3-8.P3.el6 yum 3.9 M
bind-chroot i686 32:9.7.3-8.P3.el6 yum 67 k
bind-dyndb-ldap i686 0.2.0-7.el6 yum 49 k
Transaction Summary
=======================================================================
==
Install 3 Package(s)
Total download size: 4.0 M
Installed size: 7.1 M
Is this ok [y/N]: y
Downloading Packages:
(1/3): bind-9.7.3-8.P3.el6.i686.rpm | 3.9 MB 00:00
(2/3): bind-chroot-9.7.3-8.P3.el6.i686.rpm | 67 kB 00:00
(3/3): bind-dyndb-ldap-0.2.0-7.el6.i686.rpm | 49 kB 00:00
--------------------------------------------------------------------------------
99
Total 20 MB/s | 4.0 MB 00:00
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
Warning: RPMDB altered outside of yum.
Installing : 32:bind-9.7.3-8.P3.el6.i686 1/3
Installing : 32:bind-chroot-9.7.3-8.P3.el6.i686 2/3
Installing : bind-dyndb-ldap-0.2.0-7.el6.i686 3/3
Installed:
bind.i686 32:9.7.3-8.P3.el6 bind-chroot.i686 32:9.7.3-8.P3.el6
bind-dyndb-ldap.i686 0:0.2.0-7.el6
Complete!
[root@station Desktop]#
To Copy named.conf file
[root@station Desktop]# cp /etc/named.conf /var/named/chroot/etc/named.conf
To Change directory
cd /var/named/chroot/etc/
To edit configuration file
[root@stationetc]#vim named.conf
options {
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 63
directory "/var/named";
};
zone "example.com" IN {
type master;
file "for.zone";
};
zone "12.90.10.in-addr.arpa" IN {
type master;
file "rev.zone";
};
save :wq
To Change Group Name
[root@stationetc]# chgrp named named.conf
To Copy File same Location
[root@stationetc]# cp /var/named/named.localhost /var/named/chroot/var/named/for.zone
[root@stationetc]# cp /var/named/named.loopback /var/named/chroot/var/named/rev.zone
To change directory
[root@stationetc]# cd /var/named/chroot/var/named/
To edit configuration file
[root@station named]# vim for.zone
$TTL 1D
@ IN SOA example.com. root.example.com. (
0 ; serial
1D ; refresh
1H ; retry
1W ; expire
3H ) ; minimum
@ IN NS station.example.com.
station IN A 10.90.12.1
100
save :wq
To edit configuration file
[root@station named]# vim rev.zone
$TTL 1D
@ IN SOA example.com. root.example.com. (
0 ; serial
1D ; refresh
1H ; retry
1W ; expire
3H ) ; minimum
@ IN NS station.example.com.
1 IN PTR station.example.com.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 64
save :wq
To Change Group Name
[root@station named]# chgrp named for.zone
[root@station named]# chgrp named rev.zone
[root@station named]# ll
total 8
-rw-r-----. 1 root named 190 Jun 1 19:12 for.zone
-rw-r-----. 1 root named 196 Jun 1 19:15 rev.zone
[root@station named]#
To Restart Service & On
[root@station named]# service named restart
Stopping named: [ hiren ]
Starting named: [ hiren ]
[root@station named]# chkconfig named on
To Check Named Server
[root@station named]# dig 10.90.12.1
; <<>>DiG 9.7.3-P3-RedHat-9.7.3-8.P3.el6 <<>> 10.90.12.1
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 23819
;; flags: qrrdra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 0
;; QUESTION SECTION:
;10.90.12.1. IN A
;; AUTHORITY SECTION:
. 10800 IN SOA a.root-servers.net. nstld.verisign-grs.com. 2012060501 1800 900 604800 86400
;; Query time: 193 msec
;; SERVER: 113.193.1.14#53(113.193.1.14)
;; WHEN: Fri Jun 1 19:17:27 2012
;; MSG SIZE rcvd: 103
[root@station named]# dig station.example.com
; <<>>DiG 9.7.3-P3-RedHat-9.7.3-8.P3.el6 <<>> station.example.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 24133
;; flags: qraardra; QUERY: 1, ANSWER: 1, AUTHORITY: 1, ADDITIONAL: 0
;; QUESTION SECTION:
;station.example.com. IN A
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
101
Page | 65
;; ANSWER SECTION:
station.example.com. 86400 IN A 10.90.12.1
;; AUTHORITY SECTION:
example.com. 86400 IN NS station.example.com.
;; Query time: 1 msec
;; SERVER: 10.90.12.1#53(10.90.12.1)
;; WHEN: Fri Jun 1 19:17:47 2012
;; MSG SIZE rcvd: 67
[root@station named]#
Client end Setting
[admin@station1]$vim /etc/resolve.conf
search station.example.com
nameserver 10.90.12.1
Save :wq
[admin@station1]$ dig station.example.com
; <<>>DiG 9.7.3-P3-RedHat-9.7.3-8.P3.el6 <<>> station.example.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 24133
;; flags: qraardra; QUERY: 1, ANSWER: 1, AUTHORITY: 1, ADDITIONAL: 0
;; QUESTION SECTION:
;station.example.com. IN A
;; ANSWER SECTION:
station.example.com. 86400 IN A 10.90.12.1
;; AUTHORITY SECTION:
example.com. 86400 IN NS station.example.com.
;; Query time: 1 msec
;; SERVER: 10.90.12.1#53(10.90.12.1)
;; WHEN: Fri Jun 1 19:17:47 2012
;; MSG SIZE rcvd: 67
Domain Name Server (DNS) Configuration and Administration using Windows
Steps to install DNS on Windows Server 2012
Domain Name System (DNS) is one of the fundamentals of every network especially on the
Internet.
It translates computers and domain names into IP addresses and vice versa.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 66
GUI method:
1. Open Server Manager, on Dashboard, click Add roles and features
2. On Before you begin window, click Next
3. On Installation Type window, select Role-based or featured-based installation, and click
Next
4. On Server Selection window, check Select a server from a server pool, select the desired
server and click Next
5. On Server Roles page, select DNS Server, confirm Add Features, and click Next twice
6. On DNS Server window, click Next
7. On Confirmation window, click Install
8. On Results page, ensure that DNS installed successfully without any errors, then click Close to
finish the wizard
PowerShell method:
1. Open PowerShell and run this command:
102
Install-WindowsFeature DNS –IncludeManagementTools
Managing DNS in Windows Server 2012
If you have installed DNS on a Domain Controller, the administrative job will become so less,
because
DNS is integrated into Active Directory.
DNS client will update its DNS record automatically if “Register the connection’s addresses in
DNS”
is selected (by default it is), or your DHCP server can register DNS records on behalf of DNS
clients
too. So, in most of the time managing DNS is easy. Otherwise, if you want to manually configure it,
pay attention to these procedures.
GUI:
1. Press Windows Key + R, execute dnsmgmt.msc
2. On DNS Manager window, right-click your server and click New Zone
3. On wizard, click on Next. On Zone Type window, select Primary zone (because the first zone
must be primary), and check Store the zone in Active Directory (it is selected by default).
Then click Next
4. On Active Directory Zone Replication Scope page, select the default option of To all DNS
servers running on domain controllers on this domain : hiren.local, click Next then
5. Be sure to select Forward lookup zone as the default option, and click Next
6. Type hiren for zone name, then click on Next
7. Check the radio button of Allow only secure dynamic updates (recommended for Active
Directory), click on Next, then Finish to close the wizard
8. Now you should add records to DNS server, so on DNS manager, expand SERVER1,
Forward Lookup Zones, then right click hiren, and select New Host (A or AAAA)…
9. On New Host window, type the name of one of your computers, for example Server2, and
below IP address type its IP address like 10.10.10.2. And click Add Host, then confirm OK
and close the window
PowerShell:
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 67
1. Open PowerShell console
2. Type and hit enter the below command:
Add-DnsServerPrimaryZone -Name hiren -ZoneFilehiren.dns
Add-DnsServerResourceRecordA -ZoneNamehiren –Name Server2 -IPv4Address 10.10.10.2
Launch your Server Manager if it is not already up
On your Dashboard, click on “Add roles and features”
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 68
You will get the “Add Roles and Features Wizard”, click Next
Select “Role-based or feature-based installation”, click Next
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 69
In “Select destination server” screen, most likely you will only see one selection, which is the server
you are on, if not, select the server you want to add the DNS role to and click Next
Check the “DNS Server” box
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 70
A smaller window will launch to confirm that there are other features that needs to be installed with
your DNS role, click on “Add Features” then click Next
You do not have to select anything in the “Select features” screen, click Next
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14

103
Page | 71
In the “DNS Server” screen you can read what DNS is and what it does, but we already know that,
read the “Things to note:” part, once done, click Next
Here we just have a confirmation of what we are installing and what features, click Install
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 72
You will see the installation progress, once done, click Close
Once the installation is done, DNS should be installed, you will also notice a new “DNS” tile in
your
Start screen.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 73
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 74
Practical No.9
Q9) Configure FTP and HTTP. Run Telnet and SSH.
Steps to install FTP Server on Windows Server 2012.
Step 1
First of all open your Server Manager. In the Server Manager you will find the option "Add Roles
and Features" on the front page. Click on it or you can go to the Manage option and then click "Add
Roles and Features", either way will open the same window.
Now a new window will be opened named "Add Roles and Features". First, some information about this window
will be given, then you can click on the "Next" button to start the process of adding a FTP Server.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 75
Step 2
The next page is for selecting the "Installation type". Select the first option and then click on
"Next".
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 76
On clicking, next the "Destination Server" page will be opened where you must select the server
from
the Server Pool. Here I have only one server in the Server Pool so my server is automatically
selected.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 77
Step 3
On the Next Page you had to select the Rolls that you want to install. Scroll down to "Web Server
IIS"
and click on it.
As you click on the Web Server IIS, a new window will be opened where you must select the "Add
Features" option.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 78
Step 4
The next page is for the features, you can select any feature you want to install or otherwise simply
click on the "Next" button without selecting anything like I do.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 79
The next page will provide you information about the Web Server IIS and will tell you what work
can
be done by it.
Step 5

104
Now for the main part where you must select the "Roll Services under Web Server IIS". Scroll
down
to the "FTP Server" and select it's "Services and Extensibility".
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 80
The next page is the "Confirmation page" that will show you your selections, you can check them
and
then click on Install to start the Installation process.
Now your Installation will begin that will require a few minutes depending on the processing power
of
your server.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 81
Telnet:
1. Telnet sends data in clear text format.
2. Either an access control list is filtering the Telnet session or the VTY password is not set on the
remote device, then Telnet to remote device is not possible.
3. By default, Cisco router support five simultaneous Telnet sessions.
The command Router(config)#line vty 0 4,from global configuration mode, will configure all the
default VTY ports(five default VTY lines) on a router.
4. To enable a telnet session to a router, the password must be set up through the VTY lines.
If you don’t set VTY password, the Cisco router will not allow telnet access.
To set VTY password:
Router(config)# line vty 0 4
Router(config-line)# password Aspell
Router(Config-line)# login
Or
Router(config)# line vty 0 4
Router(config-line)# login
Router(Config-line)# password Aspell
5. By default, users are not placed into privileged exec mode. A user going to be put into user exec
mode. Vty password and Enable secret password must be configured in order to connect by Telnet
to a properly secured Cisco Router.
The enable secret password always overwrites the enable password.
The following command places an incoming Telnet user directly into enable mode upon
successfully entering the password:
Router (config)# line vty 0 4
Router (config-line)# password Aspell
Router (config-line)# login
Router (config-line)#
Any user telneting, puts the password Aspell, its going to be put into user exec mode by default and
you might not want that, because you have to know the enable password to get to enable mode.
Use the command privilege level 15, allow telnet access to anyone who know the password Aspell
and
prompted to enable mode.
Router (config-line)# privilege level 15
Router (config-line)#
6. To keep open one or more Telnet sessions open at the same time, use the keystroke combination.
7. To end or terminate the Telnet session from a remote device, just type the command exit or
logout
from a VTY line The command show sessions will show active Telnet connections to neighbor and
remote devices.
105
Telnet with Packet Tracer:
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 82
Configure R1 router.
Router>en
Router#conf t
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#host R1
R1(config)#intfa 0/0
R1(config-if)#ip address 192.168.0.1 255.255.255.0
R1(config-if)#no shut
R1(config-if)#^Z
R1#
Configure R2 router.
Router>en
Router#conf t
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#host R2
R2(config)#intfa 0/0
R2(config-if)#ip address 192.168.0.2 255.255.255.0
R2(config-if)#no shut
R2(config-if)#exit
R2(config-if)#
Configure for telnet.
R2(config)#line vty 0 4
R2(config-line)#no login
R2(config-line)#^ZR2#
no login means that no login on vty lines i.e. no password require.
Telnet from R1.
R1#
R1#telnet 192.168.0.2
Trying 192.168.0.2 ...Open
R2>exit
[Connection to 192.168.0.2 closed by foreign host]
R1#
no password required.
Go back to R2 router and change rule to telnet using password.
R2#conf t
Enter configuration commands, one per line. End with CNTL/Z.
R2(config)#line vty 0 4
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 83
R2(config-line)#login
% Login disabled on line 66, until 'password' is set
% Login disabled on line 67, until 'password' is set
% Login disabled on line 68, until 'password' is set
% Login disabled on line 69, until 'password' is set
% Login disabled on line 70, until 'password' is set
R2(config-line)#
login says that if you require to telnet, you have to set password.
If there's no password, you can't telnet.
R2(config-line)#password 1234
106
R2(config-line)#exit
Go back to R1 router and try to telnet.
R1#telnet 192.168.0.2
Trying 192.168.0.2 ...Open
User Access Verification
Password:
R2>exit
[Connection to 192.168.0.2 closed by foreign host]
R1#
Entire department know this password.
How do this fix?
Let's go to R2 router.
Train the router to identify people and it should prompt username and password.
R2(config)#username Aspell password Aspell123
R2(config)#
We could use the keyword secret instead of password.
R2(config)#line vty 0 4
R2(config-line)#login local
R2(config-line)#
login local means that R2 router will use local database.
When telnet anyone, R2 prompt username and password for authentication.
Go to R1 router.
R1#telnet 192.168.0.2
Trying 192.168.0.2 ...Open
User Access Verification
Username: Aspell
Password:
R2>exit
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 84
[Connection to 192.168.0.2 closed by foreign host]
R1#
Telnet with packet tracer:
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 85
Configure router R1
Router>enable
Router#conf t
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#host R1
R1(config)#intfa 0/0
R1(config-if)#ip address 192.168.10.1 255.255.255.0
R1(config-if)#no shut
R1(config-if)#intfa 0/1
R1(config-if)#ip address 10.10.10.1 255.255.255.0
R1(config-if)#no shut
R1(config-if)#exit
R1(config)#
Configure router R2
Router>enable
Router#conf t
Enter configuration commands, one per line. End with CNTL/Z.

107
Router(config)#host R2
R2(config)#intfa 0/1
R2(config-if)#ip address 10.10.10.2 255.255.255.0
R2(config-if)#no shut
R2(config)#intfa 0/0
R2(config-if)#ip address 172.16.10.1 255.255.0.0
R2(config-if)#no shut
R2(config-if)#exit
R2(config)#
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 86
Configure static route on router R1
R1(config)#ip route 172.16.0.0 255.255.0.0 10.10.10.2
R1(config)#
Configure static route on router R2
R2(config)#ip route 192.168.10.0 255.255.255.0 10.10.10.1
R2(config)#
Configure telnet on router R2
R2(config)#line vty 0 4
R2(config-line)#login local
R2(config-line)#exit
R2(config)#
Create some users on router R2
R2(config)#username xxx password x123
R2(config)#username yyy password y123
R2(config)#username Admin ?
password Specify the password for the user
privilege Set user privilege level
secret Specify the secret for the user
<cr>
R2(config)#username Admin privilege ?
<0-15> User privilege level
R2(config)#username Admin privilege 15 ?
password Specify the password for the user
secret Specify the secret for the user
<cr>
R2(config)#username Admin privilege 15 secret ?
0 Specifies an UNENCRYPTED secret will follow
5 Specifies a HIDDEN secret will follow
LINE The UNENCRYPTED (cleartext) user secret
R2(config)#username Admin privilege 15 secret Aspell
R2(config)#
privilege 15 makes user go to directly hash prompt, not > prompt.
Go to PC-1 and try to telnet
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 87
PC>telnet 10.10.10.2
Trying 10.10.10.2 ...Open
User Access Verification
Username: xxx
Password:
R2>
Notice that user xxx can enter > prompt.
108
R2>exit
[Connection to 10.10.10.2 closed by foreign host]
PC>telnet 10.10.10.2
Trying 10.10.10.2 ...Open
User Access Verification
Username: Admin
Password:
R2#
Notice that user Admin directly go to # prompt.
This is the power of privilege 15 command.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 88
Practical No.10
Q10) Configure SMTP, POP3, IMAP and MIME.
How to Setup and Configure the SMTP Service for Windows Server 2012
Many applications depend on the internal Windows SMTP Service to relay email confirmations to
visitors browsing their web site. When using Windows Server 2012 the SMTP feature must be
installed and configured first. Below are the steps for installing the internal Windows SMTP
Service.
Install the SMTP Service
1 Launch the Server Manager.
2 From the Dashboard, click on Add Roles and Features to begin the wizard. Click Next on the first
screen.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 89
3 Select 'Role-based or feature-based installation'.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 90
4 Select the server.
5 Click Next to bypass the Roles selections.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 91
6 Scroll down the list and tick the 'SMTP Server' feature.
7 A new window will pop up to inform you that some other services will also be installed. Click
Add
Features to confirm and continue.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 92
8 Click Next to continue past the features selection screen.
9 Click Install to complete the installation.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 93
10 Click Close when the installation has completed.
Configure the SMTP Service
1 Launch the Internet Information Services (IIS) 6.0 Manager.
2 Click Yes to the UAC Prompt.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 94
3 Right-click on SMTP Virtual Server #1 and select Properties.
4 Select the General tab and change the IP Address to the server’s IP address.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 95
5 Select the Access tab and click on the Connection button.
109
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 96
6 In the Connection window, select 'Only the list below' and click the Add button.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 97
7Add the IP address, Group of computers or Domain of the devices permitted to use the internal
SMTP, then click OK.
8 In the Access tab of the Connection window, click the Relay button. Add the same permitted
devices
to the Relay Restrictions list.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 98
9 In the Delivery tab of the Connection window, set an external domain.
10 Launch the Windows Firewall with Advanced Security console.
11 Right-click on 'Inbound Rule' and select 'New Rule' to begin the wizard.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 99
12 Select 'Port' and click Next.
13 Set the local port to 25 and click Next.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 100
14 Choose 'Allow the connection' and click Next.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 101
15 Uncheck 'Public' to prevent external access to the server. Click Next.
16 Give the rule a name, and click Finish.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 102
17 You should now see a new rule enabled in the firewall management console.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 103
18 In the Server Manager, click on Tools and select Services.
19 In the Services window, double-click on 'Simple Mail Transfer Protocol (SMTP)'.
TYBSc.I.T,Semester VI Internet Technologies - Practical Manual 2013-14
Page | 104
20 Stop and then Start the service. Set the Startup type to Automatic.
20 Click OK to finish. The internal SMTP service is now ready and listening.

24. Write a socket program to get the current date and time from the server.

1. SERVER:

2. #include"netinet/in.h"

3. #include"sys/socket.h"#include"stdio.h"

4. #include"string.h"

5. #include"time.h"

110
6. main( )

7. {

8. struct sockaddr_in sa;

9. struct sockaddr_in cli;int sockfd,conntfd;int len,ch;char str[100];

10. time_t tick;

11. sockfd=socket(AF_INET,SOCK_STREAM,0);

12. if(sockfd<0)

13. {

14. printf("error in socket\n");

15. exit(0);

16. }

17. else printf("Socket opened");

18. bzero(&sa,sizeof(sa));

19. sa.sin_port=htons(5600);

20. sa.sin_addr.s_addr=htonl(0);

21. if(bind(sockfd,(struct sockaddr*)&sa,sizeof(sa))<0)

22. {

23. printf("Error in binding\n");

24. }

25. else

26. printf("Binded Successfully");

27. listen(sockfd,50);

28. for(;;)

29. {

30. len=sizeof(ch);

31. conntfd=accept(sockfd,(struct sockaddr*)&cli,&len);

32. printf("Accepted");

33. tick=time(NULL);

34. snprintf(str,sizeof(str),"%s",ctime(&tick));

35. printf("%s",str);write(conntfd,str,100);

111
36. }

37. }

1.

2. CLIENT:

3. #include"netinet/in.h"

4. #include"sys/socket.h"

5. #include"stdio.h"

6. main()

7. {

8. struct sockaddr_in sa,cli;

9. int n,sockfd;

10. int len;char buff[100];

11. sockfd=socket(AF_INET,SOCK_STREAM,0);

12. if(sockfd<0){ printf("\nError in Socket");

13. exit(0);

14. }

15. else printf("\nSocket is Opened");

16. bzero(&sa,sizeof(sa));

17. sa.sin_family=AF_INET;

18. sa.sin_port=htons(5600);

19. if(connect(sockfd,(struct sockaddr*)&sa,sizeof(sa))<0)

20. {

21. printf("\nError in connection failed");

22. exit(0);

23. }

24. else

25. printf("\nconnected successfully");

26. if(n=read(sockfd,buff,sizeof(buff))<0)

112
27. {

28. printf("\nError in Reading");

29. exit(0);

30. }

31. else

32. {printf("\nMessage Read %s",buff);

33. }}

34.

SERVER SIDE:
[shanthi@linuxserver ~]$ cc tcpcd.c
[shanthi@linuxserver ~]$ cc tcpcd.c -o ll
[shanthi@linuxserver ~]$ ./ll
Socket is Openedconnected successfully
Message Read Fri Sep 24 15:16:26 2010
[shanthi@linuxserver ~]$
CLIENT SIDE:
[shanthi@linuxserver ~]$ cc tcpd.c
[shanthi@linuxserver ~]$ cc tcpd.c -o kk
[shanthi@linuxserver ~]$ ./kk
SocketOpenedBinded SuccessfullyAccepted
Fri Sep 24 15:16:26 2010

Write a socket program where the client will send lowercase letters and the server will return
uppercase letter.
Problem Statement : Program to perform TCP client and server application to convert
lower case string to upper case string.
Lowercase to Uppercase String by TCP client and server program consist of client and
server programs. Client will send the character to the server and upon receiving server
will convert character to uppercase . These characters will be again send back to client
and will be printed to screen by client.
Client.c is the Client program which will interact with the Client.
Server.c is the Server program which listen the Client and convert the lowercase
characters to Uppercase.

Lowercase to Uppercase String by TCP : Client Program

1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <sys/types.h>

113
4 #include <sys/socket.h>
5 #include <netinet/in.h>
6 #include <arpa/inet.h>
7 #include <unistd.h>
8
9 int main(int argc, char **argv)
10 {
11 int clnt_fd;
12 struct sockaddr_in serv_addr;
13 char c;
14 // create socket
15 clnt_fd = socket(AF_INET, SOCK_STREAM, 0);
16 // prepare for connect
17 serv_addr.sin_family = AF_INET;
18 serv_addr.sin_port = htons(atoi(argv[2]));
19 serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
20 // connect to echo server
21 connect(clnt_fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
22 // write to echo server
23 while ((c = (char) getchar()) != EOF)
24 {
25 // read from keyboard
26 write(clnt_fd, &c, 1); // write to echo server
27 read(clnt_fd, &c, 1); // read from echo server
28 putchar((int) c); // write to monitor
29 }
30 close(clnt_fd);
31 return 0;
32 }
[button style=”large green embossed”
link=”https://sites.google.com/site/codesgeeks/codesgeek_1/Convert%20Lowercase%20
to%20Uppercase%20String-client.c” target=”_blank” ]Client Code Download[/button]

Lowercase to Uppercase String by TCP : Server Program

1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <sys/types.h>
5 #include <sys/socket.h>
6 #include <netinet/in.h>
7 #include <arpa/inet.h>
8 #include <unistd.h>
9
10 int main(int argc, char **argv)
11 {
12 int serv_fd, clnt_fd;
13 struct sockaddr_in serv_addr;
14 char c,d;
15 serv_fd = socket(AF_INET, SOCK_STREAM, 0);
16 serv_addr.sin_family = AF_INET;
17 serv_addr.sin_port = htons(atoi(argv[1]));
18 serv_addr.sin_addr.s_addr = INADDR_ANY;
19 bind(serv_fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
20 listen(serv_fd, 1);
21 clnt_fd = accept(serv_fd, NULL, NULL);
22 while (read(clnt_fd, &c, 1))
23 {
24 d=toupper(c);

114
25 write(clnt_fd, &d, 1);
26 }
27 close(clnt_fd);
28 close(serv_fd);
29 return 0;
30 }
[button style=”large green embossed”
link=”https://sites.google.com/site/codesgeeks/codesgeek_1/Convert%20Lowercase%20
to%20Uppercase%20String-server.c” target=”_blank” ]Server Code Download[/button]
Lowercase to Uppercase String by TCP Output
Sample Output 1
mint@mint ~ $ ./client
127.0.0.1 5000
hello
HELLO
mint@mint ~ $. /Server
5000
Sample Output 2
mint@mint ~ $ ./client
127.0.0.1 5000
welcome
WELCOME
mint@mint ~ $. /Server
5000

26. Write a server and a client program to implement TCP chat server-client.

SERVER
#include<stdio.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netdb.h>
#include<stdlib.h>
#include<string.h>
#define MAX 80
#define PORT 43454
#define SA struct sockaddr
void func(int sockfd)
{
char buff[MAX];
int n;
for(;;)
{
bzero(buff,MAX);
read(sockfd,buff,sizeof(buff));
115
printf("From client: %s\t To client : ",buff);
bzero(buff,MAX);
n=0;
while((buff[n++]=getchar())!='\n');
write(sockfd,buff,sizeof(buff));
if(strncmp("exit",buff,4)==0)
{
printf("Server Exit...\n");
break;
}
}
}
int main()
{
int sockfd,connfd,len;
struct sockaddr_in servaddr,cli;
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd==-1)
{
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(PORT);
if((bind(sockfd,(SA*)&servaddr, sizeof(servaddr)))!=0)
{
printf("socket bind failed...\n");
exit(0);
}
else
printf("Socket successfully binded..\n");
if((listen(sockfd,5))!=0)
{
printf("Listen failed...\n");
exit(0);
}
else
printf("Server listening..\n");
len=sizeof(cli);
connfd=accept(sockfd,(SA *)&cli,&len);
if(connfd<0)
{
116
printf("server acccept failed...\n");
exit(0);
}
else
printf("server acccept the client...\n");
func(connfd);
close(sockfd);
}

CLIENT
#include<stdio.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netdb.h>
#include<string.h>
#include<stdlib.h>
#define MAX 80
#define PORT 43454
#define SA struct sockaddr
void func(int sockfd)
{
char buff[MAX];
int n;
for(;;)
{
bzero(buff,sizeof(buff));
printf("Enter the string : ");
n=0;
while((buff[n++]=getchar())!='\n');
write(sockfd,buff,sizeof(buff));
bzero(buff,sizeof(buff));
read(sockfd,buff,sizeof(buff));
printf("From Server : %s",buff);
if((strncmp(buff,"exit",4))==0)
{
printf("Client Exit...\n");
break;
}
}
}

int main()
{
int sockfd,connfd;
117
struct sockaddr_in servaddr,cli;
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd==-1)
{
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
servaddr.sin_port=htons(PORT);
if(connect(sockfd,(SA *)&servaddr,sizeof(servaddr))!=0)
{
printf("connection with the server failed...\n");
exit(0);
}
else
printf("connected to the server..\n");
func(sockfd);
close(sockfd);
}

OUTPUT
SERVER SIDE
$ cc tcpchatserver.c
$ ./a.out
Socket successfully created..
Socket successfully binded..
Server listening..
server acccept the client...
From client: hai
To client : hello
From client: exit
To client : exit
Server Exit...
$

CLIENT SIDE
$ cc tcpchatclient.c
$ ./a.out
Socket successfully created..
connected to the server..
Enter the string : hai
118
From Server : hello
Enter the string : exit
From Server : exit
Client Exit...

RMI called as remote method innovaction,by using rmi to develop

calculator program in java

Solution
Calc.java
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface calc extends Remote
{
public long addition(long a,long b)throws RemoteException;
public long subtraction(long a,long b)throws RemoteException;
public long multiplication(long a,long b)throws RemoteException;
public long divition(long a,long b)throws RemoteException;
}

calcimpl.java
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class calcimpl extends UnicastRemoteObject implements calc
{
protected calcimpl() throws RemoteException
{
super();
}
public long addition(long a,long b)throws RemoteException
{
return a+b;

119
}
public long subtraction(long a,long b)throws RemoteException
{
return a-b;
}
public long multiplication(long a,long b)throws RemoteException
{
return a*b;
}
public long divition(long a,long b)throws RemoteException
{
return a/b;
}
}

calcserv.java
import java.rmi.Naming;
public class calcserv
{
calcserv()
{
try{
calc c=new calcimpl();
Naming.rebind("rmi://localhost:1099/calcservice",c);
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
public static void main(String arg[])
{
new calcserv();
}
120
}

calclaint.java
import java.rmi.Naming;
public class calccli
{
public static void main(String arg[])
{
try{
calc c=(calc)Naming.lookup("//127.0.0.1:1099/calcservice");
System.out.println("Addition:"+c.addition(10,5));
System.out.println("subtraction:"+c.subtraction(10,5));
System.out.println("Multiplication:"+c.multiplication(10,5));
System.out.println("Divition:"+c.divition(10,5));
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
}

Java program of Client-Server network for Chatting between Client


and Server
1 import java.net.*;
2 import java.io.*;
3
4 public class chatserver
5 {
6 public static void main(String args[]) throws Exception
7 {
8 ServerSocket ss=new ServerSocket(2000);
9 Socket sk=ss.accept();
10 BufferedReader
11 cin=newBufferedReader(newInputStreamReader(sk.getInputStream()));

121
12 PrintStream cout=new PrintStream(sk.getOutputStream());
13 BufferedReader stdin=new BufferedReader(new
14 InputStreamReader(System.in));
15 String s;
16 while ( true )
17 {
18 s=cin.readLine();
19 if (s.equalsIgnoreCase("END"))
20 {
21 cout.println("BYE");
22 break;
23 }
24 System. out.print("Client : "+s+"\n");
25 System.out.print("Server : ");
26 s=stdin.readLine();
27 cout.println(s);
28 }
29 ss.close();
30 sk.close();
31 cin.close();
32 cout.close();
33 stdin.close();
34 }
35 }
36
37 public class chatclient
38 {
39 public static void main(String args[]) throws Exception
40 {
41 Socket sk=new Socket("192.168.0.19",2000);
42 BufferedReader sin=new BufferedReader(new
43 InputStreamReader(sk.getInputStream()));
44 PrintStream sout=new PrintStream(sk.getOutputStream());
45 BufferedReader stdin=new BufferedReader(new
46 InputStreamReader(System.in));
47 String s;
48 while ( true )
49 {
50 System.out.print("Client : ");
51 s=stdin.readLine();
52 sout.println(s);
53 s=sin.readLine();
54 System.out.print("Server : "+s+"\n");
55 if ( s.equalsIgnoreCase("BYE") )
56 break;
57 }
58 sk.close();
59 sin.close();
sout.close();
stdin.close();
}
}

Output:

Java chatclient

From Server : Hi
From Client: Hi

122
From Server: Good morning
From Client: End

HTML

123
What is HTML?
HTML is the standard markup language for creating Web pages.

 HTML stands for Hyper Text Markup Language

 HTML describes the structure of Web pages using markup

 HTML elements are the building blocks of HTML pages

 HTML elements are represented by tags

 HTML tags label pieces of content such as "heading", "paragraph", "table", and so on

 Browsers do not display the HTML tags, but use them to render the content of the page

A Simple HTML Document


Example
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>My First Heading</h1>


<p>My first paragraph.</p>

</body>
</html>

Example Explained
 The <!DOCTYPE html> declaration defines this document to be HTML5

 The <html> element is the root element of an HTML page

 The <head> element contains meta information about the document

 The <title> element specifies a title for the document


124
 The <body> element contains the visible page content

 The <h1> element defines a large heading

 The <p> element defines a paragraph

HTML Tags
HTML tags are element names surrounded by angle brackets:

<tagname>content goes here...</tagname>

 HTML tags normally come in pairs like <p> and </p>

 The first tag in a pair is the start tag, the second tag is the end tag

 The end tag is written like the start tag, but with a forward slash inserted before the tag name

Tip: The start tag is also called the opening tag, and the end tag the closing tag.

Web Browsers
The purpose of a web browser (Chrome, IE, Firefox, Safari) is to read HTML documents and display
them.

The browser does not display the HTML tags, but uses them to determine how to display the document:

HTML Page Structure


Below is a visualization of an HTML page structure:
<html>
<head>
<title>Page title</title>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
Note: Only the content inside the <body> section (the white area above) is displayed in a browser

The <!DOCTYPE> Declaration


The <!DOCTYPE> declaration represents the document type, and helps browsers to display web pages
correctly.

It must only appear once, at the top of the page (before any HTML tags).

125
The <!DOCTYPE> declaration is not case sensitive.

The <!DOCTYPE> declaration for HTML5 is:


<!DOCTYPE html>

HTML Editor

Write HTML Using Notepad or TextEdit


Web pages can be created and modified by using professional HTML editors.

However, for learning HTML we recommend a simple text editor like Notepad (PC) or TextEdit (Mac).

We believe using a simple text editor is a good way to learn HTML.

Follow the four steps below to create your first web page with Notepad or TextEdi

Step 1: Open Notepad (PC)


Windows 8 or later:
Open the Start Screen (the window symbol at the bottom left on your screen). Type Notepad.

Windows 7 or earlier:
Open Start > Programs > Accessories > Notepad

Step 1: Open TextEdit (Mac)


Open Finder > Applications > TextEdit

Also change some preferences to get the application to save files correctly. In Preferences > Format
> choose "Plain Text"

Then under "Open and Save", check the box that says "Display HTML files as HTML code instead of
formatted text".

Then open a new document to place the code.

Step 2: Write Some HTML


Write or copy some HTML into Notepad.
<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>

<p>My first paragraph.</p>

126
</body>
</html>

Step 3: Save the HTML Page


Save the file on your computer. Select File > Save as in the Notepad menu.

Name the file "index.htm" and set the encoding to UTF-8 (which is the preferred encoding for HTML
files).

You can use either .htm or .html as file extension. There is no difference, it is up to you.

Step 4: View the HTML Page in Your Browser


Open the saved HTML file in your favorite browser (double click on the file, or right-click - and choose
"Open with").

The result will look much like this:

Example
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>This is a Heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

HTML Basic Example


Don't worry if these examples use tags you have not learned.
You will learn about them in the next chapters.

HTML Documents
All HTML documents must start with a document type declaration: <!DOCTYPE html>.

The HTML document itself begins with <html> and ends with </html>.

127
The visible part of the HTML document is between <body> and </body>.

Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>


<p>My first paragraph.</p>

</body>
</html>

HTML Headings
HTML headings are defined with the <h1> to <h6> tags.

<h1> defines the most important heading. <h6> defines the least important heading:

Example
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>

HTML Paragraphs
HTML paragraphs are defined with the <p> tag:

Example
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

HTML Links
HTML links are defined with the <a> tag:

Example
<a href="https://www.w3schools.com">This is a link</a>

The link's destination is specified in the href attribute.

Attributes are used to provide additional information about HTML elements.

128
You will learn more about attributes in a later chapter

HTML Images
HTML images are defined with the <img> tag.

The source file (src), alternative text (alt), width, and height are provided as attributes:

Example
<img src="w3schools.jpg" alt="W3Schools.com" width="104" height="142"

HTML Buttons
HTML buttons are defined with the <button> tag:

Example
<button>Click me</button>

HTML Lists
HTML lists are defined with the <ul> (unordered/bullet list) or the <ol> (ordered/numbered list) tag,
followed by <li> tags (list items):

Example
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>

HTML Elements
HTML Elements
An HTML element usually consists of a start tag and end tag, with the content inserted in between:
<tagname>Content goes here...</tagname>
The HTML element is everything from the start tag to the end tag:
<p>My first paragraph.</p>

129
Start tag Element content End tag

<h1> My First Heading </h1>

<p> My first paragraph. </p>

<br>

HTML elements with no content are called empty elements. Empty elements do not have an end tag,
such as the <br> element (which indicates a line break).

Nested HTML Elements


HTML elements can be nested (elements can contain elements).

All HTML documents consist of nested HTML elements.

This example contains four HTML elements:

Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>


<p>My first paragraph.</p>

</body>
</html>

Example Explained
The <html> element defines the whole document.

It has a start tag <html> and an end tag </html>.

The element content is another HTML element (the <body> element).


<html>
<body>

130
<h1>My First Heading</h1>
<p>My first paragraph.</p>

</body>
</html>
The <body> element defines the document body.

It has a start tag <body> and an end tag </body>.

The element content is two other HTML elements (<h1> and <p>).
<body>

<h1>My First Heading</h1>


<p>My first paragraph.</p>

</body>
The <h1> element defines a heading.

It has a start tag <h1> and an end tag </h1>.

The element content is: My First Heading.


<h1>My First Heading</h1>
The <p> element defines a paragraph.

It has a start tag <p> and an end tag </p>.

The element content is: My first paragraph.


<p>My first paragraph.</p>

Do Not Forget the End Tag


Some HTML elements will display correctly, even if you forget the end tag:

Example
<html>
<body>

<p>This is a paragraph
<p>This is a paragraph

</body>
</html>

131
The example above works in all browsers, because the closing tag is considered optional.

Never rely on this. It might produce unexpected results and/or errors if you forget the end tag.

Empty HTML Elements


HTML elements with no content are called empty elements.

<br> is an empty element without a closing tag (the <br> tag defines a line break).
Empty elements can be "closed" in the opening tag like this: <br />.

HTML5 does not require empty elements to be closed. But if you want stricter validation, or if you need
to make your document readable by XML parsers, you must close all HTML elements properly.

Use Lowercase Tags


HTML tags are not case sensitive: <P> means the same as <p>.

The HTML5 standard does not require lowercase tags, but W3C recommends lowercase in HTML,
and demandslowercase for stricter document types like XHTML.

HTML Attributes
Attributes provide additional information about HTML elements.

HTML Attributes
 All HTML elements can have attributes

 Attributes provide additional information about an element

 Attributes are always specified in the start tag

 Attributes usually come in name/value pairs like: name="value

The href Attribute


HTML links are defined with the <a> tag. The link address is specified in the href attribute:

Example
<a href="https://www.w3schools.com">This is a link</a>

You will learn more about links and the <a> tag later in this tutorial.

132
The src Attribute
HTML images are defined with the <img> tag.

The filename of the image source is specified in the src attribute:

Example
<img src="img_girl.jpg">

The width and height Attributes


Images in HTML have a set of size attributes, which specifies the width and height of the image:

Example
<img src="img_girl.jpg" width="500" height="600">
The image size is specified in pixels: width="500" means 500 pixels wide.

You will learn more about images in our HTML Images chapter.

The alt Attribute


The alt attribute specifies an alternative text to be used, when an image cannot be displayed.

The value of the attribute can be read by screen readers. This way, someone "listening" to the webpage,
e.g. a blind person, can "hear" the element.

Example
<img src="img_girl.jpg" alt="Girl with a jacket">

The alt attribute is also useful if the image does not exist:

Example
See what happens if we try to display an image that does not exist:
<img src="img_typo.jpg" alt="Girl with a jacket"

The style Attribute


The style attribute is used to specify the styling of an element, like color, font, size etc.

Example
<p style="color:red">I am a paragraph</p>
133
You will learn more about styling later in this tutorial, and in our CSS Tutorial

The lang Attribute


The language of the document can be declared in the <html> tag.

The language is declared with the lang attribute.

Declaring a language is important for accessibility applications (screen readers) and search engines:
<!DOCTYPE html>
<html lang="en-US">
<body>

...

</body>
</html>
The first two letters specify the language (en). If there is a dialect, use two more letters (US).

The title Attribute


Here, a title attribute is added to the <p> element. The value of the title attribute will be displayed as a
tooltip when you mouse over the paragraph:

Example
<p title="I'm a tooltip">
This is a paragraph.
</p>

Use Lowercase Attributes


The HTML5 standard does not require lowercase attribute names.

The title attribute can be written with uppercase or lowercase like title or TITLE.

W3C recommends lowercase in HTML, and demands lowercase for stricter document types like
XHTML.

At W3Schools we always use lowercase attribute names.

We Suggest: Quote Attribute Values


134
The HTML5 standard does not require quotes around attribute values.

The href attribute, demonstrated above, can be written without quotes:

Bad
<a href=https://www.w3schools.com>

Good
<a href="https://www.w3schools.com"
W3C recommends quotes in HTML, and demands quotes for stricter document types like XHTML.

Sometimes it is necessary to use quotes. This example will not display the title attribute correctly,
because it contains a space:

Example
<p title=About W3Schools>

Using quotes are the most common. Omitting quotes can produce errors.
At W3Schools we always use quotes around attribute values.

Single or Double Quotes?


Double quotes around attribute values are the most common in HTML, but single quotes can also be
used.

In some situations, when the attribute value itself contains double quotes, it is necessary to use single
quotes:
<p title='John "ShotGun" Nelson'>
Or vice versa:
<p title="John 'ShotGun' Nelson">

HTML Attributes
Below is an alphabetical list of some attributes often used in HTML:

Attribute Description

alt Specifies an alternative text for an image, when the image cannot be displayed

135
disabled Specifies that an input element should be disabled

href Specifies the URL (web address) for a link

id Specifies a unique id for an element

src Specifies the URL (web address) for an image

style Specifies an inline CSS style for an element

title Specifies extra information about an element (displayed as a tool tip)

HTML Attribute
Attributes provide additional information about HTML element

HTML Attributes
 All HTML elements can have attributes

 Attributes provide additional information about an element

 Attributes are always specified in the start tag

 Attributes usually come in name/value pairs like: name="value

The href Attribute


HTML links are defined with the <a> tag. The link address is specified in the href attribute:

Example
<a href="https://www.w3schools.com">This is a link</a>
You will learn more about links and the <a> tag later in this tutorial.

136
The src Attribute
HTML images are defined with the <img> tag.

The filename of the image source is specified in the src attribute:

Example
<img src="img_girl.jpg">

The width and height Attributes


Images in HTML have a set of size attributes, which specifies the width and height of the image:

Example
<img src="img_girl.jpg" width="500" height="600">

The image size is specified in pixels: width="500" means 500 pixels wide.

You will learn more about images in our HTML Images chapter.

The alt Attribute


The alt attribute specifies an alternative text to be used, when an image cannot be displayed.

The value of the attribute can be read by screen readers. This way, someone "listening" to the webpage,
e.g. a blind person, can "hear" the element.

Example
<img src="img_girl.jpg" alt="Girl with a jacket">

The alt attribute is also useful if the image does not exist:

Example
See what happens if we try to display an image that does not exist:
<img src="img_typo.jpg" alt="Girl with a jacket">

137
The style Attribute
The style attribute is used to specify the styling of an element, like color, font, size etc.

Example
<p style="color:red">I am a paragraph</p>

You will learn more about styling later in this tutorial, and in our CSS Tutorial.

The lang Attribute


The language of the document can be declared in the <html> tag.

The language is declared with the lang attribute.

Declaring a language is important for accessibility applications (screen readers) and search engines:
<!DOCTYPE html>
<html lang="en-US">
<body>

...

</body>
</html>
The first two letters specify the language (en). If there is a dialect, use two more letters (US).

The title Attribute


Here, a title attribute is added to the <p> element. The value of the title attribute will be displayed as a
tooltip when you mouse over the paragraph:

Example
<p title="I'm a tooltip">
This is a paragraph.
</p>

The HTML5 standard does not require lowercase attribute names.

The title attribute can be written with uppercase or lowercase like title or TITLE.
138
W3C recommends lowercase in HTML, and demands lowercase for stricter document types like
XHTML.

At W3Schools we always use lowercase attribute names.

We Suggest: Quote Attribute Values


The HTML5 standard does not require quotes around attribute values.

The href attribute, demonstrated above, can be written without quotes:

Bad
<a href=https://www.w3schools.com>

Good
<a href="https://www.w3schools.com">

W3C recommends quotes in HTML, and demands quotes for stricter document types like XHTML.

Sometimes it is necessary to use quotes. This example will not display the title attribute correctly,
because it contains a space:

Example
<p title=About W3Schools>

Using quotes are the most common. Omitting quotes can produce errors.
At W3Schools we always use quotes around attribute values.

Single or Double Quotes?


Double quotes around attribute values are the most common in HTML, but single quotes can also be
used.

In some situations, when the attribute value itself contains double quotes, it is necessary to use single
quotes:
<p title='John "ShotGun" Nelson'>
Or vice versa:
<p title="John 'ShotGun' Nelson

139
Test Yourself with Exercise
HTML Attributes
Below is an alphabetical list of some attributes often used in HTML:

Attribute Description

alt Specifies an alternative text for an image, when the image cannot be displayed

disabled Specifies that an input element should be disabled

href Specifies the URL (web address) for a link

id Specifies a unique id for an element

src Specifies the URL (web address) for an image

style Specifies an inline CSS style for an element

title Specifies extra information about an element (displayed as a tool tip)

HTML Paragraphs
The HTML <p> element defines a paragraph:

Example
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

Note: Browsers automatically add some white space (a margin) before and after a paragraph.

140
HTML Display
You cannot be sure how HTML will be displayed.
Large or small screens, and resized windows will create different results.
With HTML, you cannot change the output by adding extra spaces or extra lines in your HTML
code.
The browser will remove any extra spaces and extra lines when the page is displayed:

Example
<p>
This paragraph
contains a lot of lines
in the source code,
but the browser
ignores it.
</p>

<p>
This paragraph
contains a lot of spaces
in the source code,
but the browser
ignores it.
</p>

Don't Forget the End Tag


Most browsers will display HTML correctly even if you forget the end tag:

Example
<p>This is a paragraph.
<p>This is another paragraph.
The example above will work in most browsers, but do not rely on it.
Note: Dropping the end tag can produce unexpected results or errors.

HTML Line Breaks


The HTML <br> element defines a line break.

Use <br> if you want a line break (a new line) without starting a new paragraph:

141
Example
<p>This is<br>a paragraph<br>with line breaks.</p>
The <br> tag is an empty tag, which means that it has no end tag.

The Poem Problem


This poem will display on a single line:

Example
<p>
My Bonnie lies over the ocean.

My Bonnie lies over the sea.

My Bonnie lies over the ocean.

Oh, bring back my Bonnie to me.


</p>

The HTML <pre> Element


The HTML <pre> element defines preformatted text.

The text inside a <pre> element is displayed in a fixed-width font (usually Courier), and it
preserves both spaces and line breaks:

Example
<pre>
My Bonnie lies over the ocean.

My Bonnie lies over the sea.

My Bonnie lies over the ocean.

Oh, bring back my Bonnie to me.


</pre>

142
HTML Tag Reference
W3Schools' tag reference contains additional information about HTML elements and their
attributes.

Tag Description

<p> Defines a paragraph

<br> Inserts a single line break

<pre> Defines pre-formatted text

HTML Styles
Example
I am Red
I am Blue

I am Big
The HTML Style Attribute
Setting the style of an HTML element, can be done with the style attribute.

The HTML style attribute has the following syntax:


<tagname style="property:value;">
The property is a CSS property. The value is a CSS value.

You will learn more about CSS later in this tutorial.

HTML Background Color


143
The background-color property defines the background color for an HTML element.

This example sets the background color for a page to powderblue:

Example
<body style="background-color:powderblue;">

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>

HTML Text Color


The color property defines the text color for an HTML element:

Example
<h1 style="color:blue;">This is a heading</h1>
<p style="color:red;">This is a paragraph.</p>

HTML Fonts
The font-family property defines the font to be used for an HTML element:

Example
<h1 style="font-family:verdana;">This is a heading</h1>
<p style="font-family:courier;">This is a paragraph.</p>

HTML Text Size


The font-size property defines the text size for an HTML element:

Example
<h1 style="font-size:300%;">This is a heading</h1>
<p style="font-size:160%;">This is a paragraph.</p>

HTML Text Alignment


The text-align property defines the horizontal text alignment for an HTML element:

Example
<h1 style="text-align:center;">Centered Heading</h1>
<p style="text-align:center;">Centered paragraph.</p>

144
HTML Text Formatting
Text Formatting
This text is bold
This text is italic

This is subscript and superscript

HTML Formatting Elements


In the previous chapter, you learned about the HTML style attribute.

HTML also defines special elements for defining text with a special meaning.

HTML uses elements like <b> and <i> for formatting output, like bold or italic text.

Formatting elements were designed to display special types of text:

 <b> - Bold text


 <strong> - Important text
 <i> - Italic text
 <em> - Emphasized text
 <mark> - Marked text
 <small> - Small text
 <del> - Deleted text
 <ins> - Inserted text
 <sub> - Subscript text
 <sup> - Superscript text

HTML <b> and <strong> Elements


The HTML <b> element defines bold text, without any extra importance.

Example
<b>This text is bold</b>
The HTML <strong> element defines strong text, with added semantic "strong" importance.

145
Example
<strong>This text is strong</strong>

HTML <i> and <em> Elements


The HTML <i> element defines italic text, without any extra importance.

Example
<i>This text is italic</i>

The HTML <em> element defines emphasized text, with added semantic importance.

Example
<em>This text is emphasized</em>

Note: Browsers display <strong> as <b>, and <em> as <i>. However, there is a difference in the
meaning of these tags: <b> and <i> defines bold and italic text, but <strong> and <em> means that the
text is "important".

HTML <small> Element


The HTML <small> element defines smaller text:

Example
<h2>HTML <small>Small</small> Formatting</h2>

HTML <mark> Element


The HTML <mark> element defines marked or highlighted text:

Example
<h2>HTML <mark>Marked</mark> Formatting</h2>

146
HTML <del> Element
The HTML <del> element defines deleted (removed) text.

Example
<p>My favorite color is <del>blue</del> red.</p>

HTML <ins> Element


The HTML <ins> element defines inserted (added) text.

Example
<p>My favorite <ins>color</ins> is red.</p

HTML <sub> Element


The HTML <sub> element defines subscripted text.

Example
<p>This is <sub>subscripted</sub> text.</p>

HTML <sup> Element


The HTML <sup> element defines superscripted text.

Example
<p>This is <sup>superscripted</sup> text.</p>

HTML Text Formatting Elements


Tag Description

147
<b> Defines bold text

<em> Defines emphasized text

<i> Defines italic text

<small> Defines smaller text

<strong> Defines important text

<sub> Defines subscripted text

<sup> Defines superscripted text

<ins> Defines inserted text

<del> Defines deleted text

<mark> Defines marked/highlighted text

HTML Quotation and Citation Elements


Quotation
Here is a quote from WWF's website:
148
For 50 years, WWF has been protecting the future of nature. The world's leading conservation
organization, WWF works in 100 countries and is supported by 1.2 million members in the United
States and close to 5 million globally.

HTML <q> for Short Quotations


The HTML <q> element defines a short quotation.

Browsers usually insert quotation marks around the <q> element.

Example
<p>WWF's goal is to: <q>Build a future where people live in harmony with nature.</q></p>

HTML <blockquote> for Quotations


The HTML <blockquote> element defines a section that is quoted from another source.

Browsers usually indent <blockquote> elements.

Example
<p>Here is a quote from WWF's website:</p>
<blockquote cite="http://www.worldwildlife.org/who/index.html">
For 50 years, WWF has been protecting the future of nature.
The world's leading conservation organization,
WWF works in 100 countries and is supported by
1.2 million members in the United States and
close to 5 million globally.
</blockquote>

HTML <abbr> for Abbreviations


The HTML <abbr> element defines an abbreviation or an acronym.

Marking abbreviations can give useful information to browsers, translation systems and search-engines.

149
Example
<p>The <abbr title="World Health Organization">WHO</abbr> was founded in 1948.</p>

HTML <address> for Contact Information


The HTML <address> element defines contact information (author/owner) of a document or an article.

The <address> element is usually displayed in italic. Most browsers will add a line break before and
after the element.

Example
<address>
Written by John Doe.<br>
Visit us at:<br>
Example.com<br>
Box 564, Disneyland<br>
USA
</address>

HTML <cite> for Work Title


The HTML <cite> element defines the title of a work.

Browsers usually display <cite> elements in italic.

Example
<p><cite>The Scream</cite> by Edvard Munch. Painted in 1893.</p>

HTML <bdo> for Bi-Directional Override


The HTML <bdo> element defines bi-directional override.

The <bdo> element is used to override the current text direction:

Example
<bdo dir="rtl">This text will be written from right to left</bdo>

HTML Quotation and Citation Elements

150
Tag Description

<abbr> Defines an abbreviation or acronym

<address> Defines contact information for the author/owner of a document

<bdo> Defines the text direction

<blockquote> Defines a section that is quoted from another source

<cite> Defines the title of a work

<q> Defines a short inline quotation

HTML Comments
Comment tags are used to insert comments in the HTML source code

HTML Comment Tags


You can add comments to your HTML source by using the following syntax:
<!-- Write your comments here -->
Notice that there is an exclamation point (!) in the opening tag, but not in the closing tag.

Note: Comments are not displayed by the browser, but they can help document your HTML source
code.

With comments you can place notifications and reminders in your HTML:
151
Example
<!-- This is a comment -->

<p>This is a paragraph.</p>

<!-- Remember to add more information here -->


Comments are also great for debugging HTML, because you can comment out HTML lines of code, one
at a time, to search for errors:

Example
<!-- Do not display this at the moment
<img border="0" src="pic_trulli.jpg" alt="Trulli">
-->

HTML Color
HTML colors are specified using predefined color names, or RGB, HEX, HSL, RGBA, HSLA
values.

Color Names
In HTML, a color can be specified by using a color name:

Tomato

Orange

DodgerBlue

MediumSeaGreen

Gray
152
SlateBlue

VioletLightGray
HTML supports 140 standard color names.

Background Color
You can set the background color for HTML elements:

Hello World

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut
laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation
ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

Example
<h1 style="background-color:DodgerBlue;">Hello World</h1>
<p style="background-color:Tomato;">Lorem ipsum...</p>

Text Color
You can set the color of text:

Hello World
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut
laoreet dolore magna aliquam erat volutpat.

Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex
ea commodo consequat.

Example
<h1 style="color:Tomato;">Hello World</h1>
<p style="color:DodgerBlue;">Lorem ipsum...</p>

153
<p style="color:MediumSeaGreen;">Ut wisi enim...</p>

Border Color
You can set the color of borders:

Hello World
Hello World
Hello World
Example
<h1 style="border:2px solid Tomato;">Hello World</h1>
<h1 style="border:2px solid DodgerBlue;">Hello World</h1>
<h1 style="border:2px solid Violet;">Hello World</h1>

Color Values
In HTML, colors can also be specified using RGB values, HEX values, HSL values, RGBA values, and
HSLA values:

Same as color name "Tomato":

rgb(255, 99, 71)

#ff6347

hsl(9, 100%, 64%)


Same as color name "Tomato", but 50% transparent:

rgba(255, 99, 71, 0.5)

154
hsla(9, 100%, 64%, 0.5)
Example
<h1 style="background-color:rgb(255, 99, 71);">...</h1>
<h1 style="background-color:#ff6347;">...</h1>
<h1 style="background-color:hsl(9, 100%, 64%);">...</h1>

<h1 style="background-color:rgba(255, 99, 71, 0.5);">...</h1>


<h1 style="background-color:hsla(9, 100%, 64%, 0.5);">...</h1>

RGB Value
In HTML, a color can be specified as an RGB value, using this formula:

rgb(red, green, blue)


Each parameter (red, green, and blue) defines the intensity of the color between 0 and 255.

For example, rgb(255, 0, 0) is displayed as red, because red is set to its highest value (255) and the
others are set to 0.

To display the color black, all color parameters must be set to 0, like this: rgb(0, 0, 0).

To display the color white, all color parameters must be set to 255, like this: rgb(255, 255, 255).

Experiment by mixing the RGB values below:

rgb(255, 99, 71)


RED
255
GREEN
99
BLUE
71

155
Example

rgb(255, 0, 0)

rgb(0, 0, 255)

rgb(60, 179, 113)

rgb(238, 130, 238)

rgb(255, 165, 0)

rgb(106, 90, 205)

Shades of gray are often defined using equal values for all the 3 light sources:

Example

rgb(0, 0, 0)

rgb(60, 60, 60)

rgb(120, 120, 120)

rgb(180, 180, 180)

156
rgb(240, 240, 240)

rgb(255, 255, 255)

HEX Value
In HTML, a color can be specified using a hexadecimal value in the form:

#rrggbb
Where rr (red), gg (green) and bb (blue) are hexadecimal values between 00 and ff (same as decimal 0-
255).

For example, #ff0000 is displayed as red, because red is set to its highest value (ff) and the others are set
to the lowest value (00).

Example

#ff0000

#0000ff

#3cb371

#ee82ee

#ffa500

157
#6a5acd

Shades of gray are often defined using equal values for all the 3 light sources:

Example

#000000

#3c3c3c

#787878

#b4b4b4

#f0f0f0

#ffffff

HSL Value
In HTML, a color can be specified using hue, saturation, and lightness (HSL) in the form:

hsl(hue, saturation, lightness)


Hue is a degree on the color wheel from 0 to 360. 0 is red, 120 is green, and 240 is blue.

Saturation is a percentage value, 0% means a shade of gray, and 100% is the full color.

Lightness is also a percentage, 0% is black, 50% is neither light or dark, 100% is white

158
Example

hsl(0, 100%, 50%)

hsl(240, 100%, 50%)

hsl(147, 50%, 47%)

hsl(300, 76%, 72%)

hsl(39, 100%, 50%)

hsl(248, 53%, 58%)

Saturation
Saturation can be described as the intensity of a color.

100% is pure color, no shades of gray

50% is 50% gray, but you can still see the color.

0% is completely gray, you can no longer see the color.

Example

hsl(0, 100%, 50%)

159
hsl(0, 80%, 50%)

hsl(0, 60%, 50%)

hsl(0, 40%, 50%)

hsl(0, 20%, 50%)

hsl(0, 0%, 50%)

Lightness
The lightness of a color can be described as how much light you want to give the color, where 0%
means no light (black), 50% means 50% light (neither dark nor light) 100% means full lightness (white).

Example

hsl(0, 100%, 0%)

hsl(0, 100%, 25%)

hsl(0, 100%, 50%)

hsl(0, 100%, 75%)


160
hsl(0, 100%, 90%)

hsl(0, 100%, 100%)

Shades of gray are often defined by setting the hue and saturation to 0, and adjust the lightness from 0%
to 100% to get darker/lighter shades:

Example

hsl(0, 0%, 0%)

hsl(0, 0%, 24%)

hsl(0, 0%, 47%)

hsl(0, 0%, 71%)

hsl(0, 0%, 94%)

hsl(0, 0%, 100%)

RGBA Value
161
RGBA color values are an extension of RGB color values with an alpha channel - which specifies the
opacity for a color.

An RGBA color value is specified with:

rgba(red, green, blue, alpha)


The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (not transparent at all):

Example

rgba(255, 99, 71, 0)

rgba(255, 99, 71, 0.2)

rgba(255, 99, 71, 0.4)

rgba(255, 99, 71, 0.6)

rgba(255, 99, 71, 0.8)

rgba(255, 99, 71, 1)

HSLA Value
HSLA color values are an extension of HSL color values with an alpha channel - which specifies the
opacity for a color.

An HSLA color value is specified with:

hsla(hue, saturation, lightness, alpha)


The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (not transparent at all):

162
Example

hsla(9, 100%, 64%, 0)

hsla(9, 100%, 64%, 0.2)

hsla(9, 100%, 64%, 0.4)

hsla(9, 100%, 64%, 0.6)

hsla(9, 100%, 64%, 0.8)

hsla(9, 100%, 64%, 1)

HTML Styles - CSS


CSS = Styles and Colors
M a n i p u l a t e T e x t
C o l o r s , B o x e s

Styling HTML with CSS


163
CSS stands for Cascading Style Sheets.

CSS describes how HTML elements are to be displayed on screen, paper, or in other media.

CSS saves a lot of work. It can control the layout of multiple web pages all at once.

CSS can be added to HTML elements in 3 ways:

 Inline - by using the style attribute in HTML elements

 Internal - by using a <style> element in the <head> section

 External - by using an external CSS file

The most common way to add CSS, is to keep the styles in separate CSS files. However, here we will
use inline and internal styling, because this is easier to demonstrate, and easier for you to try it yourself.

Tip: You can learn much more about CSS in our CSS Tutorial.

Inline CSS
An inline CSS is used to apply a unique style to a single HTML element.

An inline CSS uses the style attribute of an HTML element.

This example sets the text color of the <h1> element to blue:

Example
<h1 style="color:blue;">This is a Blue Heading</h1>

Internal CSS
An internal CSS is used to define a style for a single HTML page.

An internal CSS is defined in the <head> section of an HTML page, within a <style> element:

Example
<!DOCTYPE html>
<html>
<head>
<style>
body {background-color: powderblue;}
h1 {color: blue;}
p {color: red;}
</style>
</head>
<body>

164
<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

External CSS
An external style sheet is used to define the style for many HTML pages.

With an external style sheet, you can change the look of an entire web site, by changing one file!

To use an external style sheet, add a link to it in the <head> section of the HTML page:

Example
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

An external style sheet can be written in any text editor. The file must not contain any HTML code, and
must be saved with a .css extension.

Here is how the "styles.css" looks:


body {
background-color: powderblue;
}
h1 {
color: blue;
}
p{
color: red;
}

CSS Fonts
165
The CSS color property defines the text color to be used.

The CSS font-family property defines the font to be used.

The CSS font-size property defines the text size to be used.

Example
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
color: blue;
font-family: verdana;
font-size: 300%;
}
p {
color: red;
font-family: courier;
font-size: 160%;
}
</style>
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

CSS Border
The CSS border property defines a border around an HTML element:

Example
p{
border: 1px solid powderblue;
}

CSS Padding
166
The CSS padding property defines a padding (space) between the text and the border:

Example
p{
border: 1px solid powderblue;
padding: 30px;
}

CSS Margin
The CSS margin property defines a margin (space) outside the border:

Example
p{
border: 1px solid powderblue;
margin: 50px;
}

The id Attribute
To define a specific style for one special element, add an id attribute to the element:
<p id="p01">I am different</p>
then define a style for the element with the specific id:

Example
#p01 {
color: blue;
}

Note: The id of an element should be unique within a page, so the id selector is used to select one
unique element!

The class Attribute


To define a style for special types of elements, add a class attribute to the element:
<p class="error">I am different</p>
then define a style for the elements with the specific class:

167
Example
p.error {
color: red;
}

External References
External style sheets can be referenced with a full URL or with a path relative to the current web page.

This example uses a full URL to link to a style sheet:

Example
<link rel="stylesheet" href="https://www.w3schools.com/html/styles.css">

This example links to a style sheet located in the html folder on the current web site:

Example
<link rel="stylesheet" href="/html/styles.css
This example links to a style sheet located in the same folder as the current page:

Example
<link rel="stylesheet" href="styles.css">

HTML Style Tags


Tag Description

<style> Defines style information for an HTML document

<link> Defines a link between a document and an external resource

168
HTML Images
Images can improve the design and the appearance of a web page.

Example
<img src="pic_trulli.jpg" alt="Italian Trulli">

Example
<img src="img_girl.jpg" alt="Girl in a jacket">

Example
<img src="img_chania.jpg" alt="Flowers in Chania">

HTML Images Syntax


In HTML, images are defined with the <img> tag.

The <img> tag is empty, it contains attributes only, and does not have a closing tag.

The src attribute specifies the URL (web address) of the image:
<img src="url">

The alt Attribute


The alt attribute provides an alternate text for an image, if the user for some reason cannot view it
(because of slow connection, an error in the src attribute, or if the user uses a screen reader).

The value of the alt attribute should describe the image:

Example
<img src="img_chania.jpg" alt="Flowers in Chania">
If a browser cannot find an image, it will display the value of the alt attribute:

Example
<img src="wrongname.gif" alt="Flowers in Chania">
Note: The alt attribute is required. A web page will not validate correctly without it.

Image Size - Width and Height


You can use the style attribute to specify the width and height of an image.

169
Example
<img src="img_girl.jpg" alt="Girl in a jacket" style="width:500px;height:600px;">
Alternatively, you can use the width and height attributes:

Example
<img src="img_girl.jpg" alt="Girl in a jacket" width="500" height="600">
The width and height attributes always defines the width and height of the image in pixels.

Note: Always specify the width and height of an image. If width and height are not specified, the page
might flicker while the image loads.

Width and Height, or Style?


The width, height, and style attributes are valid in HTML5.

However, we suggest using the style attribute. It prevents styles sheets from changing the size of
images:

Example
<!DOCTYPE html>
<html>
<head>
<style>
img {
width:100%;
}
</style>
</head>
<body>

<img src="html5.gif" alt="HTML5 Icon" width="128" height="128">


<img src="html5.gif" alt="HTML5 Icon" style="width:128px;height:128px;">

</body>
</html>

Images in Another Folder


If not specified, the browser expects to find the image in the same folder as the web page.

However, it is common to store images in a sub-folder. You must then include the folder name in
the src attribute:
170
Example
<img src="/images/html5.gif" alt="HTML5 Icon" style="width:128px;height:128px;">

Images on Another Server


Some web sites store their images on image servers.

Actually, you can access images from any web address in the world:

Example
<img src="https://www.w3schools.com/images/w3schools_green.jpg" alt="W3Schools.com">
You can read more about file paths in the chapter HTML File Paths.

Animated Images
HTML allows animated GIFs:

Example
<img src="programming.gif" alt="Computer Man" style="width:48px;height:48px;">

Image as a Link
To use an image as a link, put the <img> tag inside the <a> tag:

Example
<a href="default.asp">
<img src="smiley.gif" alt="HTML tutorial" style="width:42px;height:42px;border:0;">
</a>

Note: border:0; is added to prevent IE9 (and earlier) from displaying a border around the image (when
the image is a link).

Image Floating
Use the CSS float property to let the image float to the right or to the left of a text:

171
Example
<p><img src="smiley.gif" alt="Smiley face" style="float:right;width:42px;height:42px;">
The image will float to the right of the text.</p>

<p><img src="smiley.gif" alt="Smiley face" style="float:left;width:42px;height:42px;">


The image will float to the left of the text.</p>

Tip: To learn more about CSS Float, read our CSS Float Tutorial.

Image Maps
The <map> tag defines an image-map. An image-map is an image with clickable areas.

In the image below, click on the computer, the phone, or the cup of coffee:

Example
<img src="workplace.jpg" alt="Workplace" usemap="#workmap">

<map name="workmap">
<area shape="rect" coords="34,44,270,350" alt="Computer" href="computer.htm">
<area shape="rect" coords="290,172,333,250" alt="Phone" href="phone.htm">
<area shape="circle" coords="337,300,44" alt="Coffee" href="coffee.htm">
</map>

The name attribute of the <map> tag is associated with the <img>'s usemap attribute and creates a
relationship between the image and the map.

The <map> element contains a number of <area> tags, that define the clickable areas in the image-
map.

Background Image
To add a background image on an HTML element, use the CSS property background-image:

Example
To add a background image on a web page, specify the background-image property on the BODY
element:
<body style="background-image:url('clouds.jpg')">

172
<h2>Background Image</h2>

</body>

Example
To add a background image on a paragraph, specify the background-image property on the P element:
<body>

<p style="background-image:url('clouds.jpg')">
...
</p>

</body>

To learn more about background images, study our CSS Background Tutorial.

The <picture> Element


HTML5 introduced the <picture> element to add more flexibility when specifying image resources.

The <picture> element contains a number of <source> elements, each referring to different image
sources. This way the browser can choose the image that best fits the current view and/or device.

Each <source> element have attributes describing when their image is the most suitable.

The browser will use the first <source> element with matching attribute values, and ignore any
following <source>elements.

Example
Show one picture if the browser window (viewport) is a minimum of 650 pixels, and another image if
not, but larger than 465 pixels.
<picture>
<source media="(min-width: 650px)" srcset="img_pink_flowers.jpg">
<source media="(min-width: 465px)" srcset="img_white_flower.jpg">
<img src="img_orange_flowers.jpg" alt="Flowers" style="width:auto;">
</picture>

Note: Always specify an <img> element as the last child element of the <picture> element.
The <img>element is used by browsers that do not support the <picture> element, or if none of
the <source> tags matched.

173
HTML Screen Readers
A screen reader is a software program that reads the HTML code, converts the text, and allows the user
to "listen" to the content. Screen readers are useful for people who are blind, visually impaired, or
learning disabled.

HTML Image Tags

Tag Description

<img> Defines an image

<map> Defines an image-map

<area> Defines a clickable area inside an image-map

<picture> Defines a container for multiple image resources

HTML Table

Company Contact Country

Alfreds Futterkiste Maria Anders Germany

Centro comercial Moctezuma Francisco Chang Mexico

Ernst Handel Roland Mendel Austria

Island Trading Helen Bennett UK

174
Laughing Bacchus Winecellars Yoshi Tannamuri Canada

Magazzini Alimentari Riuniti Giovanni Rovelli Italy

HTML Table Example

Defining an HTML Table


An HTML table is defined with the <table> tag.

Each table row is defined with the <tr> tag. A table header is defined with the <th> tag. By default,
table headings are bold and centered. A table data/cell is defined with the <td> tag.

Example
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
Note: The <td> elements are the data containers of the table.
They can contain all sorts of HTML elements; text, images, lists, other tables, etc.

HTML Table - Adding a Border


If you do not specify a border for the table, it will be displayed without borders.

175
A border is set using the CSS border property:

Example
table, th, td {
border: 1px solid black;
}
Remember to define borders for both the table and the table cells.

HTML Table - Collapsed Borders


If you want the borders to collapse into one border, add the CSS border-collapse property:

Example
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}

HTML Table - Adding Cell Padding


Cell padding specifies the space between the cell content and its borders.

If you do not specify a padding, the table cells will be displayed without padding.

To set the padding, use the CSS padding property:

Example
th, td {
padding: 15px;
}

HTML Table - Left-align Headings


By default, table headings are bold and centered.

To left-align the table headings, use the CSS text-align property:

176
Example
th {
text-align: left;
}

HTML Table - Adding Border Spacing


Border spacing specifies the space between the cells.

To set the border spacing for a table, use the CSS border-spacing property:

Example
table {
border-spacing: 5px;
}

Note: If the table has collapsed borders, border-spacing has no effect.

HTML Table - Cells that Span Many Columns


To make a cell span more than one column, use the colspan attribute:

Example
<table style="width:100%">
<tr>
<th>Name</th>
<th colspan="2">Telephone</th>
</tr>
<tr>
<td>Bill Gates</td>
<td>55577854</td>
<td>55577855</td>
</tr>
</table>

HTML Table - Cells that Span Many Rows


To make a cell span more than one row, use the rowspan attribute:

Example
<table style="width:100%">
177
<tr>
<th>Name:</th>
<td>Bill Gates</td>
</tr>
<tr>
<th rowspan="2">Telephone:</th>
<td>55577854</td>
</tr>
<tr>
<td>55577855</td>
</tr>
</table>

HTML Table - Adding a Caption


To add a caption to a table, use the <caption> tag:

Example
<table style="width:100%">
<caption>Monthly savings</caption>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$50</td>
</tr>
</table>

Note: The <caption> tag must be inserted immediately after the <table> tag.

A Special Style for One Table


To define a special style for a special table, add an id attribute to the table:

Example
<table id="t01">
<tr>
178
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>

Now you can define a special style for this table:


table#t01 {
width: 100%;
background-color: #f1f1c1;
}

And add more styles:


table#t01 tr:nth-child(even) {
background-color: #eee;
}
table#t01 tr:nth-child(odd) {
background-color: #fff;
}
table#t01 th {
color: white;
background-color: black;
}

HTML Table Tags


Tag Description

<table> Defines a table

<th> Defines a header cell in a table

179
<tr> Defines a row in a table

<td> Defines a cell in a table

<caption> Defines a table caption

<colgroup> Specifies a group of one or more columns in a table for formatting

<col> Specifies column properties for each column within a <colgroup> element

<thead> Groups the header content in a table

<tbody> Groups the body content in a table

<tfoot> Groups the footer content in a table

Iframe Syntax
An HTML iframe is defined with the <iframe> tag:
<iframe src="URL"></iframe>
The src attribute specifies the URL (web address) of the inline frame page.

Iframe - Set Height and Width


Use the height and width attributes to specify the size of the iframe.

The attribute values are specified in pixels by default, but they can also be in percent (like "80%").

180
Example
<iframe src="demo_iframe.htm" height="200" width="300"></iframe>

Or you can use CSS to set the height and width of the iframe:

Example
<iframe src="demo_iframe.htm" style="height:200px;width:300px;"></iframe>

Iframe - Remove the Border


By default, an iframe has a border around it.

To remove the border, add the style attribute and use the CSS border property:

Example
<iframe src="demo_iframe.htm" style="border:none;"></iframe>

With CSS, you can also change the size, style and color of the iframe's border:

Example
<iframe src="demo_iframe.htm" style="border:2px solid red;"></iframe>

Iframe - Target for a Link


An iframe can be used as the target frame for a link.

The target attribute of the link must refer to the name attribute of the iframe:

Example
<iframe src="demo_iframe.htm" name="iframe_a"></iframe>

<p><a href="https://www.w3schools.com" target="iframe_a">W3Schools.com</a></p>

HTML iframe Tag


Tag Description

181
<iframe> Defines an inline frame

XML

182
XML Tutorial
❮ HomeNext ❯

XML stands for eXtensible Markup Language.

XML was designed to store and transport data.

XML was designed to be both human- and machine-readable.

XML Example 1
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Display the XML File » Display the XML File as a Note »

XML Example 2
<?xml version="1.0" encoding="UTF-8"?>
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
183
<price>$5.95</price>
<description>
Two of our famous Belgian Waffles with plenty of real maple syrup
</description>
<calories>650</calories>
</food>
<food>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>
Light Belgian waffles covered with strawberries and whipped cream
</description>
<calories>900</calories>
</food>
<food>
<name>Berry-Berry Belgian Waffles</name>
<price>$8.95</price>
<description>
Belgian waffles covered with assorted fresh berries and whipped cream
</description>
<calories>900</calories>
</food>
<food>
<name>French Toast</name>
<price>$4.50</price>
<description>
Thick slices made from our homemade sourdough bread
</description>
<calories>600</calories>
</food>
<food>
<name>Homestyle Breakfast</name>
<price>$6.95</price>
<description>
Two eggs, bacon or sausage, toast, and our ever-popular hash browns
</description>
<calories>950</calories>
</food>
</breakfast_menu>

Why Study XML?


XML plays an important role in many different IT systems.

XML is often used for distributing data over the Internet.

It is important (for all types of software developers!) to have a good


understanding of XML.

What You Will Learn


184
This tutorial will give you a solid understanding of XML:

 What is XML?

 How does XML work?

 How can I use XML?

 What can I use XML for?

Introduction to XML
XML is a software- and hardware-independent tool for storing and transporting
data.

What is XML?
 XML stands for eXtensible Markup Language

 XML is a markup language much like HTML

 XML was designed to store and transport data

 XML was designed to be self-descriptive

 XML is a W3C Recommendation

XML Does Not DO Anything


Maybe it is a little hard to understand, but XML does not DO anything.

This note is a note to Tove from Jani, stored as XML:


<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
The XML above is quite self-descriptive:

 It has sender information.

185
 It has receiver information

 It has a heading

 It has a message body.

But still, the XML above does not DO anything. XML is just information wrapped in
tags.

Someone must write a piece of software to send, receive, store, or display it:

Note
To: Tove

From: Jani

Reminder
Don't forget me this weekend!

The Difference Between XML and HTML


XML and HTML were designed with different goals:

 XML was designed to carry data - with focus on what data is

 HTML was designed to display data - with focus on how data looks

 XML tags are not predefined like HTML tags are

XML Does Not Use Predefined Tags


The XML language has no predefined tags.

The tags in the example above (like <to> and <from>) are not defined in any
XML standard. These tags are "invented" by the author of the XML document.

HTML works with predefined tags like <p>, <h1>, <table>, etc.

With XML, the author must define both the tags and the document structure.

186
XML is Extensible
Most XML applications will work as expected even if new data is added (or
removed).

Imagine an application designed to display the original version of note.xml (<to>


<from> <heading> <body>).

Then imagine a newer version of note.xml with added <date> and <hour>
elements, and a removed <heading>.

The way XML is constructed, older version of the application can still work:
<note>
<date>2015-09-01</date>
<hour>08:30</hour>
<to>Tove</to>
<from>Jani</from>
<body>Don't forget me this weekend!</body>
</note>

Old Version

Note
To: Tove

From: Jani

Reminder
Don't forget me this weekend!

New Version

Note
To: Tove

From: Jani

Date: 2015-09-01 08:30

Don't forget me this weekend!

187
XML Simplifies Things
 It simplifies data sharing

 It simplifies data transport

 It simplifies platform changes

 It simplifies data availability

Many computer systems contain data in incompatible formats. Exchanging data


between incompatible systems (or upgraded systems) is a time-consuming task
for web developers. Large amounts of data must be converted, and incompatible
data is often lost.

XML stores data in plain text format. This provides a software- and hardware-
independent way of storing, transporting, and sharing data.

XML also makes it easier to expand or upgrade to new operating systems, new
applications, or new browsers, without losing data.

With XML, data can be available to all kinds of "reading machines" like people,
computers, voice machines, news feeds, etc.

How Can XML be Used?


XML is used in many aspects of web development.

XML is often used to separate data from presentation.

XML Separates Data from Presentation


XML does not carry any information about how to be displayed.

The same XML data can be used in many different presentation scenarios.

Because of this, with XML, there is a full separation between data and
presentation.

XML is Often a Complement to HTML


In many HTML applications, XML is used to store or transport data, while HTML is
used to format and display the same data.

XML Separates Data from HTML


When displaying data in HTML, you should not have to edit the HTML file when the
data changes.

188
With XML, the data can be stored in separate XML files.

With a few lines of JavaScript code, you can read an XML file and update the data
content of any HTML page.
Display Books.xml »

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

<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>

<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>

<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>

<book category="web" cover="paperback">


<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>

</bookstore>
You will learn a lot more about using XML and JavaScript in the DOM section of
this tutorial.

Transaction Data
189
Thousands of XML formats exists, in many different industries, to describe day-to-
day data transactions:

 Stocks and Shares

 Financial transactions

 Medical data

 Mathematical data

 Scientific measurements

 News information

 Weather services

Example: XML News


XMLNews is a specification for exchanging news and other information.

Using a standard makes it easier for both news producers and news consumers to
produce, receive, and archive any kind of news information across different
hardware, software, and programming languages.

An example XMLNews document:


<?xml version="1.0" encoding="UTF-8"?>
<nitf>
<head>
<title>Colombia Earthquake</title>
</head>
<body>
<headline>
<hl1>143 Dead in Colombia Earthquake</hl1>
</headline>
<byline>
<bytag>By Jared Kotler, Associated Press Writer</bytag>
</byline>
<dateline>
<location>Bogota, Colombia</location>
<date>Monday January 25 1999 7:28 ET</date>
</dateline>
</body>
</nitf>

Example: XML Weather Service


190
An XML national weather service from NOAA (National Oceanic and Atmospheric
Administration):
<?xml version="1.0" encoding="UTF-8"?>
<current_observation>

<credit>NOAA's National Weather Service</credit>


<credit_URL>http://weather.gov/</credit_URL>

<image>
<url>http://weather.gov/images/xml_logo.gif</url>
<title>NOAA's National Weather Service</title>
<link>http://weather.gov</link>
</image>

<location>New York/John F. Kennedy Intl Airport, NY</location>


<station_id>KJFK</station_id>
<latitude>40.66</latitude>
<longitude>-73.78</longitude>
<observation_time_rfc822>Mon, 11 Feb 2008 06:51:00 -0500 EST
</observation_time_rfc822>

<weather>A Few Clouds</weather>


<temp_f>11</temp_f>
<temp_c>-12</temp_c>
<relative_humidity>36</relative_humidity>
<wind_dir>West</wind_dir>
<wind_degrees>280</wind_degrees>
<wind_mph>18.4</wind_mph>
<wind_gust_mph>29</wind_gust_mph>
<pressure_mb>1023.6</pressure_mb>
<pressure_in>30.23</pressure_in>
<dewpoint_f>-11</dewpoint_f>
<dewpoint_c>-24</dewpoint_c>
<windchill_f>-7</windchill_f>
<windchill_c>-22</windchill_c>
<visibility_mi>10.00</visibility_mi>

<icon_url_base>http://weather.gov/weather/images/fcicons/</icon_url_base>
<icon_url_name>nfew.jpg</icon_url_name>
<disclaimer_url>http://weather.gov/disclaimer.html</disclaimer_url>
<copyright_url>http://weather.gov/disclaimer.html</copyright_url>

</current_observation>

How Can XML be Used?


XML is used in many aspects of web development.

XML is often used to separate data from presentation

191
XML Separates Data from Presentation
XML does not carry any information about how to be displayed.

The same XML data can be used in many different presentation scenarios.

Because of this, with XML, there is a full separation between data and
presentation.

XML is Often a Complement to HTML


In many HTML applications, XML is used to store or transport data, while HTML is
used to format and display the same data.

XML Separates Data from HTML


When displaying data in HTML, you should not have to edit the HTML file when the
data changes.

With XML, the data can be stored in separate XML files.

With a few lines of JavaScript code, you can read an XML file and update the data
content of any HTML page.
Display Books.xml »

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

<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>

<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>

<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
192
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>

<book category="web" cover="paperback">


<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>

</bookstore>
You will learn a lot more about using XML and JavaScript in the DOM section of
this tutorial.

Transaction Data
Thousands of XML formats exists, in many different industries, to describe day-to-
day data transactions:

 Stocks and Shares

 Financial transactions

 Medical data

 Mathematical data

 Scientific measurements

 News information

 Weather services

Example: XML News


XMLNews is a specification for exchanging news and other information.

Using a standard makes it easier for both news producers and news consumers to
produce, receive, and archive any kind of news information across different
hardware, software, and programming languages.

An example XMLNews document:


<?xml version="1.0" encoding="UTF-8"?>
<nitf>
<head>
<title>Colombia Earthquake</title>
</head>
<body>
193
<headline>
<hl1>143 Dead in Colombia Earthquake</hl1>
</headline>
<byline>
<bytag>By Jared Kotler, Associated Press Writer</bytag>
</byline>
<dateline>
<location>Bogota, Colombia</location>
<date>Monday January 25 1999 7:28 ET</date>
</dateline>
</body>
</nitf>

Example: XML Weather Service


An XML national weather service from NOAA (National Oceanic and Atmospheric
Administration):
<?xml version="1.0" encoding="UTF-8"?>
<current_observation>

<credit>NOAA's National Weather Service</credit>


<credit_URL>http://weather.gov/</credit_URL>

<image>
<url>http://weather.gov/images/xml_logo.gif</url>
<title>NOAA's National Weather Service</title>
<link>http://weather.gov</link>
</image>

<location>New York/John F. Kennedy Intl Airport, NY</location>


<station_id>KJFK</station_id>
<latitude>40.66</latitude>
<longitude>-73.78</longitude>
<observation_time_rfc822>Mon, 11 Feb 2008 06:51:00 -0500 EST
</observation_time_rfc822>

<weather>A Few Clouds</weather>


<temp_f>11</temp_f>
<temp_c>-12</temp_c>
<relative_humidity>36</relative_humidity>
<wind_dir>West</wind_dir>
<wind_degrees>280</wind_degrees>
<wind_mph>18.4</wind_mph>
<wind_gust_mph>29</wind_gust_mph>
<pressure_mb>1023.6</pressure_mb>
<pressure_in>30.23</pressure_in>
<dewpoint_f>-11</dewpoint_f>
<dewpoint_c>-24</dewpoint_c>
<windchill_f>-7</windchill_f>
<windchill_c>-22</windchill_c>
194
<visibility_mi>10.00</visibility_mi>

<icon_url_base>http://weather.gov/weather/images/fcicons/</icon_url_base>
<icon_url_name>nfew.jpg</icon_url_name>
<disclaimer_url>http://weather.gov/disclaimer.html</disclaimer_url>
<copyright_url>http://weather.gov/disclaimer.html</copyright_url>

</current_observation>

XML Syntax Rules


The syntax rules of XML are very simple and logical.
The rules are easy to learn, and easy to use

XML Documents Must Have a Root Element


XML documents must contain one root element that is the parent of all other
elements:
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
In this example <note> is the root element:
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

The XML Prolog


This line is called the XML prolog:
<?xml version="1.0" encoding="UTF-8"?>
The XML prolog is optional. If it exists, it must come first in the document.

XML documents can contain international characters, like Norwegian øæå or


French êèé.

To avoid errors, you should specify the encoding used, or save your XML files as
UTF-8.

UTF-8 is the default character encoding for XML documents.

Character encoding can be studied in our Character Set Tutorial.


195
UTF-8 is also the default encoding for HTML5, CSS, JavaScript, PHP, and SQL.

All XML Elements Must Have a Closing Tag


In XML, it is illegal to omit the closing tag. All elements must have a closing tag:
<p>This is a paragraph.</p>
<br />
Note: The XML prolog does not have a closing tag! This is not an error. The prolog
is not a part of the XML document.

XML Tags are Case Sensitive


XML tags are case sensitive. The tag <Letter> is different from the tag <letter>.

Opening and closing tags must be written with the same case:
<message>This is correct</message>
"Opening and closing tags" are often referred to as "Start and end tags". Use
whatever you prefer. It is exactly the same thing.

XML Elements Must be Properly Nested


In HTML, you might see improperly nested elements:
<b><i>This text is bold and italic</b></i>
In XML, all elements must be properly nested within each other:
<b><i>This text is bold and italic</i></b>
In the example above, "Properly nested" simply means that since the <i> element
is opened inside the <b> element, it must be closed inside the <b> element.

XML Attribute Values Must Always be Quoted


XML elements can have attributes in name/value pairs just like in HTML.

In XML, the attribute values must always be quoted:


<note date="12/11/2007">
<to>Tove</to>
<from>Jani</from>
196
</note>

Entity References
Some characters have a special meaning in XML.

If you place a character like "<" inside an XML element, it will generate an error
because the parser interprets it as the start of a new element.

This will generate an XML error:


<message>salary < 1000</message>
To avoid this error, replace the "<" character with an entity reference:
<message>salary &lt; 1000</message>
There are 5 pre-defined entity references in XML:

&lt; < less than

&gt; > greater than

&amp; & ampersand

&apos; ' apostrophe

&quot; " quotation mark

Only < and & are strictly illegal in XML, but it is a good habit to replace > with
&gt; as well.

Comments in XML
197
The syntax for writing comments in XML is similar to that of HTML:
<!-- This is a comment -->
Two dashes in the middle of a comment are not allowed:
<!-- This is an invalid -- comment -->

White-space is Preserved in XML


XML does not truncate multiple white-spaces (HTML truncates multiple white-
spaces to one single white-space):

XML: Hello Tove

HTML: Hello Tove

XML Stores New Line as LF


Windows applications store a new line as: carriage return and line feed (CR+LF).

Unix and Mac OSX uses LF.

Old Mac systems uses CR.

XML stores a new line as LF.

Well Formed XML


XML documents that conform to the syntax rules above are said to be "Well
Formed" XML documents.

What is an XML Element?


An XML element is everything from (including) the element's start tag to
(including) the element's end tag.
<price>29.99</price>
198
An element can contain:

 text

 attributes

 other elements

 or a mix of the above


<bookstore>
<book category="children">
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
In the example above:

<title>, <author>, <year>, and <price> have text content because they contain
text (like 29.99).

<bookstore> and <book> have element contents, because they contain


elements.

<book> has an attribute (category="children").

Empty XML Elements


An element with no content is said to be empty.

In XML, you can indicate an empty element like this:


<element></element>
You can also use a so called self-closing tag:
<element />
The two forms produce identical results in XML software (Readers, Parsers,
Browsers).

Empty elements can have attributes.

199
XML Naming Rules
XML elements must follow these naming rules:

 Element names are case-sensitive

 Element names must start with a letter or underscore

 Element names cannot start with the letters xml (or XML, or Xml, etc)

 Element names can contain letters, digits, hyphens, underscores, and


periods

 Element names cannot contain spaces

Any name can be used, no words are reserved (except xml).

Best Naming Practices


Create descriptive names, like this: <person>, <firstname>, <lastname>.

Create short and simple names, like this: <book_title> not like this:
<the_title_of_the_book>.

Avoid "-". If you name something "first-name", some software may think you want
to subtract "name" from "first".

Avoid ".". If you name something "first.name", some software may think that
"name" is a property of the object "first".

Avoid ":". Colons are reserved for namespaces (more later).

Non-English letters like éòá are perfectly legal in XML, but watch out for problems
if your software doesn't support them.

Naming Styles
There are no naming styles defined for XML elements. But here are some
commonly used:

200
Style Example Description

Lower case <firstname> All letters lower case

Upper case <FIRSTNAME> All letters upper case

Underscore <first_name> Underscore separates words

Pascal case <FirstName> Uppercase first letter in each word

Camel case <firstName> Uppercase first letter in each word except th

If you choose a naming style, it is good to be consistent!

XML documents often have a corresponding database. A common practice is to


use the naming rules of the database for the XML elements.

Camel case is a common naming rule in JavaScripts.

XML Elements are Extensible


XML elements can be extended to carry more information.

Look at the following XML example:


<note>
<to>Tove</to>
<from>Jani</from>
<body>Don't forget me this weekend!</body>
</note>
Let's imagine that we created an application that extracted the <to>, <from>,
and <body> elements from the XML document to produce this output:

MESSAGE
To: Tove

201
From: Jani

Don't forget me this weekend!

Imagine that the author of the XML document added some extra information to it:
<note>
<date>2008-01-10</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Should the application break or crash?

No. The application should still be able to find the <to>, <from>, and <body>
elements in the XML document and produce the same output.

This is one of the beauties of XML. It can be extended without breaking


applications.

XML Attributes
XML elements can have attributes, just like HTML.

Attributes are designed to contain data related to a specific element.

XML Attributes Must be Quoted


Attribute values must always be quoted. Either single or double quotes can be
used.

For a person's gender, the <person> element can be written like this:
<person gender="female">
or like this:
<person gender='female'>
If the attribute value itself contains double quotes you can use single quotes, like
in this example:
<gangster name='George "Shotgun" Ziegler'>
or you can use character entities:
<gangster name="George &quot;Shotgun&quot; Ziegler">

202
XML Elements vs. Attributes
Take a look at these examples:
<person gender="female">
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>

<person>
<gender>female</gender>
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>
In the first example gender is an attribute. In the last, gender is an element. Both
examples provide the same information.

There are no rules about when to use attributes or when to use elements in XML

My Favorite Way
The following three XML documents contain exactly the same information:

A date attribute is used in the first example:


<note date="2008-01-10">
<to>Tove</to>
<from>Jani</from>
</note>
A <date> element is used in the second example:
<note>
<date>2008-01-10</date>
<to>Tove</to>
<from>Jani</from>
</note>
An expanded <date> element is used in the third example: (THIS IS MY
FAVORITE):
<note>
<date>
<year>2008</year>
<month>01</month>
<day>10</day>
</date>
<to>Tove</to>
<from>Jani</from>
</note>

Avoid XML Attributes?


203
Some things to consider when using attributes are:

 attributes cannot contain multiple values (elements can)

 attributes cannot contain tree structures (elements can)

 attributes are not easily expandable (for future changes)

Don't end up like this:


<note day="10" month="01" year="2008"
to="Tove" from="Jani" heading="Reminder"
body="Don't forget me this weekend!">
</note>

XML Attributes for Metadata


Sometimes ID references are assigned to elements. These IDs can be used to
identify XML elements in much the same way as the id attribute in HTML. This
example demonstrates this:
<messages>
<note id="501">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note id="502">
<to>Jani</to>
<from>Tove</from>
<heading>Re: Reminder</heading>
<body>I will not</body>
</note>
</messages>
The id attributes above are for identifying the different notes. It is not a part of
the note itself.

What I'm trying to say here is that metadata (data about data) should be stored
as attributes, and the data itself should be stored as elements.

Displaying XML
Raw XML files can be viewed in all major browsers.

Don't expect XML files to be displayed as HTML pages.

204
Viewing XML Files
<?xml version="1.0" encoding="UTF-8"?>
- <note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Look at the XML file above in your browser: note.xml

Most browsers will display an XML document with color-coded elements.

Often a plus (+) or minus sign (-) to the left of the elements can be clicked to
expand or collapse the element structure.

To view raw XML source, try to select "View Page Source" or "View Source" from
the browser menu.

Note: In Safari 5 (and earlier), only the element text will be displayed. To view
the raw XML, you must right click the page and select "View Source".

Viewing an Invalid XML File


If an erroneous XML file is opened, some browsers will report the error, and some
will display it, or display it incorrectly.
<?xml version="1.0" encoding="UTF-8"?>
- <note>
<to>Tove</to>
<from>Jani</Ffrom>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Try to open the following XML file: note_error.xml

Other XML Examples


Viewing some XML documents will help you get the XML feeling:

An XML breakfast menu


This is a breakfast food menu from a restaurant, stored as XML.

205
An XML CD catalog
This is a CD collection, stored as XML.

An XML plant catalog


This is a plant catalog from a plant shop, stored as XML.

Why Does XML Display Like This?


XML documents do not carry information about how to display the data.

Since XML tags are "invented" by the author of the XML document, browsers do
not know if a tag like <table> describes an HTML table or a dining table.

Without any information about how to display the data, the browsers can just
display the XML document as it is

Displaying XML Files with CSS?


Below is an example of how to use CSS to format an XML document.

We can use an XML file like cd_catalog.xml and a style sheet like cd_catalog.css

RESULT: The CD catalog formatted with the CSS file

Below is a fraction of the XML file. The second line links the XML file to the CSS
file:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="cd_catalog.css"?>
<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
.
.
.
</CATALOG>

206
207

Potrebbero piacerti anche