cmpe 587 advanced network programming perl programming by buğra başaran caner kurtul

71
CMPE 587 CMPE 587 Advanced Network Advanced Network Programming Programming PERL PROGRAMMING PERL PROGRAMMING by by Buğra Başaran Buğra Başaran Caner Kurtul Caner Kurtul

Upload: georgina-cobb

Post on 26-Dec-2015

245 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

CMPE 587CMPE 587Advanced Network Advanced Network

ProgrammingProgramming

PERL PROGRAMMINGPERL PROGRAMMING

byby

Buğra BaşaranBuğra Başaran

Caner KurtulCaner Kurtul

Page 2: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

22

What is Perl? What is Perl? Perl is an acronym for "Practical Extraction and Report Perl is an acronym for "Practical Extraction and Report

LanguageLanguage””

Initially designed as a glue language for Unix, now Perl is Initially designed as a glue language for Unix, now Perl is available for most other operating systems.available for most other operating systems.

Because it runs nearly everywhere, Perl is one of the most Because it runs nearly everywhere, Perl is one of the most portable programming environments available today.portable programming environments available today.

Perl is a free software.Perl is a free software.

Perl has taken good ideas from nearly everywhere and Perl has taken good ideas from nearly everywhere and installed them into an easy-to-use mental framework.installed them into an easy-to-use mental framework.

Page 3: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

33

Compilation vs. Compilation vs. Interpretation In In PerlPerl

Compilation vs. Compilation vs. Interpretation In In PerlPerl

Perl is an interpreted language, you can just execute it like Perl is an interpreted language, you can just execute it like a batch file or shell scripts. a batch file or shell scripts.

Program Compiler

Syntax &

sematic errors Intermediate Format

outputInterpreter

Page 4: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

44

Basic SyntaxBasic Syntax

Perl is free form - whitespace doesn't matter.Perl is free form - whitespace doesn't matter. All perl statements end in a All perl statements end in a ;; (semicolon), like C. (semicolon), like C. Case sensitiveCase sensitive Comments Comments

begin with begin with ## (pound sign) (pound sign) everything after the #, and up to the end of the line is ignored. everything after the #, and up to the end of the line is ignored. the # needn't be at the beginning of the line. the # needn't be at the beginning of the line. There is no way to comment out blocks of codThere is no way to comment out blocks of codee

Page 5: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

55

A Basic Perl ProgramA Basic Perl Program

How to run:perl hello.pl (file is given as parameter to perl interpreter)

hello.pl (first, file should be changed to(first, file should be changed to executable modeexecutable mode) )

perl -w perl -w hello.plhello.pl (shows the warnings)(shows the warnings)

perl -d perl -d hello.plhello.pl ((run the program with a debuggerrun the program with a debugger))

Without a file :perl -e ‘ print "perl -e ‘ print "Hello world.Hello world." ‘" ‘

How to take help:perldoc –f undefperldoc –f undef (to take help about undef function)(to take help about undef function)

perldoc -f localtimeperldoc -f localtime (to take help about localtime function)(to take help about localtime function)

#!/usr/local/bin/perl # Program to do the obvious print 'Hello world.';

hello.pl

Page 6: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

66

Scalar VariablesScalar Variables

$answer = 42; # an integer

$pi = 3.14159265; # a real number

$avocados = 6.02e23; # scientific notation

$pet = ”Camel”; # a string

$sign = ”I love my $pet”; # string with interpolation

$cost = ‘It costs $100’; # string without interpolation

$thence = $sign; # another variable’s value

$num = $answer * $pi; # result of an expression

$exit = system(”vi $file1”); # numeric status of a command

$cwd = `pwd`; # string output from a command

No need to define types explicitly. A variable can be assigned different types of values No need to define types explicitly. A variable can be assigned different types of values during the execution of the program.during the execution of the program.

Page 7: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

77

Operations & Assignments on Scalar Variables

Operations & Assignments on Scalar Variables

Perl uses all the usual C arithmetic operators:Perl uses all the usual C arithmetic operators:

$a = 1 + 2; # Add 1 and 2 and store in $a

$a = 3 - 4; # Subtract 4 from 3 and store in $a

$a = 5 * 6; # Multiply 5 and 6

$a = 7 / 8; # Divide 7 by 8 to give 0.875

$a = 9 ** 10; # Nine to the power of 10

$a = 5 % 2; # Remainder of 5 divided by 2

++$a; # Increment $a and then return it

$a++; # Return $a and then increment it

--$a; # Decrement $a and then return it

$a--; # Return $a and then decrement it

$a = $b = $c = 0;

Page 8: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

88

Operations & Assignments on Scalar Variables (continued)

Operations & Assignments on Scalar Variables (continued)

For strings Perl has the following among others: $a = $b . $c; # Concatenate $b and $c

$a = $b x $c; # $b repeated $c times

To assign values Perl includesTo assign values Perl includes::$a = $b; # Assign $b to $a

$a += $b; # Add $b to $a

$a -= $b; # Subtract $b from $a $a .= $b; # Append $b onto $a

when Perl assigns a value with when Perl assigns a value with $a = $b$a = $b it makes a copy of $b and then it makes a copy of $b and then assigns that to $a. Therefore the next time you change $b it will not assigns that to $a. Therefore the next time you change $b it will not alter $a. alter $a.

Page 9: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

99

Interpolation DetailsInterpolation Details

The following code prints apples and pears using concatenation:

$a = $a = ’’applesapples’’; ;

$b = $b = ’’pearspears’’;;

print $a.’ and ’.$b;print $a.’ and ’.$b;

print '$a and $b'; print '$a and $b'; # prints # prints $a and $b$a and $b

print print "$a and $b";"$a and $b"; # prints# prints apples and pearsapples and pears

Page 10: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

1010

Logical OperatorsLogical Operators

$a if $a is false, $b otherwise$a if $a is false, $b otherwiseAndAnd$a and $b

$a if $a is true, $b otherwise$a if $a is true, $b otherwiseOrOr$a or $b

True if $a or $b is true, but not bothTrue if $a or $b is true, but not bothXorXor$a xor $b

True if $a is not trueTrue if $a is not trueNotNotnot $a

True if $a is not trueTrue if $a is not trueNotNot!$a

$a if $a is true, $b otherwise$a if $a is true, $b otherwiseOrOr$a || $b

$a if $a is false, $b otherwise$a if $a is false, $b otherwiseAndAnd$a && $b

ResultNameExample

Page 11: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

1111

Some File Test OperatorsSome File Test Operators

True if file named in $a is a directoryTrue if file named in $a is a directoryDirectoryDirectory-d $a

True if file named in $a is a regular fileTrue if file named in $a is a regular fileFileFile-f $a

True if file named in $a is a text fileTrue if file named in $a is a text fileText FileText File-T $a

True if file named in $a writableTrue if file named in $a writableWritableWritable-w $a

True if file named in $a readableTrue if file named in $a readableReadableReadable-r $a

True if file named in $a existsTrue if file named in $a existsExistsExists-e $a

ResultNameExample

Page 12: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

1212

Some Numeric and String Comparison Operators

Some Numeric and String Comparison Operators

0 if equal, 1 if $a greater, -1 if $b greater0 if equal, 1 if $a greater, -1 if $b greatercmpcmp<=>ComparisonComparison

True if $a is not less then $bTrue if $a is not less then $bgege>=Greater than or Greater than or equalequal

