About site: Programming/Languages/Perl/FAQs, Help, and Tutorials - Strictly On-Line: Network Programming with Perl
Return to Computers also Computers
  About site: http://www.linuxjournal.com/article/3237

Title: Programming/Languages/Perl/FAQs, Help, and Tutorials - Strictly On-Line: Network Programming with Perl Using Perl to perform networking tasks is easy. An article by James Lee. (April 1, 1999)
Bluewater_Systems Distributes and supports ARM technology products and offers related consulting services.

TalkTrix Described as a fun place where you can meet other people and talk about anything you want.

Hype\'s_Color_Specifier_for_Netscape Vertical chart of image bars with names, hexadecimal and RGB codes, includes an HTML page with the chosen color.

t-_Sofotex Directory of freeware and shareware download sites, with rated descriptions of available programs, utilities, and scripts.

Programmershelp Various Visual Basic code snippets.

TD_Script_Shop Useful Perl CGI scripts with freeware versions, Perl tutorials, reasonable custom programming available.


  Alexa statistic for http://www.linuxjournal.com/article/3237





Get your Google PageRank






Please visit: http://www.linuxjournal.com/article/3237


  Related sites for http://www.linuxjournal.com/article/3237
    WorldFriendship_Net Free service, online chatrooms in English and Chinese.
    ResearchIndex__Structure-preserving_specification_languages_for_knowledge-based_systems Much work on validation and verification of knowledge based systems (KBSs) has been done in implementation languages, mostly rule based. Recent papers suggest it is useful to do validation and verific
    translations_pas C header files and sources translated for Borland Delphi. Includes MySQL client API and WebSite server API.
    NetMechanic_Web_Site_Maintenance Site offers a variety of site maintenance tools to help the webmaster manage a web site. Tools include an HTML validator, link checker, server monitor, and promotion tools.
    Uversa_Consulting Linux consulting for businesses in the Phoenix, Arizona.
    CertificationZone Cisco Certification Study Area. Online preparation for Cisco CCNA and CCIE certification exams. Includes free monthly White Papers (authored by industry leaders), practice questions, simulated exams,
    XEBOT Rapid Application Development and self contained multiplatform execution environment. The execution environment includes a full featured GUI. It run on a barebones system such a LINUX box with simple
    RFC2187_-_Application_of_Internet_Cache_Protocol_(ICP),_version_2 ICPv2 application specification.
    RFC_3390_-_Increasing_TCP\'s_Initial_Window Proposed standard, intended to improve startup performance of TCP.
    IceWM Window manager with partial KDE compliant (KDE hint support).
    Digital_Mars_C_and_C++_Compilers Successor of Symantec C++ with support for Win32, Win16, DOS16, and DOS32. Command-line compiler is freely available.
    CHAOS_Generator CHAOS Generator generates passwords of any length and character content. CHAOS Generator will create alphabetic, numeric, alphanumeric or all keyboard characters passwords of user-defined lengths.
    Tlbtlb_com__Downloads Downloads for watercolor brushes.
    RegNet_-_The_Registration_Network Registration Service, Charge: 10% + 3%, Optional use of their own registration code system.
    Property_Manager_Online Downloadable property management software for landlords and property managers. Organises and manages property details, tenants, payment schedules, accounts, property maintenance and insurance.
    ABA_Creative_Web_Services Offers site design. Located in Rio Rancho, New Mexico.
    WinCrypto_LLC Creates encrypted volume within a file or partition on a hard drive or any external data storage device and then mount it as a real disk.
    Buddy_Site_AIM_Icons Assortment of Buddy Icons
    Call_Handling_Services_Ltd Provides solutions to call handling problems for the private, public, and voluntary sectors.
    SilkWebware_Marquee Marquee control for WebForms. Compatible with IE 4+ and NN 6+.
This is websites2007.org cache of m/ as retrieved on 2008.08.21 websites2007.org's cache is the snapshot that we took of the page as we crawled the web. The page may have changed since that time.
Network Programming with Perl @import "/modules/aggregator/aggregator.css";@import "/modules/book/book.css";@import "/modules/node/node.css";@import "/modules/poll/poll.css";@import "/modules/system/defaults.css";@import "/modules/system/system.css";@import "/modules/user/user.css";@import "/sites/linuxjournal.com/modules/cck/content.css";@import "/sites/linuxjournal.com/modules/cck/fieldgroup.css";@import "/sites/linuxjournal.com/modules/diggthis/diggthis.css";@import "/sites/linuxjournal.com/modules/fivestar/css/fivestar.css";@import "/files/linuxjournal.com/ufiles/fivestar/outline/outline.css";@import "/modules/comment/comment.css";@import "/sites/linuxjournal.com/themes/linuxjournal/style.css"; Drupal.extend({ settings: { "fivestar": { "titleUser": "Your rating: ", "titleAverage": "Average: ", "feedbackSavingVote": "Saving your vote...", "feedbackVoteSaved": "Your vote has been saved.", "feedbackDeletingVote": "Deleting your vote...", "feedbackVoteDeleted": "Your vote has been deleted." } } }); _uacct = "UA-1117794-1"; urchinTracker();_qacct="p-a3K3N6enFe9wA";quantserve();Quantcast