True if $a is not greater then $bTrue if $a is not greater then $blele<=Less than or EqualLess than or Equal

True if $a is greater then $bTrue if $a is greater then $bgtgt>Greater ThanGreater Than

True if $a is less then $bTrue if $a is less then $bltlt<Less ThanLess Than

True if $a is not equal to $bTrue if $a is not equal to $bnene!=Not EqualNot Equal

True if $a is equal to $bTrue if $a is equal to $beqeq==EqualEqual

Return ValueReturn ValueStringStringNumericNumericComparisonComparison

Page 13: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

1313

Array VariablesArray Variables Array variable is a list of scalars (i.e. numbers and strings). Array variables have the same format as

scalar variables except that they are prefixed by an @ symbol No need to define size for an array. It grows automatically when new elements are added.

@food = ("apples", "pears", "eels");

@music = ("whistle", "flute");

@chars = ’a’..’z’;

@ints = 1..20;

@chars2=@chars; #chars2 gets all elements of chars

The array is accessed by using indices starting from 0, and square brackets are used to specify the index

$food[2] #returns eels

$food[-1] #returns eels

$food[10] = “banana” # food[3]..food[9] can be uninitialized.

@moremusic = ("organ", @music, "harp");

@moremusic = ("organ", "whistle", "flute", "harp");

A neater way of adding elements is to use the statement

push(@food, "eggs"); #pushes eggs to end of the array @food

Page 14: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

1414

Array Variables (continued I)

Array Variables (continued I)

To push two or more items onto the array:push(@food, "eggs", "lard");

push(@food, ("eggs", "lard"));

push(@food, @morefood);

The push function returns the length of the new list. To remove the last item from a list and return it use the pop function.

$grub = pop(@food); # Now $grub has last element of @food

To remove the first item from a list and return it use the shift function.$grub = shift @food;

It is also possible to assign an array to a scalar variable$f = @food; #assigns the length of @food

$f = "@food"; #turns the list into a string with a space

#between each element

This space can be replaced by any other string by changing the value of the special $" variable. This variable is just one of Perl's many special variables.

Page 15: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

1515

Array Variables (continued Array Variables (continued II)II)

Array Variables (continued Array Variables (continued II)II)

Arrays can also be used to make multiple assignments to scalar variables:($a, $b) = ($c, $d); # Same as $a=$c; $b=$d;

($a, $b) = @food; # $a and $b are the first two

# items of @food.

($a, @somefood) = @food; # $a is the first item of @food

# @somefood is a list of the

# others.

(@somefood, $a) = @food; # @somefood is @food and

# $a is undefined.

To find the index of the last element of a list$#food #so lenght is $#food+1

To display arraysprint @food; # applespearseels

print "@food"; # apples pears eels

print @food.""; # 3

Page 16: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

1616

Summary of Array Functions

Summary of Array Functions

return a string formed by concatenating each element of LIST joined return a string formed by concatenating each element of LIST joined by EXPRby EXPR

join(EXPR,LIST)

return a listreturn a list/array/array formed from each substring of EXPR bordered by formed from each substring of EXPR bordered by PATTERNPATTERN

split(PATTERN,EXPR)

return a new list, the sorted from LIST return a new list, the sorted from LIST sort(LIST)

return a new list, the reverse of LISTreturn a new list, the reverse of LISTreverse(LIST)

return the number of elements in the arrayreturn the number of elements in the arrayscalar(@ARRAY)

remove and return the first element of @ARRAY remove and return the first element of @ARRAY shift(@ARRAY)

add LIST to the front of @ARRAY add LIST to the front of @ARRAY unshift(@ARRAY,LIST)

remove and return the last element of @ARRAYremove and return the last element of @ARRAYpop(@ARRAY)

add LIST to the end of @ARRAY add LIST to the end of @ARRAY push(@ARRAY,LIST)

Page 17: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

1717

Hashes (Associative Arrays)

Hashes (Associative Arrays)

Arrays eArrays elements of lements of whichwhich consist of consist of "key" and "value" pairs "key" and "value" pairs Hash declarations:Hash declarations:

%map = (’red’,0xff0000, ’green’,0x00ff00, ’blue’,0x0000ff);

oror%map = (’red’=>0xff0000, ’green’=>0x00ff00, %map = (’red’=>0xff0000, ’green’=>0x00ff00,

’blue’=>0x0000ff); ’blue’=>0x0000ff);

oror%map = ();

$map{red} = 0xff0000;

$map{green} = 0x00ff00;

$map{blue} = 0x0000ff;

@arr = %map; # arr has 6 elements

Page 18: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

1818

Some Hash FunctionsSome Hash Functions

Each time this is called on an %Each time this is called on an %HASHHASH, it will return a 2 , it will return a 2 element list consisting of the next key/value pair in the array.element list consisting of the next key/value pair in the array.

each(%HASH)

remove the pair associated with KEY from remove the pair associated with KEY from HASHHASH. . delete($HASH{KEY})

Return a list of all the keys in %Return a list of all the keys in %HASHHASH. The list is . The list is "unordered" it depends on the hash function used internally. "unordered" it depends on the hash function used internally.

keys(%HASH)

Return a list of all the values in %Return a list of all the values in %HASHHASH values(%HASH)

Page 19: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

1919

Control StructuresControl Structures if else

if (EXPRESSION) { STATEMENTS; }

elsif (EXPRESSION) { STATEMENTS; } else { STATEMENTS; }

NoteNote: curly braces are not optional in contrast to C.: curly braces are not optional in contrast to C.

unless unless (EXPRESSION) { STATEMENTS; }

while/do/until Loops

while/until ( EXPRESSION ) { STATEMENTS; }

do { STATEMENTS; } while/until ( EXPRESSION );

Page 20: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

2020

Control Structures (continued)

Control Structures (continued)

for loopfor loop

for (INITIAL_EXPR ; COND_EXPR ; LOOP_EXPR ) {

STATEMENTS;

} foreachforeach loop loop

foreach $tmp (@arr) {

# do something with $tmp

}

All loops support the following two control statements:All loops support the following two control statements: lastlast : : Declare that this is the last statement in the loop; completely exit the loop Declare that this is the last statement in the loop; completely exit the loop

even if the condition is still true, ignoring all statements up to the loop's closing even if the condition is still true, ignoring all statements up to the loop's closing brace. brace.

nextnext : : Start a new iteration of the loopStart a new iteration of the loop

Page 21: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

2121

File HandlingFile Handling$file = '/etc/passwd'; # Name the file

open(INFO, $file); # Open the file

@lines = <INFO>; # Read it into an array

close(INFO); # Close the file

print @lines; # Print the array

<> is line reading operator<> is line reading operator If the filename was given in quotes then it is taken literally without shellIf the filename was given in quotes then it is taken literally without shell e expansionxpansion. T. To o

force shell expansion then use angled bracketsforce shell expansion then use angled brackets. U. Use se like like <~/notes/todolist><~/notes/todolist>

open(INFO, $file); # Open for input

open(INFO, ">$file"); # Open for output

open(INFO, ">>$file"); # Open for appending

open(INFO, "<$file"); # Also open for input

Page 22: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

2222

File Handling (continued)File Handling (continued) To print a string to the file with the INFO filehandle useTo print a string to the file with the INFO filehandle use

print INFO "This line goes to the file.\n"; 3 predefined file handler STDIN, STDOUT, STDERR3 predefined file handler STDIN, STDOUT, STDERR