HomeTopicsAudio/VideoCommunityEducationEmbeddedHardwareHOWTOsInternationalReviewsSecuritySoftwareSysAdminWebmasterNewsletterCommunity ResourcesWhat Is Linux?How to Get LinuxSupported HardwareSoftwareGetting HelpIndustry EventsForumsShopMagazineReadSubscribeRenewCustomer ServiceArchive CDFree IssueFAQMastheadWrite a LetterWrite for UsAdvertise Login Home Network Programming with Perl April 1st, 1999 by James Lee inSoftware Using Perl to make network task is easy—here's how. digg_url = 'http://www.linuxjournal.com/article/3237';digg_title = "Network Programming with Perl";digg_bodytext = "";digg_skin = 'standard'; Average: Select ratingCancel ratingPoorOkayGoodGreatAwesome Your rating: NonePerl has been called the glue that holdsthe Internet together because it is an extremely powerful textprocessing and CGI programming language. Although Perl was designedin the beginning to be a text manipulation language, it has evolvedinto a potent multi-purpose programming language. One area in whichPerl has shown its power is that of network programming.Perl makes network programming easy by providing built-infunctions that can be used to create low-level client/serverprograms from scratch. Also, many modules are freely available thatmake programming common networking tasks simple and quick. Thesetasks include pinging remote machines, TELNET and FTP sessions.This article presents examples of each of these types of networkprograms.IntroductionClient/server network programming requires a server runningon one machine to serve one or more clients running on either thesame machine or different machines. These different machines can belocated anywhere on the network.To create a server, simply perform the following steps usingthe built-in Perl function indicated:Create a socket withsocket.Bind the socket to a port address withbind.Listen to the socket at the port address withlisten.Accept client connections withaccept.Establishing a client is even easier:Create a socket withsocket.Connect (the socket) to the remote machine withconnect.Several other required functions and variables are defined inthe Socket.pm module. This moduleis probably already installed on your machine, but if not, it isavailable at the Comprehensive Perl Archive Network (CPAN), theofficial Perl source code repository (see Resources). To use thismodule in our programs, the following statement is required at thetop of the program:use Socket;This statement will locate the file Socket.pm and import allof its exported functions and variables.Viewing Module DocumentationAll examples in this article use modules that are availableat no cost from CPAN.Perl modules are usually self-documenting. If the author ofthe module follows the generally accepted rules of creating a Perlmodule, they will add Plain Old Documentation (POD) to the module's.pm file. One way to view the POD for the Socket module (assumingPerl and Socket.pm were installed correctly) is to execute thefollowing at the shell:perldoc SocketThis command displays Socket.pm's POD converted to a manpage. The output is a relatively thorough discussion of thefunctions and variables defined in this module.Another way to view the documentation is to convert the PODto text using:pod2text \/usr/lib/perl5/i686-linux/5.00404/Socket.pm | moreThe program pod2text isincluded in the Perl distribution, as are the programspod2html,pod2man,pod2usage andpod2latex.A Simple ServerListing 1.Our first programming example is a simple server running onone machine that can service only one client program at a timeconnecting from the same or a different machine. Recall that thesteps for creating a server were to create a socket, bind it to aport, listen at the port and accept client connections.Listing 1, server1.pl, is the source code for this simpleserver. First, it is generally a good idea to compile using Perl'sstrict rules:use strict;This requires all variables to be declared with themy function before they are used.Using my may be inconvenient, but it can catch many commonsyntactically correct yet logically incorrect programming bugs.The variable $port is assigned the firstcommand-line argument or port 7890 as the default. When choosing aport for your server, pick one that is unused on your machine. Notethat the only way to ensure you select a port that does not have apredefined use is to look at the appropriate RFC (seeResources).Next, the socket is created using the socket function. Asocket is like a file handle—it can be read from, written to orboth. The function setsockopt iscalled to ensure that the port will be immediately reusable.The sockaddr_in functionobtains a port on the server. The argumentINADDR_ANY chooses one of the server's virtualIP addresses. You could instead decide to bind only one of thevirtual IP addresses by replacing INADDR_ANYwithinet_aton("192.168.1.1")orgethostbyname("server.onsight.com")The bind function binds the socket to the port, i.e., plugs thesocket into that port. Then, the listen function causes the serverto begin listening at the port. The second argument to the listenfunction is the maximum queue length or the maximum number ofpending client connections. The value SOMAXCONNis the maximum queue length for the machine being used.Once the server begins listening at the port, it can acceptclient connections using the accept function. When the client isaccepted, a new socket is created named CLIENTwhich can be used like a file handle. Reading from the socket readsthe client's output and printing to the socket sends data to theclient.To read from a file handle or socket in Perl, wrap it inangle brackets (<FH>). To write to it,use the print function:print SOCKET;The return value of the accept function is the Internetaddress of the client in a packed format. The function sockaddr_intakes that format and returns the client's port number and theclient's numeric Internet address in a packed format. The packednumeric Internet address can be converted to a text stringrepresenting the numeric IP usinginet_ntoa (numeric to ASCII). Toconvert the packed numeric address to a host name, the functiongethostbyaddr is used.Let's assume all of the servers referred to in this articleare started on the machine named server.onsight.com. To start theserver on this machine, execute:[james@server networking]$ server1.plSERVER started on port 7890The server is now listening at port 7890 onserver.onsight.com, waiting for clients to connect.A Simple ClientListing 2.Listing 2, client1.pl, shows a simple client. The firstcommand-line argument to this program is the host name to which itshould connect, which defaults to server.onsight.com. The secondcommand-line argument is the port number which defaults to7890.The host name and the port number are used to generate theport address using inet_aton(ASCII to numeric) and sockaddr_in. A socket is then created usingsocket and the client connects the socket to the port address usingconnect.The while loop then reads the data theserver sends to the client until the end-of-file is reached,printing this input to STDOUT. Then the socket is closed.Let's assume all of the clients are started on the themachine named client.avue.com, although they could be executed fromany machine on the network. To execute the client, type:[james@client networking]$ client1.pl server.onsight.comHello from the server: Tue Oct 27 09:48:40 1998The following is the standard output from the server:got a connection from: client.avue.com [192.168.1.2]Perl Makes Life EasyCreating sockets using the functions described above is goodwhen you want to control how the socket is created, the protocol tobe used, etc. But using the functions above is too hard; I preferthe easy way—IO::Socket.The module IO::Socket provides an easy way to create socketswhich can then be used like file handles. If you don't have itinstalled on your machine, it can be found on CPAN. To see thismodule's POD, type:perldoc IO::SocketA Simple Server Using IO::SocketListing 3.Listing 3, serverIO.pl, is a simple server using IO::Socket.A new IO::Socket::INET object is created usingthe new method. Note that thearguments to the method include the host name, port number,protocol, queue length and an option indicating we want this portto be immediately reusable. The new method returns a socket that isassigned to $sock. This socket can be used likea file handle—we can either read the client output from it, orwrite to it by sending data to the client.A client connection is accepted using the accept method. Notethe accept method returns the client socket when evaluated inscalar context:$new_sock = $sock->accept()and returns the client's socket and the client's IP addresswhen evaluated in list context:($new_sock, $client_addr) = $sock->accept()The client address is computed and printed the same as in Listing1, server1.pl. Then the socket associated with that client is readuntil end-of-file. The data read is printed to STDOUT. This exampleillustrates that the server can read from a client using < >around the socket variable.A Simple Client Using IO::SocketListing 4.Listing 4, clientIO.pl, is a simple client usingIO::Socket. This time, a new object is createdthat connects to a host at a port using the TCP protocol. Tenstrings are then printed to that server, then the socket isclosed.If the server in Listing 3, serverIO.pl, is executed and thenthe client Listing 4, clientIO.pl, connects, the output wouldbe:[james@server networking]$ serverIO.plgot a connection from: client.avue.com [192.168.1.2]hello, world: 1hello, world: 2hello, world: 3hello, world: 4hello, world: 5hello, world: 6hello, world: 7hello, world: 8hello, world: 9hello, world: 10Bidirectional CommunicationIt is possible to create servers and clients that communicatewith one another in both directions. For instance, the client maysend information to the server, then the server may sendinformation back to the client. Therefore, network programs can bewritten so that the server and client follow some predeterminedprotocol.Listing 5.Listing 5, server2way.pl, shows how a simple server can becreated to read a command from a client, then print out anappropriate response to the client. The moduleSys::Hostname provides a functionnamed hostname that returns thehost name of the server. To insure output is seen as we print, IObuffering is turned off for the STDOUT file handle using theautoflush function. Then awhile loop is executed that accepts connections.When a client connects, the server reads a line from the client,chopping off the newline character. Then aswitch statement is executed. (Theswitch is cleverly disguised as aforeach loop, which happens to be one of myfavorite ways of writing a switch.) Depending onthe input entered by the client, the server outputs an appropriateresponse. All lines from the client are read untilend-of-file.Listing 6.Listing 6, client2way.pl, shows the companion client. Aconnection to the server is made, then the client prints a fewcommands to the server reads the response and prints the responseto STDOUT.The following is the output of the client code in Listing6:[james@client networking]$ client2way.plserver.onsight.comHiserver.onsight.comTue Oct 27 15:36:19 1998DEFAULTA Forking ClientIf you want to write a client that accepts commands fromSTDIN and sends them to the server, the easiest solution is towrite a client that forks a child. (A solution can be written usingselect that does not fork, but itis more complicated.) The client's parent process will read thecommands from the user through STDIN and print them to the server.The client's child process will then read from the server and printthe responses to STDOUT.Listing 7.Listing 7, clientfork.pl, is an example of a client thatforks.To fork in Perl, call the cleverly namedfork function. It returnsundef if the fork fails. If it succeeds, itreturns 0 to the child, non-zero (the child'spid) to the parent. In clientfork.pl, an ifstatement checks the value of $kid, the returnvalue from the fork. If $kid is true (non-zero,the child's pid), parent executes reading from STDIN printing tothe server. If $kid is false (zero), the childexecutes reading from the server printing to STDOUT.The following is the example session executing the clientcode in Listing 7, clientfork.pl connecting to the code in Listing5, server2way.pl:[james@client networking]$ clientfork.plserver.onsight.comNAMEserver.onsight.comDATETue Oct 27 15:42:58 1998HELPDEFAULTHELLOHiWhen the parent process is finished reading from STDIN, itexecutes the kill function to killthe child process. It is very important the parent reap its childso that the child does not outlive the parent and become a zombie.A Forking ServerListing 8.Servers usually don't handle only one client at a time. Oneapproach to a server that can handle more than one client is aserver that forks a child process to handle each client connection.Listing 8, serverfork.pl, is an example of a forking server.One way for the parent process to reap its children is todefine a subroutine and assign a reference to that subroutine to$SIG{CHLD}. (The hash %SIG isPerl's way of handling signals.) In this example, a subroutinenamed REAP is defined and areference to this subroutine is assigned to$SIG{CHLD}. When the parent receives theCHLD (child terminated) signal, the REAPsubroutine will be invoked.Within the while loop that accepts all theclient connections, the server forks. If the fork returns true, theparent is running and it executes the nextstatement which immediately transfers control to thecontinue block, performs the housecleaning stepof closing the child socket and waits for the next client toconnect. If the fork returns undef, then thefork failed, so the server dies. If the fork returns neither truenor undef, then the child is running, so theparent socket is closed and the child reads from the client andprocesses the client. When the child is finished processing theclient, the child exits and is reaped by the parent.Thread Programming in Perl5.005Perl version 5.005 supports thread programming. This means athreaded networking program can be created to be either a server ora client.Listings 9, 10, and 11 are three different versions of aclient that logs into several web servers and determines the typeof server being used (Apache, Netscape, etc).Listing 9.Listing 9, getservertype1.pl, shows a non-forking,non-threaded client. First, an array of hosts is created andinitialized to a few web sites. The subroutinedoit is defined to receive the webserver name as an argument, open a client connection to that serverat port 80 (the HTTP port), send the HTTP request and read eachline of response. When the line starting Server:is read, it will extract the server name and store it in$1. Then the host name and web server name areprinted. This subroutine is called for each host in the array ofhosts.Here is the output of getservertype1.pl:processing www.ssc.com...www.ssc.com: Stronghold/2.2 Apache/1.2.5 PHP/FI-2.0b12processing www.linuxjournal.com...www.linuxjournal.com: Stronghold/2.2 Apache/1.2.5 PHP/FI-2.0b12processing www.perl.com...www.perl.com: Apache/1.2.6 mod_perl/1.11processing www.perl.org...www.perl.org: Apache/1.2.5processing www.nytimes.com...www.nytimes.com: Netscape-Enterprise/2.01processing www.onsight.com...www.onsight.com: Netscape-Communications/1.12processing www.avue.com...www.avue.com: Netscape-Communications/1.12Note that the hosts are processed in the same order as storedin @hosts.Listing 10.Listing 10, getservertype2.pl, is a forking version ofgetservertype1.pl. The forking occurs within theforeach loop. The fork is executed and if itreturns true, the parent then executes the nextstatement to the next host name. If the fork returnsundef, then the program dies. Otherwise, thechild calls the doit function passing in the host, then exits.After the parent completes its work in the whileloop, it waits for all child processes to finish, thenexits.Here is the output of getservertype2.pl:processing www.ssc.com...processing www.linuxjournal.com...processing www.perl.com...processing www.perl.org...processing www.nytimes.com...processing www.onsight.com...processing www.avue.com...www.onsight.com: Netscape-Communications/1.12www.nytimes.com: Netscape-Enterprise/2.01www.avue.com: Netscape-Communications/1.12www.linuxjournal.com: Stronghold/2.2 Apache/1.2.5 PHP/FI-2.0b12www.perl.com: Apache/1.2.6 mod_perl/1.11www.ssc.com: Stronghold/2.2 Apache/1.2.5 PHP/FI-2.0b12www.perl.org: Apache/1.2.5Parent exiting...Note that the hosts are not printed in the order stored in@hosts. They are printed in the order processed,the slower hosts taking longer than the faster ones.Listing 11.Listing 11, getservertype3.pl, is a threaded version. In theloop through the host names, a new Thread objectis created. When creating the Thread, the newmethod is passed a reference to a subroutine that the thread willexecute, as well as the arguments passed into that subroutine. Thethread then executes its subroutine and when the subroutinereturns, the thread is destroyed. Here is the output ofgetservertype3.pl:processing www.ssc.com...processing www.linuxjournal.com...processing www.perl.com...processing www.perl.org...processing www.nytimes.com...processing www.onsight.com...processing www.avue.com...www.nytimes.com: Netscape-Enterprise/2.01www.onsight.com: Netscape-Communications/1.12www.avue.com: Netscape-Communications/1.12www.linuxjournal.com: Stronghold/2.2 Apache/1.2.5 PHP/FI-2.0b12www.perl.com: Apache/1.2.6 mod_perl/1.11www.ssc.com: Stronghold/2.2 Apache/1.2.5 PHP/FI-2.0b12www.perl.org: Apache/1.2.5Net::Ping ModuleListing 12.The Net::Ping module makespinging hosts easy. Listing 12, ping.pl, is a program similar to aprogram on my server that pings my ISP to keep my connection alive.First, a new Net::Ping object is created. Theprotocol chosen is tcp (the choices aretcp, udp andicmp; the default is udp).The second argument is the timeout (two seconds). Then an infiniteloop is executed, pinging the desired host. Theping() method returns true if the host responds,false otherwise, and an appropriate message is printed. Then theprogram sleeps ten seconds and pings again.An example output of Listing 12, ping.pl, is:Success: Wed Nov 4 14:47:58 1998Success: Wed Nov 4 14:48:08 1998Success: Wed Nov 4 14:48:18 1998Success: Wed Nov 4 14:48:28 1998Success: Wed Nov 4 14:48:38 1998Success: Wed Nov 4 14:48:48 1998Net::Telnet ModuleListing 13.The Net::Telnet module makesautomating TELNET sessions easy. Listing 13, telnet.pl, is anexample of connecting to a machine, sending a few system commandsand printing the result.First, a server and a user name are used. The user namedefaults to the user running the script by assigning to$user the value $ENV{USER}.(The hash %ENV contains all of the environmentvariables the script inherits from the shell.)Next, the password is requested, then read in. Note thatturning off the stty echoing is done through asystem call. It can also be doneusing the Term::ReadKeymodule.Then, a Net::Telnet object is created. Tolog in to the server using this object, thelogin method is called. Severalsystem commands are executed using thecmd method which returns theSTDOUT of the system command which is then printed. Note that partof that output is the system prompt, which is printed along withthe output of the command.Also note that the code$tn->cmd('/usr/bin/who') is evaluated in listcontext and stored in @who, which is an arraythat contains all the lines of ouptut of that command, one line ofoutput per array element.After all of the system commands are executed, the TELNETsession is closed.Here is an example output of Listing 13, telnet.pl:Enter password:Hostname: server.onsight.com[james@server james]Here's who:james tty1 Oct 24 21:07james ttyp1 Oct 27 20:59 (:0.0)james ttyp2 Oct 24 21:11 (:0.0)james ttyp6 Oct 28 07:16 (:0.0)james ttyp8 Oct 28 19:02 (:0.0)[james@server james]What is your command: dateThu Oct 29 14:39:57 EST 1998[james@server james]Net::FTP ModuleListing 14.The Net::FTP module makesautomating FTP sessions easy. Listing 14, ftp.pl, is an example ofconnecting and getting a file.A Net::FTP object is created, the login iscalled to log in to the machine, thecwd changes the working directoryand the get method gets the file.Then the session is terminated withquit.There are methods to do many common FTP operations:put,binary,rename,delete, etc. To see a list of allthe available methods, type:perldoc Net::FTPHere is an example output of Listing 14, ftp.pl:[james@k2 networking]$ ftp.pl server.onsight.comEnter your password:Before----------------------------------------/bin/ls: *.gz: No such file or directory----------------------------------------After----------------------------------------perl5.005_51.tar.gz----------------------------------------Archive a Web SiteUsing both Net::Telnet and Net::FTP, a very simple script canbe created that can archive a directory structure on a remotemachine.Listing 15.Listing 15, taritup.pl, is a Perl program that is similar toa program I use that logs in to my ISP and archives my website.The steps this program follows are:Start a session on the remote machine withTELNET.Go to the web page directory usingcd.Archive the directory usingtar.Start an FTP session to the remote machine.Change to the directory containing the tarfile.Get the tar file.Quit the FTP session.Back in the TELNET session, delete the tar file onthe remote machine.Close the TELNET session.This program outputs text to let the user know how the scriptis progressing.SummaryPerl is a powerful, easy-to-use programming language. Thatpower and ease of use includes network programming due to manybuilt-in functions and modules. Best of all, it's free.Resources James Lee is the president and founder of Onsight (http://www.onsight.com/). When he is not teaching Perl classes or writing Perl code on his Linux machine, he likes to spend time with his kids, root for the Northwestern Wildcats (it was a long season), and daydream about his next climbing trip. He also likes to receive e-mail at james@onsight.com.__________________________ hr {border: solid 1px #ccc}.small {font-size: .8em}Special Magazine Offer -- 2 Free Trial Issues!Receive 2 free trial issues of Linux Journal as well as instant online access to current and past issues. There's NO RISK and NO OBLIGATION to buy. CLICK HERE for offerLinux Journal: delivering readers the advice and inspiration they need to get the most out of their Linux systems since 1994.Sorry, offer available in the US only. International orders, click here. Add new commentPrinter-friendly versionDelicious DeliciousDigg DiggReddit RedditNewsvine NewsvineTechnorati Technorati