TTo open the standard input (usually the keyboard) and standard outputo open the standard input (usually the keyboard) and standard output

open(INFO, '-'); # Open standard input

open(INFO, '>-'); # Open standard output

chop($number=<STDIN>); #input number and remove newline

chop($number=<>); #input number and remove newline

Which meansWhich means

$number=<STDIN>; #input number

chop($number); #remove newline

print STDOUT “The number is $number. \n” #print the number

Page 23: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

2323

String MatchingString Matching One of the most useful features of Perl is its powerful string manipulation facilitiesOne of the most useful features of Perl is its powerful string manipulation facilities. . A A

regular expression is contained in slashes, and matching occurs with the =~ operator.regular expression is contained in slashes, and matching occurs with the =~ operator. T The he operator !~ is used for spotting a non-matchoperator !~ is used for spotting a non-match

$sentence =~ /the/ # expression is true if the string # “the” appears in the variable

$sentence !~ /the/

The RE is case sensitiveThe RE is case sensitive if we assign the sentence to the special variable $_ which is of course a scalarif we assign the sentence to the special variable $_ which is of course a scalar::

if (/under/)

{ print "We're talking about rugby\n";

}

Page 24: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

2424

String Matching (continued)

String Matching (continued)

Here are some special RE characters and their meaningHere are some special RE characters and their meaning

. # Any single character except a newline

^ # The beginning of the line or string

$ # The end of the line or string

* # Zero or more of the last character

+ # One or more of the last character

? # Zero or one of the last character

[qjk] # Either q or j or k

[^qjk] # Neither q nor j nor k

[a-z] # Anything from a to z inclusive

[^a-z] # No lower case letters

[a-zA-Z] # Any letter

[a-z]+ # Any non-zero sequence of lower case letters

jelly|cream # Either jelly or cream

(eg|le)gs # Either eggs or legs

(da)+ # Either da or dada or dadada or...

.*?: # It stops at first colon

Page 25: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

2525

Substitution and Translation

Substitution and Translation

Perl can make substitutions based on matchesPerl can make substitutions based on matches

$sentence =~ s/london/London/ # To replace an occurrence of # london by London in the string

s/london/London/ # To do the same thing with the # $_ variable

s/[Ll][Oo][Nn][Dd][Oo][Nn]/London/g # To make global substitution

s/london/London/gi # an easier way is to use the i # option (for "ignore case").

$sentence =~ tr/abc/edf/ # tr function allows character-# by-character translation

tr/a-z/A-Z/; # This statement converts $_ to # upper case

Page 26: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

2626

SplitSplitThe The splitsplit function is used like this: function is used like this:

$info = "Caine:Michael:Actor:14, Leafy Drive";

@personal = split(/:/, $info);

which has the same overall effect as which has the same overall effect as

@personal = ("Caine", "Michael", "Actor", "14, Leafy Drive");

If we have the information stored in the If we have the information stored in the $_$_ variable then we can just use this instead variable then we can just use this instead

@personal = split(/:/);