Comment viewing options

Flat list - collapsedFlat list - expandedThreaded list - collapsedThreaded list - expanded Date - newest firstDate - oldest first 10 comments per page30 comments per page50 comments per page70 comments per page90 comments per page150 comments per page200 comments per page250 comments per page300 comments per pageSelect your preferred way to display the comments and click "Save settings" to activate your changes. Odd accept() behavior On November 8th, 2007 Owen LaGarde (not verified) says: I noticed this when I converted Listings 6 (client) and 8 (server) to use EOLN delimited IO(to better examine the behavior of concurrent stream sessions). This was initially donebecause Listing 8 did not wait for new sessions after the first was closed. After the 1stclient exited accept() would return undef until another request was queued but didn't blockwhile waiting for the queue event. Eventually I just wrapped the outer while() in another"while( ; sleep 2)" to give myself time to check the socket queue and matchincoming requests to accept() results. This revealed yet more oddities. Note that the'Listen' parameter is set to SOMAXCONN (128 for my RHEL box and perl 5.8.5) for both formsof new() socket operators. Any ideas on the following 3 oddities?- Using IO::Socket::INET sockets -- the third concurrent session request hangs unprocesseduntil one of the previous [still open] sessions exit, ie., when more than 2 open sessionsexist accept() blocks until there is only 1 open session, then processes the next waitingrequest as expected.- Using IO::Socket::UNIX sockets -- many concurrent sessions can be opened but once any ofthese are closed accept() hangs until all other sessions are closed, ie., if open sessionsexist and one is closed accept() blocks until all are closed, then processes request(s) --but not as expected, see bullet 3 below.- Using either form of sockets -- prior to opening any sessions accept() blocks, waits forrequests to queue, and processes the first queued request as expected, but subsequent callsto accept() return undef unless another request is queued, ie., accept() behaves as if theO_NONBLOCK bit is being automatically set on the original socket at or after the first call.##################################################### The Client####################################################!/usr/bin/perl -wuse strict;use IO::Socket;#use Carp;#use Data::Dumper;# Domain socketsmy $sock = new IO::Socket::UNIX( Peer => '/tmp/mysock', Type => SOCK_STREAM ) or die $!;## IP sockets#my $sock = new IO::Socket::INET( PeerAddr => 'localhost', PeerPort => '7890',# Proto => 'tcp'); $sock or die "no socket :$!";my $buf;while( $buf = <> ) { chomp $buf; print $sock "$buf\n"; print "$0 ($$): ", scalar localtime(), " sent: [$buf]\n"; $buf = scalar <$sock>; chomp $buf; print "$0 ($$): ", scalar localtime(), " received: [$buf]\n";}close $sock;##################################################### The server####################################################!/usr/bin/perl -wuse strict;use IO::Socket;use POSIX qw(:sys_wait_h);#use Carp;#use Data::Dumper;sub REAP { 1 until( -1 == waitpid( -1, WNOHANG ) ); $SIG{CHLD} = \&REAP;}$SIG{CHLD} = \&REAP;# Domain socketsunlink '/tmp/mysock';my $sock = new IO::Socket::UNIX( Local => '/tmp/mysock', Type => SOCK_STREAM, Listen => SOMAXCONN, Reuse => 1 ) or die $!;## IP sockets#my $sock = new IO::Socket::INET( LocalHost => 'localhost', LocalPort => 7890,# Proto => 'tcp', Listen => SOMAXCONN, Reuse => 1) or die $!;STDOUT->autoflush(1);my( $new_sock, $child, $buf );while( 1 ) { while( $new_sock = $sock->accept() ) { if( $child = fork ) { close $new_sock } elsif( defined( $child ) ) { close $sock; while( defined( $buf = <$new_sock> ) ) { chomp $buf; print "$0 ($$): ", scalar localtime(), " received: [$buf]\n"; sleep 1; print "$0 ($$): ", scalar localtime(), " sending: [$buf]\n"; print $new_sock "$buf\n"; } exit } else { die "$0 ($$): fork: $!" } } sleep 2}##################################################### END################################################### replyPrinter-friendly version Re: odd accept() behavior On November 8th, 2007 Owen LaGarde (not verified) says: BTY: no, it isn't the "while( defined( $buf = <$new_sock> ) )..." at line 32 of the server, where the child proc reads the copied socket. Yes, changing this to an if() will remove the behavior -- by enforcing line-only processing of the socket contents -- but this doesn't explain why the behavior only occurs when sessions=3 for IP sockets or when the first child exit occurs for Domain sockets. replyPrinter-friendly version clientfork.pl is not working on XP On October 25th, 2007 lakshmi (not verified) says: hi there, I'm trying to execute client fork.pl on my xp machine with both client and server running on the same machine but it doesn't seem to be working. when i enter input at client, it simply accepts the input and then nothing happens.Can anybody help me with this.Thanks in advance,lakshmi. replyPrinter-friendly version Sending binay data to the server On June 28th, 2007 Anonymous (not verified) says: Can the print statement be used to send binary data to the server? For example: to send the message to the server, you would have a statement PRINT $client $message. If $message = 0xFF ;what would be sent to the server? Is it the ASCII representation of the number 255? How can I send the 8-bit binary representation of the numner 255 and not one byte for 2, one byte for 5, and another byte for 5 ? Any help would be appreciated.Thanks. replyPrinter-friendly version Minor correction to server1.pl example On March 29th, 2007 Allan (not verified) says: There is a minor error at the end of the server1.pl example:# send them a message, close connection print CLIENT "Hello from the server: ", close CLIENT;As stated, there is a write to closed socket error and no message passed to the client. One fix is to replace the "," with ";" on the print line. replyPrinter-friendly version Another fix On April 30th, 2007 RyDer (not verified) says: Another fix is to put this on the end of the line:print CLIENT "Hello from the server: ", scalar localtime, "\n";because on the response of the server to the client shows a time stamp.Be care. replyPrinter-friendly version Another fix On April 30th, 2007 RyDer (not verified) says: Another fix is to put this on the end of the line:print CLIENT "Hello from the server: ", scalar localtime, "\n";because on the response of the server to the client shows a time stamp.Be care. replyPrinter-friendly version A very good example set for On February 22nd, 2007 Shilpa (not verified) says: A very good example set for beginners. I am interested in knowing more about how I could use perl and start a program as server and which takes an input text from client and processes it and returns the result to client. Something using VEC and SELECT per commanda. I am woring on this code I have which uses all this. If you have any examples for that please let me know.Thanks, replyPrinter-friendly version Absolute Good thing.. Thanks On December 6th, 2006 Anonymous (not verified) says: Absolute Good thing.. Thanks for all the info presented. replyPrinter-friendly version Fork vs Thread On August 9th, 2006 lintastic (not verified) says: This tutorial was excelent. It was clear, concise, and informative. Although, I did have one question. What are the bennefits of using fork over thread? In most cases I know that creating a thread has most of the same bennefits of using fork but without the extra overhead. Why would one want to use fork in a web server as opposed to thread? Thanks! replyPrinter-friendly version Fantastic On May 19th, 2006 jayanthi (not verified) says: I really got interested in learning network programming after looking in to this article. It is really great on you. Can you suggest us the sites used for learning in depth of network programming with the real time examples replyPrinter-friendly version great help On April 19th, 2006 jatin patni (not verified) says: Hi, i have been looking around lately for some networking related tutorials and i admit that this place is actually exactly what i was looking for.Thanks.PS: Beginner in perl. replyPrinter-friendly version Re: Strictly On-Line: Network Programming with Perl On September 20th, 2004 Anonymous says: Hi James,I'm very new to PERL. I want to know about socket programming in PERL. I have to make chat module in my site. where is any user want to chat with somebody then he/se can be able to send alert message to that perticular user. if he/she accept the request then new chat window should open both side without any page refreshment.I hope your guidance will be important for me.regards,Bharat replyPrinter-friendly version Re: Strictly On-Line: Network Programming with Perl On June 11th, 2004 Anonymous says: a good guide to the world of the networks! replyPrinter-friendly version Re: Strictly On-Line: Network Programming with Perl On April 3rd, 2004 Anonymous says: I was really in big trouble with perl' sockets programming, this tutorial was proved to be a big help for me to get stated writing programs that use sockets in perl.....thnx for such a nice tutorial... replyPrinter-friendly version Re: Strictly On-Line: Network Programming with Perl On November 15th, 2002 Anonymous says: Great article, most of it worked on my FBSD server to.Thanks alot, keep up the good work. - Stian replyPrinter-friendly version Re: Strictly On-Line: Network Programming with Perl On February 24th, 2002 Anonymous says: Hi James, A very informative site. Also very elegantly written. Easy to understand and implement. Was a big help to me.Thanks a bunch.Cheers, Arun Krishnan replyPrinter-friendly version HI On July 28th, 2005 Anonymous (not verified) says: Yes really ArunI'm very new to this Socket programming in perlPlease let me know , if you are familiar with this Thanks and regardsJey replyPrinter-friendly version good job On August 9th, 2006 kararu (not verified) says: Keep up the good job of showing a wonderful way to perl network programming beginners. replyPrinter-friendly version Hey! This one's simply too On September 7th, 2007 Shraddha (not verified) says: Hey!This one's simply too good...was yearning for something on networking concepts...couldn ask better than this one.Lets keep the good work coming!Best Regards,Shraddha replyPrinter-friendly version Subscribe now! SubscribeRenewFree IssueCustomer service The Latest Rebooting the Magic WayAug-21-08 Product Spotlight: Virtualization for High-End ComputingAug-21-08 Remote Application Deployment with NXAug-20-08 Google Drops $300,000 on Open SourceAug-20-08 It's Sir Penguin, and Where's My Fish?Aug-20-08 Use Nagios to Check Your ZypperAug-20-08 more Featured Videos Remote Application Deployment with NX The X Window System is a magnificent platform for many uses, but using it to run an application over a slow network is nearly impossible. This is an introduction to NX, a technology that makes remote applications fly even over commodity internet. Add new commentRead moreRate Review: Flip Video Ultra Linux Journal Gadget Guy, Shawn Powers, reviews the Flip Video Ultra, a small portable video camera, and shows us how easy it is to edit the video with Kino.Thanks to our sponsor: Silicon Mechanics 3 commentsRead moreRate p.videofoot {text-align: right; padding-bottom:0; margin-bottom:0;}See more Linux Journal Videos Recently Popular Rebooting the Magic Way4.833335 Rebooting the Magic Way4.833335 Rebooting the Magic Way4.833335 The DNS Bug: Why You Should Care5 The BeagleBoard: $149 Linux System5 Generating Native Excel Files in Perl5 more From the Magazine September 2008, #173 Feeling a bit like a Thermian? Never give up, never surrender! Someday, you could go from underdog to top dog. Just take a look at a few of the underdogs we highlight in this issue: Mutt, djbdns, Nginix, Gentoo, Xara and the program voted mostly likely to fail just a few years back—Firefox. If Firefox not radical enough for you, check out Chef Marcel's column for some more alternatives. Having trouble mapping your program data to your relational database? If so, Rueven Lerner shows you some tricks in his At The Forge column. Need to run GUI applications on your server in the next state? In his Paranoid Penguin column, Mick Bauer shows you how to do it securely. Kyle Rankin keeps hacking and slashing and shows you a few split screen secrets you may not be familiar with. Finally, we all know what happens next February, but only Doc knows what happens afterward. Read this issue Contribute to the Linux Journal Flickr PoolFollow Linux Journal on TwitterAdd Linux Journal to your RSS readerMeet other readers on FacebookGet Linux Journal Miis SubscribeAdvertiseContact usPrivacy statementReport problemsRSS Feeds Copyright © 1994 - 2008 Linux Journal. All rights reserved.
 

Using

Perl

to

perform

networking

tasks

is

easy.

An

article

by

James

Lee.

(April

1,

1999)

http://www.linuxjournal.com/article/3237

Strictly On-Line: Network Programming with Perl 2008 August

dvd rental

dvd


Using Perl to perform networking tasks is easy. An article by James Lee. (April 1, 1999)

Rules




© 2008 Internet Explorer 5+ or Netscape 6+

Recommended Sites: 1. Arts - Business - Computers - Games - Health - Home - Kids and Teens - News - Recreation - Reference - Regional - Science - Shopping - Society - Sports - World Miss Gallery - Top Anime Hentai - DVD rental by mail - Personal Loans - Debt Management - Mortgage - Pay Day Loans - Loans
2008-08-21 17:59:45

Copyright 2005, 2006 by Webmaster
Websites is cool :) 267Kasy Fiskalne Warszawa - Hotel Hamburg - Baby Gifts - Art. Biurowe,multimedia - Hotel Istanbul