@chars = split(//, $word);

@words = split(/ /, $sentence);

@sentences = split(/\./, $paragraph);

Page 27: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

2727

SubroutinesSubroutinessub printargs

{ print "@_\n"; }

&printargs("perly", "king"); &printargs("perly", "king"); # Example prints # Example prints perlyperly kingking

&printargs("frog", "and", "toad"); &printargs("frog", "and", "toad"); # Prints "frog and toad" # Prints "frog and toad"

sub printfirsttwo sub printfirsttwo

{ {

print "Your first argument was $_[0]\n"; print "Your first argument was $_[0]\n";

print "and $_[1] was your second\n"; print "and $_[1] was your second\n";

} } indexed scalars $_[0], $_[1] and so on have nothing to with the scalar $_indexed scalars $_[0], $_[1] and so on have nothing to with the scalar $_ Result of a subroutine is always the last thing evaluatedResult of a subroutine is always the last thing evaluatedsub maximum

{ if ($_[0] > $_[1])

{ $_[0]; }

else

{ $_[1]; }

}

$biggest = &maximum(37, 24); # Now $biggest is 37

Page 28: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

2828

Example 1Example 1 Finds users whose accounts were locked in a linux computer.Finds users whose accounts were locked in a linux computer.

open(FD,"/etc/shadow");@users=<FD>;foreach $elem (@users){ ($user,$passwdfield)=split(/:/,$elem); if ($passwdfield =~ /^!/){ print $user."\n"; }}

Finds users whose accounts were locked in a Solaris computerFinds users whose accounts were locked in a Solaris computeropen(FD,"/etc/shadow");@users=<FD>;foreach $elem (@users){ ($user,$passwdfield)=split(/:/,$elem); if ($passwdfield eq "*LK*"){ print $user."\n"; }}

Page 29: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

2929

Example 2Example 2

Finds words in the dictionary file /usr/dict/words that consists of only Finds words in the dictionary file /usr/dict/words that consists of only asdfjghjkl lettersasdfjghjkl letters

open(fd,"/usr/dict/words");

while($line=<fd>){

if ($line =~ /^[asdfjklgh]+$/)

{print $line;}

}

Page 30: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

3030

Example 3Example 3 Counts # of lines , # of sentences, # of nonwhitespace chars and determines which word is used Counts # of lines , # of sentences, # of nonwhitespace chars and determines which word is used

how many times in the file whose name is given as parameter or in the text which is input from how many times in the file whose name is given as parameter or in the text which is input from stdin if no parameter is given. stdin if no parameter is given.

@text=<>;

foreach $sentence (@text){

$sentencecount++;

@words=split(/\s/,$sentence);

foreach $word (@words){

$myhash{$word}++;

$wordcount++;

@chars=split(//,$word);

$charcount+=scalar(@chars);

}

}

print "Total Number of Lines: $sentencecount\n";

print "Total Number of Words: $wordcount\n";

print "Total Number of Nonwhitespace chars: $charcount\n";

foreach $word (sort keys %myhash){

print "$word: $myhash{$word}\n";

}

Page 31: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

3131

Example 4Example 4open(FD,"/var/mail/basarabu") or die "No inbox";

while (<FD>)

{ print if /^From:/ ; }

close FD;

open(FD,"/var/mail/basarabu") or die "No inbox";

while (<FD>)

{ print "$1\n" if /^From:(.+)/ ; }

close FD;

open(FD,"/var/mail/basarabu") or die "No inbox";

while (<FD>)

{

next unless /^From:(.+)/;

next if $seen{$1};

print "$1\n";

$seen{$1}=1;

}

close FD;

Page 32: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

3232

Perl Socket ProgrammingPerl Socket Programming Perl Perl socket socket functionfunctionss have the same names as the corresponding system calls in C have the same names as the corresponding system calls in C.. AArguments tend to differ for two reasons:rguments tend to differ for two reasons:

Perl filehandles work differently than C file descriptorsPerl filehandles work differently than C file descriptors Perl already knows the length of its stringsPerl already knows the length of its strings

AA sample TCP client using Internet-domain sockets sample TCP client using Internet-domain sockets::

use strict; use strict; use Socket; use Socket; my ($remote,$port, $iaddr, $paddr, $proto, $line); my ($remote,$port, $iaddr, $paddr, $proto, $line); $remote = $remote = shift || shift || 'localhost'; 'localhost'; $port = $port = shift || shift || 2345; # random port 2345; # random port $iaddr = inet_aton($remote) || die "no host: $remote"; $iaddr = inet_aton($remote) || die "no host: $remote"; $paddr = sockaddr_in($port, $iaddr); $paddr = sockaddr_in($port, $iaddr); $proto = getprotobyname('tcp'); $proto = getprotobyname('tcp'); socket(SOCK, PF_INET, SOCK_STREAM, $proto) || die "socket: $!"; socket(SOCK, PF_INET, SOCK_STREAM, $proto) || die "socket: $!"; connect(SOCK, $paddr) || die "connect: $!"; connect(SOCK, $paddr) || die "connect: $!"; while (defined($line = <SOCK>)) { print $line; } while (defined($line = <SOCK>)) { print $line; } close (SOCK) || die "close: $!"; close (SOCK) || die "close: $!"; exit; exit;

Page 33: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

3333

A Corresponding ServerA Corresponding Serveruse strict;

use Socket;

use Carp;

$EOL = "\015\012"; # carriage return followed by new line

sub logmsg { print ”$_[0] at ", scalar localtime, "\n" }

my $port = shift || 2345;

my $proto = getprotobyname('tcp');

socket(Server, PF_INET, SOCK_STREAM, $proto) || die "socket: $!"; setsockopt(Server, SOL_SOCKET, SO_REUSEADDR, pack("l",1)) || die "setsockopt:$!";

bind(Server, sockaddr_in($port, INADDR_ANY)) || die "bind: $!";

listen(Server,SOMAXCONN) || die "listen: $!";

logmsg "server started on port $port";

my $paddr;

for ( ; $paddr = accept(Client,Server); close Client) {

my($port, $iaddr) = sockaddr_in($paddr);

my $name = gethostbyaddr($iaddr,AF_INET);

logmsg "connection from $name [", inet_ntoa($iaddr), "] at port $port";

print Client "Hello there, $name, it's now ", scalar localtime, $EOL;

}

Page 34: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

3434

Multithreaded ServerMultithreaded Serveruse strict;

use Socket;

use Carp;

$EOL = "\015\012";

sub spawn; # forward declaration

sub logmsg { print "@_ at ", scalar localtime, "\n" }

my $port = shift || 2345;

my $proto = getprotobyname('tcp');

socket(Server, PF_INET, SOCK_STREAM, $proto) || die "socket: $!";

setsockopt(Server, SOL_SOCKET, SO_REUSEADDR, pack("l", 1))

|| die "setsockopt: $!";

bind(Server, sockaddr_in($port, INADDR_ANY)) || die "bind: $!";

listen(Server,SOMAXCONN) || die "listen: $!";

logmsg "server started on port $port";

my $waitedpid = 0;

my $paddr;

Page 35: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

3535

Multithreaded Server (cont. I)

Multithreaded Server (cont. I)

sub REAPER { $waitedpid = wait; $SIG{CHLD} = \&REAPER; # loathe sysV logmsg "reaped $waitedpid";

} $SIG{CHLD} = \&REAPER;

for ( $waitedpid = 0; ($paddr = accept(Client,Server)) || $waitedpid; $waitedpid = 0, close Client)

{ next if $waitedpid and not $paddr; my($port,$iaddr) = sockaddr_in($paddr); my $name = gethostbyaddr($iaddr,AF_INET); logmsg “Conn. from $name [", inet_ntoa($iaddr), "] at port $port"; spawn;

}

Page 36: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

3636

Multithreaded Server (cont. II)

Multithreaded Server (cont. II)

sub spawn {

my $coderef = shift;

unless (@_ == 0 && $coderef && ref($coderef) eq 'CODE') {

confess "usage: spawn CODEREF";

}

my $pid;

if (!defined($pid = fork)) {

logmsg "cannot fork: $!";

return;

} elsif ($pid) {

logmsg "begat $pid";

return; # I'm the parent

} # else I'm the child -- go spawn

open(STDIN, "<&Client") || die "can't dup client to stdin"; open(STDOUT, ">&Client") || die "can't dup client to stdout"; print "Hello there, $name, it's now ", scalar localtime, $EOL; exec '/usr/games/myGame’ or confess "can't exec the game: $!";

exit;

}

Page 37: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

3737

A Sample Unix-domain Client

A Sample Unix-domain Client

#!/usr/bin/perl -w

use Socket;

use strict;

my ($rendezvous, $line);

$rendezvous = shift || '/tmp/catsock';

socket(SOCK, PF_UNIX, SOCK_STREAM, 0) || die "socket: $!";

connect(SOCK, sockaddr_un($rendezvous)) || die "connect: $!";

while (defined($line = <SOCK>))

{

print $line;

}

exit;

Page 38: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

3838

A Corresponding ServerA Corresponding Serveruse strict; use Socket; use Carp;

sub logmsg { print "@_ at ", scalar localtime, "\n" } my $NAME = '/tmp/catsock'; my $uaddr = sockaddr_un($NAME); my $proto = getprotobyname('tcp'); socket(Server,PF_UNIX,SOCK_STREAM,0) || die "socket: $!"; unlink($NAME); bind (Server, $uaddr) || die "bind: $!"; listen(Server,SOMAXCONN) || die "listen: $!"; logmsg "server started on $NAME"; my $waitedpid; sub REAPER {

$waitedpid = wait; $SIG{CHLD} = \&REAPER; logmsg "reaped $waitedpid”;

}

Page 39: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

3939

Corresponding Server (cont.)

Corresponding Server (cont.)

$SIG{CHLD} = \&REAPER;

for (

$waitedpid = 0;

accept(Client,Server) || $waitedpid;

$waitedpid = 0, close Client)

{

next if $waitedpid;

logmsg "connection on $NAME";

spawn sub {

print "Hello there, it's now ", scalar localtime, "\n";

exec '/usr/games/myGame' or die "can't exec myGame: $!";

};

}

Page 40: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

4040

Object-Oriented Network Programming

Object-Oriented Network Programming

Some basic modules:Some basic modules: IO::SocketIO::Socket IO::Socket::INET, IO::Socket::UNIXIO::Socket::INET, IO::Socket::UNIX Net::InetNet::Inet Net::FTPNet::FTP Net::TCPNet::TCP Net::UDPNet::UDP Net::TelnetNet::Telnet Net::DNSNet::DNS

Page 41: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

4141

IO::SocketIO::SocketIO::SocketIO::Socket BBuilt upon the uilt upon the IOIO interface and inherits all the methods defined by interface and inherits all the methods defined by IOIO OOnly defines methods for those operations which are common to all types of socketnly defines methods for those operations which are common to all types of socket Operations Operations which are spewhich are speccifiificc to a socket in a particular domain have methods to a socket in a particular domain have methods

defined in sub classes of defined in sub classes of IO::SocketIO::Socket Methods:Methods:

accept([PKG]) accept([PKG]) timeout([VAL])timeout([VAL])

Set or get the timeout value associated with this socketSet or get the timeout value associated with this socket

sockopt(OPT [, VAL])sockopt(OPT [, VAL]) If called with one argument then getsockopt is called, otherwise setsockopt is calledIf called with one argument then getsockopt is called, otherwise setsockopt is called

sockdomainsockdomain Returns the numerical number for the socket domain typeReturns the numerical number for the socket domain type

socktype socktype Returns the numerical number for the socket typeReturns the numerical number for the socket type

protocol protocol Returns the numerical number for the protocol being used on the socket, if knownReturns the numerical number for the protocol being used on the socket, if known

Page 42: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

4242

IO::Socket::INETIO::Socket::INETIO::Socket::INETIO::Socket::INET Object interface for AF_INET domain socketsObject interface for AF_INET domain sockets BBuilt upon the uilt upon the IOIO interface and inherits all the methods defined by interface and inherits all the methods defined by IOIO key-value pairs accepted by construtor:key-value pairs accepted by construtor:

PeerAddr PeerAddr Remote host address Remote host address <hostname>[:<port>] <hostname>[:<port>] PeerPort PeerPort Remote port or serviceRemote port or service <service>[(<no>)] | <service>[(<no>)] |

<no> <no> LocalAddr LocalAddr Local host bind address Local host bind address LocalPortLocalPort Local host bind port Local host bind port ProtoProto Protocol name (or number) Protocol name (or number) "tcp" | "udp" | ... "tcp" | "udp" | ... Type Type Socket type Socket type SOCK_STREAM | SOCK_DGRAM |.. SOCK_STREAM | SOCK_DGRAM |.. ListenListen Queue size for listen Queue size for listen Reuse Reuse Set SO_REUSEADDR before binding Set SO_REUSEADDR before binding Timeout Timeout Timeout value for various operations Timeout value for various operations MultiHomed MultiHomed Try all addresses for multi-homed hosts Try all addresses for multi-homed hosts

Page 43: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

4343

IO::Socket::INET (cont.)IO::Socket::INET (cont.)IO::Socket::INET (cont.)IO::Socket::INET (cont.) Examples:Examples:

$sock = IO::Socket::INET->new($sock = IO::Socket::INET->new(

PeerAddr => 'www.perl.org', PeerAddr => 'www.perl.org',

PeerPort => 'http(80)', PeerPort => 'http(80)',

Proto => 'tcp‘Proto => 'tcp‘

););

$sock = IO::Socket::INET->new(PeerAddr => 'localhost:smtp(25)');$sock = IO::Socket::INET->new(PeerAddr => 'localhost:smtp(25)');

$sock = IO::Socket::INET->new($sock = IO::Socket::INET->new(

Listen => 5, Listen => 5,

LocalAddr => 'localhost', LocalAddr => 'localhost',

LocalPort => 9000, LocalPort => 9000,

Proto => 'tcp‘Proto => 'tcp‘

););

$sock = IO::Socket::INET->new(’www.boun.edu.tr:80');$sock = IO::Socket::INET->new(’www.boun.edu.tr:80');

Page 44: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

4444

IO::Socket::UnixIO::Socket::UnixIO::Socket::UnixIO::Socket::Unix Object interface for AF_UNIX domain socketsObject interface for AF_UNIX domain sockets key-value pairs accepted by construtor:key-value pairs accepted by construtor:

Type Type Type of socket (eg SOCK_STREAM or SOCK_DGRAM)Type of socket (eg SOCK_STREAM or SOCK_DGRAM) Local Local Path to local fifoPath to local fifo Peer Peer Path to peer fifoPath to peer fifo Listen Listen Create a listen socketCreate a listen socket

Methods:Methods:

hostpath()hostpath() Returns the pathname to the fifo at the local endReturns the pathname to the fifo at the local end

peerpath()peerpath() Returns the pathanme to the fifo at the peer endReturns the pathanme to the fifo at the peer end

Page 45: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

4545

Net::InetNet::InetNet::InetNet::Inet Provides basic services for handling socket-based communications for the Internet Provides basic services for handling socket-based communications for the Internet

protocol protocol

Public Methods:Public Methods: newnew

$obj = new Net::Inet; $obj = new Net::Inet;

$obj = new Net::Inet $host, $service; $obj = new Net::Inet $host, $service;

$obj = new Net::Inet \%parameters; $obj = new Net::Inet \%parameters;

$obj = new Net::Inet $host, $service, \%parameters;$obj = new Net::Inet $host, $service, \%parameters; initinit

return undef unless $self->init; return undef unless $self->init;

return undef unless $self->init(\%parameters); return undef unless $self->init(\%parameters);

return undef unless $self->init($host, $service); return undef unless $self->init($host, $service);

return undef unless $self->init($host, $service, \%parameters);return undef unless $self->init($host, $service, \%parameters); bindbind

$ok = $obj->bind; $ok = $obj->bind;

$ok = $obj->bind($host, $service); $ok = $obj->bind($host, $service);

$ok = $obj->bind($host, $service, \%parameters);$ok = $obj->bind($host, $service, \%parameters);

Page 46: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

4646

Net::Inet (cont. I)Net::Inet (cont. I)Net::Inet (cont. I)Net::Inet (cont. I) unbind unbind

$obj->unbind;$obj->unbind;

connectconnect

$ok = $obj->connect; $ok = $obj->connect;

$ok = $obj->connect($host, $service); $ok = $obj->connect($host, $service);

$ok = $obj->connect($host, $service, \%parameters);$ok = $obj->connect($host, $service, \%parameters);

format_addrformat_addr $string = $obj->format_addr($sockaddr); $string = $obj->format_addr($sockaddr);

$string = $obj->format_addr($sockaddr, $numeric_only);$string = $obj->format_addr($sockaddr, $numeric_only);

format_local_addr, format_remote_addr format_local_addr, format_remote_addr

$string = $obj->format_local_addr; $string = $obj->format_local_addr;

$string = $obj->format_local_addr($numeric_only); $string = $obj->format_local_addr($numeric_only);

$string = $obj->format_remote_addr;$string = $obj->format_remote_addr;

Page 47: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

4747

Net::Inet (cont. II)Net::Inet (cont. II)Net::Inet (cont. II)Net::Inet (cont. II) Non-Method Subroutines:Non-Method Subroutines:

inet_atoninet_aton returns the packed AF_INET address in network orderreturns the packed AF_INET address in network order

$in_addr = inet_aton('192.0.2.1');$in_addr = inet_aton('192.0.2.1'); inet_addrinet_addr a synonym for a synonym for inet_aton() inet_aton()

inet_ntoainet_ntoa returns the ASCII representation of the returns the ASCII representation of the AF_INET address AF_INET address providedprovided

$addr_string = inet_ntoa($in_addr); $addr_string = inet_ntoa($in_addr);

htonl, htons, ntohl, ntohs htonl, htons, ntohl, ntohs pack_sockaddr_in pack_sockaddr_in returns the packed struct sockaddr_inreturns the packed struct sockaddr_in

$connect_address = pack_sockaddr_in($family, $port, $in_addr); $connect_address = pack_sockaddr_in($family, $port, $in_addr);

$connect_address = pack_sockaddr_in($port, $in_addr);$connect_address = pack_sockaddr_in($port, $in_addr);

unpack_sockaddr_in unpack_sockaddr_in returns the address family, port, and packed struct in_addrreturns the address family, port, and packed struct in_addr ($family, $port, $in_addr) = unpack_sockaddr_in($connected_address); ($family, $port, $in_addr) = unpack_sockaddr_in($connected_address);

Page 48: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

4848

Net::FTPNet::FTPNet::FTPNet::FTP FTP Client classFTP Client class Methods:Methods:

new (HOST [,OPTIONS]) new (HOST [,OPTIONS])

Options are: Firewall, Port, Timeout, Debug, PassiveOptions are: Firewall, Port, Timeout, Debug, Passive

login ([LOGIN [,PASSWORD [, ACCOUNT] ] ]) login ([LOGIN [,PASSWORD [, ACCOUNT] ] ])

type (TYPE [, ARGS]) type (TYPE [, ARGS])

ascii ([ARGS]) binary([ARGS]) ascii ([ARGS]) binary([ARGS])

rename ( OLDNAME, NEWNAME ) rename ( OLDNAME, NEWNAME )

delete ( FILENAME ) delete ( FILENAME )

cwd ( [ DIR ] )cwd ( [ DIR ] )

cdup () cdup ()

pwd () pwd ()

rmdir ( DIR ) rmdir ( DIR )

mkdir ( DIR [, RECURSE ]) mkdir ( DIR [, RECURSE ])

get ( REMOTE_FILE [, LOCAL_FILE [, WHERE]] ) get ( REMOTE_FILE [, LOCAL_FILE [, WHERE]] )

Page 49: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

4949

Net::FTP (cont. I)Net::FTP (cont. I)Net::FTP (cont. I)Net::FTP (cont. I) put ( LOCAL_FILE [, REMOTE_FILE ] ) put ( LOCAL_FILE [, REMOTE_FILE ] )

append ( LOCAL_FILE [, REMOTE_FILE ] ) append ( LOCAL_FILE [, REMOTE_FILE ] )

mdtm ( FILE ) mdtm ( FILE )

modification time of a filemodification time of a file

size ( FILE ) size ( FILE )

supported ( CMD ) supported ( CMD )

pasv () pasv ()

pasv_xfer ( SRC_FILE, DEST_SERVER [, DEST_FILE ] ) pasv_xfer ( SRC_FILE, DEST_SERVER [, DEST_FILE ] )

do a file transfer between two remote ftp serversdo a file transfer between two remote ftp servers

pasv_wait ( NON_PASV_SERVER ) pasv_wait ( NON_PASV_SERVER )

wait for a transfer to complete between a passive server and a non-passive serverwait for a transfer to complete between a passive server and a non-passive server

abort () abort ()

quit ()quit ()

Page 50: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

5050

Net::FTP (cont. II)Net::FTP (cont. II)Net::FTP (cont. II)Net::FTP (cont. II) Example:Example:

use Net::FTP;use Net::FTP;

$ftp = Net::FTP->new(”ftp.boun.edu.tr"); $ftp = Net::FTP->new(”ftp.boun.edu.tr");

$ftp->login("anonymous","[email protected]"); $ftp->login("anonymous","[email protected]");

$ftp->cwd("/pub"); $ftp->cwd("/pub");

$ftp->get("the.file"); $ftp->get("the.file");

$ftp->quit;$ftp->quit;

Page 51: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

5151

Net::TCPNet::TCPNet::TCPNet::TCP Provides services for TCP communications over socketsProvides services for TCP communications over sockets

Layered on top of the Net::Inet and Net::Gen modulesLayered on top of the Net::Inet and Net::Gen modules

Constructor:Constructor: $obj = new Net::TCP; $obj = new Net::TCP;

$obj = new Net::TCP $host, $service; $obj = new Net::TCP $host, $service;

$obj = new Net::TCP \%parameters; $obj = new Net::TCP \%parameters;

$obj = new Net::TCP $host, $service, \%parameters;$obj = new Net::TCP $host, $service, \%parameters;

Page 52: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

5252

Net::UDPNet::UDPNet::UDPNet::UDP Provides services for UDP communications over socketsProvides services for UDP communications over sockets

Layered on top of the Net::Inet and Net::Gen modulesLayered on top of the Net::Inet and Net::Gen modules

Constructor:Constructor: $obj = new Net::UDP;$obj = new Net::UDP;

$obj = new Net::UDP $host, $service;$obj = new Net::UDP $host, $service;

$obj = new Net::UDP \%parameters;$obj = new Net::UDP \%parameters;

$obj = new Net::UDP $host, $service, \%parameters;$obj = new Net::UDP $host, $service, \%parameters;

Page 53: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

5353

Net::TelnetNet::TelnetNet::TelnetNet::Telnet All output is flushed while all input is buffered. Each object contains an input bufferAll output is flushed while all input is buffered. Each object contains an input buffer

Simple ExampleSimple Example::

use Net::Telnet; use Net::Telnet;

$t = new Net::Telnet (Timeout => 10, Prompt => '/bash\$ $/'); $t = new Net::Telnet (Timeout => 10, Prompt => '/bash\$ $/');

$t->open(”yunus.cmpe.boun.edu.tr"); $t->open(”yunus.cmpe.boun.edu.tr");

$t->login($username, $passwd); $t->login($username, $passwd);

@lines = $t->cmd("/usr/bin/who"); @lines = $t->cmd("/usr/bin/who");

print @lines;print @lines;

In addition to a username and password, you must also know the user's shell prompt, In addition to a username and password, you must also know the user's shell prompt, which which for this example is for this example is bash$bash$

The methods The methods login()login() and and cmdcmd()() use the use the promptprompt setting in the object to determine when a login or remote setting in the object to determine when a login or remote

command is completecommand is complete

Page 54: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

5454

Net::Telnet (cont. I)Net::Telnet (cont. I)Net::Telnet (cont. I)Net::Telnet (cont. I) Example: Example: This example gets a weather forecastThis example gets a weather forecast

my($forecast, $t);my($forecast, $t); use Net::Telnet;use Net::Telnet; $t = new Net::Telnet;$t = new Net::Telnet; $t->open("rainmaker.wunderground.com");$t->open("rainmaker.wunderground.com");

## Wait for first prompt and "hit return".## Wait for first prompt and "hit return". $t->waitfor('/continue:.*$/');$t->waitfor('/continue:.*$/'); $t->print("");$t->print("");

## Wait for second prompt and respond with city code.## Wait for second prompt and respond with city code. $t->waitfor('/city code.*$/');$t->waitfor('/city code.*$/'); $t->print("BRD");$t->print("BRD");

## Read and print the first page of forecast.## Read and print the first page of forecast. ($forecast) = $t->waitfor('/[ \t]+press return to continue/i');($forecast) = $t->waitfor('/[ \t]+press return to continue/i'); print $forecast;print $forecast;

$t->close;$t->close; exit;exit;

Page 55: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

5555

Net::Telnet (cont. II)Net::Telnet (cont. II)Net::Telnet (cont. II)Net::Telnet (cont. II) Example: Example: This example checks a POP server if we have mailThis example checks a POP server if we have mail

my($hostname, $line, $passwd, $pop, $username);my($hostname, $line, $passwd, $pop, $username);$hostname = "your_destination_host_here";$hostname = "your_destination_host_here";

$username = "your_username_here";$username = "your_username_here"; $passwd = "your_password_here";$passwd = "your_password_here"; use Net::Telnet ();use Net::Telnet ();

# Turn off the telnet mode since the port we’re connecting is not telnet# Turn off the telnet mode since the port we’re connecting is not telnet $pop = new Net::Telnet (Telnetmode => 0);$pop = new Net::Telnet (Telnetmode => 0);

$pop->open(Host => $hostname, Port => 110);$pop->open(Host => $hostname, Port => 110);

## Read connection message.## Read connection message. $line = $pop->getline;$line = $pop->getline; die $line unless $line =~ /^\+OK/;die $line unless $line =~ /^\+OK/;

## Send user name.## Send user name. $pop->print("user $username");$pop->print("user $username"); $line = $pop->getline;$line = $pop->getline; die $line unless $line =~ /^\+OK/;die $line unless $line =~ /^\+OK/;

## Send password.## Send password. $pop->print("pass $passwd");$pop->print("pass $passwd"); $line = $pop->getline;$line = $pop->getline; die $line unless $line =~ /^\+OK/;die $line unless $line =~ /^\+OK/;

## Request status of messages.## Request status of messages. $pop->print("list");$pop->print("list"); $line = $pop->getline;$line = $pop->getline; print $line;print $line; exit;exit;

Page 56: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

5656

Net::Telnet (cont. III)Net::Telnet (cont. III)Net::Telnet (cont. III)Net::Telnet (cont. III) Example: Example: This example downloads a file of any typeThis example downloads a file of any type

my(my( $block, $filename, $host, $hostname, $k_per_sec, $line, $block, $filename, $host, $hostname, $k_per_sec, $line, $num_read, $passwd, $prevblock, $prompt, $size, $size_bsd, $num_read, $passwd, $prevblock, $prompt, $size, $size_bsd, $size_sysv, $start_time, $total_time, $username);$size_sysv, $start_time, $total_time, $username);

$hostname = "your_destination_host_here";$hostname = "your_destination_host_here"; $username = "your_username_here";$username = "your_username_here"; $passwd = "your_password_here";$passwd = "your_password_here"; $filename = "your_download_file_here";$filename = "your_download_file_here";

## Connect and login.## Connect and login. use Net::Telnet ();use Net::Telnet (); $host = new Net::Telnet (Timeout => 30, Prompt => '/[%#>] $/');$host = new Net::Telnet (Timeout => 30, Prompt => '/[%#>] $/'); $host->open($hostname);$host->open($hostname); $host->login($username, $passwd);$host->login($username, $passwd);

## Make sure prompt won't match anything in send data.## Make sure prompt won't match anything in send data. $prompt = '_funkyPrompt_';$prompt = '_funkyPrompt_'; $host->prompt("/$prompt\$/");$host->prompt("/$prompt\$/"); $host->cmd("set prompt = '$prompt'");$host->cmd("set prompt = '$prompt'");

## Get size of file.## Get size of file. ($line) = $host->cmd("/usr/bin/ls -l $filename");($line) = $host->cmd("/usr/bin/ls -l $filename"); ($size_bsd, $size_sysv) = (split ' ', $line)[3,4];($size_bsd, $size_sysv) = (split ' ', $line)[3,4]; if ($size_sysv =~ /^\d+$/) if ($size_sysv =~ /^\d+$/) { $size = $size_sysv; }{ $size = $size_sysv; } elsif ($size_bsd =~ /^\d+$/) elsif ($size_bsd =~ /^\d+$/) { $size = $size_bsd; }{ $size = $size_bsd; } else else { die "$filename: no such file on { die "$filename: no such file on

$hostname"; }$hostname"; }

Page 57: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

5757

Net::Telnet (cont. IV)Net::Telnet (cont. IV)Net::Telnet (cont. IV)Net::Telnet (cont. IV)## Start sending the file.## Start sending the file.

binmode STDOUT;binmode STDOUT; $host->binmode(1);$host->binmode(1); $host->print("cat $filename");$host->print("cat $filename"); $host->getline; # discard echoed back line$host->getline; # discard echoed back line

## Read file a block at a time.## Read file a block at a time. $num_read = 0;$num_read = 0; $prevblock = '';$prevblock = ''; $start_time = time;$start_time = time; while (($block = $host->get) and ($block !~ /$prompt$/o)) {while (($block = $host->get) and ($block !~ /$prompt$/o)) { if (length $block >= length $prompt) {if (length $block >= length $prompt) { print $prevblock;print $prevblock; $num_read += length $prevblock;$num_read += length $prevblock; $prevblock = $block;$prevblock = $block; }} else {else { $prevblock .= $block;$prevblock .= $block; }} }} $host->close;$host->close;

exit;exit;

Page 58: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

5858

Example 5 Example 5 Simple Client reads from standard input or from file given as parameter and sends to the Simple Client reads from standard input or from file given as parameter and sends to the

server. server. Perl provides support for the socket API nativelyPerl provides support for the socket API natively. A. Although the interface is not lthough the interface is not that bad anyway, there is also a very convenient module, IO::Socket that works like a that bad anyway, there is also a very convenient module, IO::Socket that works like a wrapper on the native API and provides a simpler and easier way to deal with sockets.wrapper on the native API and provides a simpler and easier way to deal with sockets.

use IO::Socket;

my $sock = new IO::Socket::INET (

PeerAddr => 'ipsala.cc.boun.edu.tr',

PeerPort => '2581',

Proto => 'tcp',

Timeout => '5',

);

die "Could not create socket: $!\n" unless $sock;

while($line=<>){

print $sock $line;

}

close($sock);

Page 59: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

5959

Example 5 (continued)Example 5 (continued) Simple Server reads from the socket and writes to the screen. It is an iterative server.Simple Server reads from the socket and writes to the screen. It is an iterative server.

use IO::Socket;

my $sock = new IO::Socket::INET (

LocalHost => 'ipsala.cc.boun.edu.tr',

LocalPort => '2581',

Proto => 'tcp',

Listen => 1,

Reuse => 1,

);

die "Could not create socket: $!\n" unless $sock;

while(){

my $new_sock = $sock->accept();

if (defined($new_sock)){

print "Connected with client:".$new_sock->peerhost().":".$new_sock->peerport()."\n";

while($line=<$new_sock>) {

print $line;

}

}

print "Connection closed with client:".$new_sock->peerhost().":".$new_sock->peerport()."\n";

close($new_sock);

undef($new_sock);

}

Page 60: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

6060

Example 5 (continued II)Example 5 (continued II)use IO::Socket; $sock = new IO::Socket::INET ( LocalHost => 'ipsala', LocalPort => '2581', Proto => 'tcp', Listen => 5, Reuse => 1,); die "Could not create socket: $!\n" unless $sock; use IO::Select; $read_set = new IO::Select(); # create handle set for reading $read_set->add($sock); # add the main socket to the set while () { @ready=$read_set->can_read(); foreach $rh (@ready) { if ($rh == $sock) { $ns = $rh->accept(); print "Connected with client:".$ns->peerhost().":".$ns->peerport()."\n"; $read_set->add($ns); } else { $buf = <$rh>; if($buf) { print $rh->peerhost().":".$rh->peerport()." wrote >>"; print $buf; } else { $read_set->remove($rh); print "Connection closed with client:".$rh->peerhost().":".$rh->peerport()."\n"; close($rh); } } } }

Page 61: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

6161

Example 6Example 6 It finds all the DNS entries that belongs to a network for example 193.140.196 It finds all the DNS entries that belongs to a network for example 193.140.196

network.network.

use Net::Ping;

use Socket;

unless (scalar(@ARGV)==1){

print "Usage: <program name> <network in xxx.yyy.zzz format>\n";

exit 0;

}

print "DNS Entries for the network ($ARGV[0]) :\n";

for $i (1..254){

$host=$ARGV[0].".".$i;

my $Wert = gethostbyaddr(inet_aton("$host"), AF_INET);

print "$host--->$Wert\n";

}

Page 62: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

6262

Example 7Example 7 It finds all the open computer without firewall and corresponding DNS entries of a It finds all the open computer without firewall and corresponding DNS entries of a

network for example 193.140.196 network.network for example 193.140.196 network.

#only root can runuse Net::Ping;use Socket;unless (scalar(@ARGV)==1){ print "Usage: <program name> <network in xxx.yyy.zzz format>\n"; exit 0;}print "Alive Computers in network ($ARGV[0]) are : \n";for $i (1..254){ $p = Net::Ping->new("icmp"); $host=$ARGV[0].".".$i; if ($p->ping($host,1)){ my $Wert = gethostbyaddr(inet_aton("$host"), AF_INET); print "$host--->$Wert\n"; } $p->close();}

Page 63: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

6363

Example 8Example 8 Portscan the computer whose IP is given as parameter ,starting from the given first port Portscan the computer whose IP is given as parameter ,starting from the given first port

number to the given second port number.number to the given second port number.

use IO::Socket;

unless (scalar(@ARGV)==3) {

print "Usage: <IP> <StartPort> <EndPort>\n";

exit 1;

}

for $i ($ARGV[1]..$ARGV[2]){

my $sock = new IO::Socket::INET ( PeerAddr => $ARGV[0],

PeerPort => $i,

Proto => 'tcp',

Timeout=>1,);

if ($sock) { print "ok with $ARGV[0] on port $i\n" }

close($sock);

undef($sock);

}

Page 64: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

6464

Example 9Example 9 Sends a mail using the specified mail server from the specified person and from the specified Sends a mail using the specified mail server from the specified person and from the specified

domain to the specified person.domain to the specified person.

use IO::Socket::INET;print "Your domain name:"; $domainname=<STDIN>; print "Mail Server To Be Used:"; $mailserver=<STDIN>; chop($mailserver);print "Mail From:"; $mailfrom=<STDIN>; print "Mail To:"; $mailto=<STDIN>; print "Your message:"; @mesaj=<STDIN>;($mailfr1,$mailfr2)=split(/\@/,$mailfrom);($mailto1,$mailto2)=split(/\@/,$mailto);chop($mailfr2); chop($mailto2);$socket = IO::Socket::INET->new("$mailserver:25") or die "Couldn't connect to port 25 of hisar: $!";<$socket>; print $socket "HELO $domainname";<$socket>; print $socket "Mail from: <$mailfr1\@$mailfr2>\n";<$socket>; print $socket "rcpt to: <$mailto1\@$mailto2>\n";<$socket>; print $socket "data\n";<$socket>; print $socket "@mesaj \n ";print $socket "\r\n.\r\n";<$socket>;print $socket "quit\n";<$socket>;

Page 65: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

6565

Example 10Example 10 Simple RedirectionSimple Redirection#!/usr/local/bin/perl

print "Location: http://www.boun.edu.tr\n\n";

Prints environmental variables and time at the serverPrints environmental variables and time at the server#!/usr/local/bin/perl

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

print "<html><body>";

($sec, $min, $hour) = localtime (time);

$time = "$hour:$min:$sec";

print "Time at the server is : <b><big><big>$time</big></big></b><br><br>";

foreach $elem (sort keys %ENV)

{

print "<b>$elem</b> = $ENV{$elem}<br>";

}

print "</html></body>";

Page 66: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

6666

Example 11Example 11#!/usr/local/bin/perl

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

print "<html><body>";

$temp=`date '+(at %H:%M:%S in %m/%d/%y)'`;

system("echo $ENV{\"REMOTE_ADDR\"} is visiting your homepage at `date '+(at %H:%M:%S in %m/%d/%y)'` | mail basarabu");

$sayac_dosyasi="counter.log";

if(open(SAYAC,$sayac_dosyasi))

{

$ziyaretci_sayisi=<SAYAC>;

close(SAYAC);

if(open(SAYAC, ">$sayac_dosyasi"))

{

$ziyaretci_sayisi++;

print SAYAC $ziyaretci_sayisi;

close(SAYAC);

print "<CENTER><H2>Visitor Number: $ziyaretci_sayisi</H2></CENTER>";

}

else { print "counter.log dosyasina kayit yapamadim!!!"; }

}

else { print "counter.log dosyasini okumak icin acamadim!!!!"; }

print "</body></html>";

Page 67: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

6767

Example 12Example 12 My nslookup it can take both IP or domain name as parameter My nslookup it can take both IP or domain name as parameter

use Socket;

unless (scalar(@ARGV)==1){

print "Usage: <programname> <IP or DNS name>\n";

exit 0;

}

if ($ARGV[0] =~ /^[0-9]/)

{

$addr = inet_aton($ARGV[0]);

$x = gethostbyaddr($addr, AF_INET);

print "Name of the host : $x\n";

}

else

{

use Net::hostent;

my $h = gethostbyname($ARGV[0]);

if ($h){ print "IP of the host is : ",inet_ntoa($h->addr),"\n"; }

else { print "No DNS entry was found \n"; }

}

Page 68: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

6868

Example 13Example 13use IO::Socket::INET;

$socket = IO::Socket::INET->new("www.boun.edu.tr:80")

or die "Couldn't connect : $!";

print $socket "GET http://www.boun.edu.tr/scripts/studsearch.asp?language=Eng&Page=1&name=ali&surnam

e=&x=0&y=0 HTTP/1.0\n\n";

@a=<$socket>;

print @a;

use LWP::UserAgent;

use HTTP::Request::Common;

my $ua = LWP::UserAgent->new;

$site="www.mit.edu";

$res=$ua->request(GET "http://www.net.cmu.edu/cgi-bin/netops.cgi?query=$site&op=traceroute&.submit=Submit+Query&.cgifields=op");

if ($res->is_success) { print $res->content; };

Page 69: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

6969

Example 14Example 14use Net::FTP;

unless (scalar(@ARGV)==3) {

print "usage: <program-name> <hostaddress> <username> <password>\n";

exit 0;

}

$ftp = Net::FTP->new($ARGV[0]) or die "Couldn't connect: $@\n";

$ftp->login($ARGV[1],$ARGV[2]) or die "Could not login\n";

$ftp->binary;

my @items = $ftp->ls("-lFa");

print "Normal files in the account are :\n";

foreach $elem (@items){

unless ($elem =~ /^d/) { print $elem."\n"; }

}

print "Directories in the account are :\n";

foreach $elem (@items){

if ($elem =~ /^d/) { print $elem."\n"; };

}

$ftp->quit;

Page 70: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

7070

ResourcesResourcesResourcesResources http://www.perl.orghttp://www.perl.org http://www.perldoc.comhttp://www.perldoc.com http://www.perlfect.comhttp://www.perlfect.com http://www.modperl.comhttp://www.modperl.com http://www.perl.comhttp://www.perl.com http://forums.perlguru.comhttp://forums.perlguru.com http://www.oreilly.com/catalog/pperl3http://www.oreilly.com/catalog/pperl3 http://www.engelschall.com/ar/perldoc/http://www.engelschall.com/ar/perldoc/ Programming Perl, O’Reilly, 3Programming Perl, O’Reilly, 3rdrd Edition Edition

Page 71: CMPE 587 Advanced Network Programming PERL PROGRAMMING by Buğra Başaran Caner Kurtul

7171

ThanksThanks

QQuestions ?uestions ?