Home > Articles > Web Development > Perl

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Three Example Perl Programs That Use Sockets

The following examples use the socket functions and network protocols explained previously. Basic knowledge of Perl is required. The utilities are portable and can be used on Windows as well as the UNIX platform from the command line. These utilities should not be run in a production environment or on a machine that contains critical data, critical information, or critical systems because they do not contain error and security checks. The sole purpose of the examples here is to explain the usage of sockets in network systems.

Email Utility Using the SMTP Protocol

Objective: To be able to send email from the command line.

The client email utility works by first sending the message along with the receiver information to the SMTP server. The connection then is closed, and this message is picked up from the SMTP server by a POP3 client at the receiver's end.

The following are the generic steps to be kept in mind while coding the utility:

  1. Find out the SMTP server hostname or address. Use this as the last argument when invoking the utility.

  2. Create a client SMTP socket on your end through which you will carry on our conversation with the SMTP server.

  3. Now try to establish a connection with the SMTP server.

  4. After the connection is accepted, you need to begin sending the mail information to the server.

  5. According to the SMTP protocol, you first identify yourself by sending a "HELO Client Name," then sender information, then receiver information, and then the message to appear at the receiver's end.

  6. Tell the server you are finished.

  7. Close the connection.

The utility in Listing 1 can be used on Windows as well as UNIX.

Listing 1: Email Utility Using SMTP

#!/usr/bin/perl

# Author: Prashant V. Khergaonkar
# Usage: mailx "Subject" "Receiver Addresses" "Message File Name" 
# "Sender Address" "SMTP Server"

use Socket;

# address of person/s you want to send mail to
$mailTo     = $ARGV[1];                    

# address of the Mail server
$mailServer = $ARGV[4] || 'mailhost';               
# e-mail address of the sender
$mailFrom  = $ARGV[3] || 'Prashant.Khergaonkar@bbh .com'; 
# subject of the mail
$subject    = $ARGV[0] || "Test";

$body      = $ARGV[2] || "Testing - Please disregard e-mail. [ccc]
\r\n"; # e-mail message

# getprotobyname is the function used to get the number representing 
# TCP, If function fails use 6  
$proto   = getprotobyname("tcp")    || 6;            

# getservbyname is the function used to get the number representing 
# SMTP, If function fails use 25
$port    = getservbyname("smtp", "tcp") || 25;

# gethostbyname is the function used to get the ip address using 
# the host name
$serverAddr = gethostbyname($mailServer) || print [ccc]
"gethostbyname error: $! \n";

# create the Client Socket s_SMTP which will be used to talk to 
# the SMTP server
socket(s_SMTP,AF_INET,SOCK_STREAM,$proto) || die("socket error : [ccc]
$! \n");

# pack format meaning : <unsigned short><short in network order> 
# <null padded 4 char string><8 null bytes>
# check the operating system and assign the pack format accordingly
if ( $^O =~ /Win/ )
{ 
  $packFormat = 'S n a4 x8';  # Windows 95, SunOs 4.1+ : 
}
if ( $^O =~ /solaris/ )
{
  $packFormat = 'S n c4 x8';  # SunOs 5.4+ (Solaris 2)
}

# pack function packs the SMTP Server information according to format 
# specified as explained above.
$s_server = pack($packFormat,AF_INET,$port,$serverAddr);

# connect to the SMTP Mail Server
connect(s_SMTP,$s_server) || die("connect error: $! \n");

# wait to receive an OK signal from the SMTP Server that it has accepted our connection.
# and that we can begin actual information transfer
recv(s_SMTP,$inpbuf,1000,0);
print "$inpbuf \n";

# Each message block ends with \r\n or \n to indicate to server we
# have finished sending.

# send 'HELO' to the server - this is required to indicate we
# are ready to begin. 
send(s_SMTP,"HELO xyz.com \r\n",0);
# receive the server response
recv(s_SMTP,$inpbuf,1000,0);
print "$inpbuf \n";

# send the e-mail address of the sender(yours) to the server -- 
# end with end-of -line
send(s_SMTP,"MAIL From: \r\n",0);
# receive the server response
recv(s_SMTP,$inpbuf,1000,0);
print "$inpbuf \n";

# use the split function to separate multiple receiver e-mail addresses
# if not multiple no difference.
@mT = split(' ',$mailTo);
foreach $mTo (@mT)
{
 # send the e-mail address of the receiver to the server
 send(s_SMTP,"RCPT To: \r\n",0);
 # receive the server response
 recv(s_SMTP,$inpbuf,1000,0);
 print "$inpbuf \n";
}

# by sending 'DATA' to the server we indicate that we are ready to 
# begin sending the e-mail details and message that should appear at
# the receiver.
send(s_SMTP,"DATA \r\n",0);
# receive the server response
recv(s_SMTP,$inpbuf,1000,0);
print "$inpbuf \n";

##########################################
# Will appear in the To text box when the receiver sees mesg
send(s_SMTP,"To: $mailTo \r\n", 0);       

# Will appear in the From text box when the receiver sees mesg
send(s_SMTP,"From: $mailFrom \r\n", 0);   

# Will appear in the Subject text box when he receiver sees mesg
send(s_SMTP,"Subject: $subject \r\n", 0);   


# open the file which contains the message to be sent in mail.
open(f1,"$body");
while ( $i = <f1> )  # read file a line at a time
{
# send the file contents line by line
 send(s_SMTP,"$i", 0);
}

##########################################

# To indicate the end of e-mail send a full-stop on a new line 
# followed by a new line.
send(s_SMTP,"\r\n .\r\n", 0);
# receive server response 
recv(s_SMTP,$inpbuf,1000,0);
print "$inpbuf \n";

# send QUIT to the server to indicate we are done and have no more 
# messages to send
# and that the server can close the connection.
send(s_SMTP,"QUIT \r\n",0);
# receive server response
recv(s_SMTP,$inpbuf,1000,0);
print "$inpbuf \n";

# close our side of the connection 
shutdown(s_SMTP,2) || print "shutdown error: $! \n";

# close(s_SMTP) || print "close error: $! \n";

# close the disk file which contains the message sent over.
close(f1);

exit 0;

Simple Web Client Using the HTTP protocol

Objective: To request and receive a Web page from a site (Web server) the Internet.

The Web client works by establishing a connection with the Web site HTTP Web server. The request for the file is sent along with the client information to the Web site HTTP Web server. The file sent by the HTTP Web server then is received, and the connection is closed.

The following are the generic steps to be kept in mind while coding the utility:

  1. Find out the site name or HTTP Web server hostname or IP address. Use this as the first argument when invoking the utility.

  2. Create a client HTTP socket on your end through which you will carry on your conversation with the Web site HTTP server.

  3. Now try to establish a connection with the HTTP server.

  4. After your connection is accepted, you need to begin your conversation with the server.

  5. According to the HTTP protocol, you use GET <path>/filename to request the file.

  6. Start receiving the file bytes sent by the server, and store them in a temporary file on your machine.

  7. After the file has been received, close your connection.

The utility in Listing 2 can be used on Windows as well as UNIX.

Listing 2: Simple Web Client Using HTTP

#!/usr/bin/perl

# Author : Prashant V. Khergaonkar
# Usage : webclient.pl "Site Address"

#require 5.002;
use Socket;

# site address to connect to.
$remote    = $ARGV[0] || 'execonn.com';            


# getprotobyname is the function used to get the number representing 
# TCP, if function fails use 6

$proto     = getprotobyname("tcp")    || 6;   

# getservbyname is the function used to get the number representing 
# HTTP, if function fails use 80
$port      = getservbyname("http", "tcp") || 80;

# gethostbyname is the function used to get the ip address using 
# the host name
$serverAddr   = gethostbyname($remote) || print [ccc]
"gethostbyname error: $! \n";

# create the Client Socket s_CLIENT which we will use to connect 
# to the HTTP server
socket(s_CLIENT,AF_INET,SOCK_STREAM,$proto) || [ccc]
die("socket error : $! \n");

# pack format meaning : <unsigned short><short in network order> 
# <null padded 4 char string><8 null bytes>
#check the operating system and assign the pack format accordingly
if ( $^O =~ /Win/ )
{ 
  $packFormat = 'S n a4 x8';  # Windows 95, SunOs 4.1+
}
if ( $^O =~ /solaris/ )
{
  $packFormat = 'S n c4 x8';  # SunOs 5.4+ (Solaris 2)
}

# pack function packs the HTTP Server information according to 
# format specified
# as explained above.
$s_server = pack($packFormat,AF_INET,$port,$serverAddr) || [ccc]
die("pack error : $! \n");

# connect to the HTTP Web Server
connect(s_CLIENT,$s_server) || die("connect error: $! \n");

# the request that we are going to send to the server :
# here we request the server to send us the index.html file
# by default most of the sites send this file when we connect to
# them. Ex. http://www.sitename.com can be interpreted as 
# http://www.sitename.com/index.html
$reqt="GET /index.html \r\n HTTP 1.0 \r\n\r\n";

# send the above request to the HTTP server
send(s_CLIENT,$reqt,0) || print "send error: $! \n";

# Save the file sent over by the server in this file called 
# say temp.htm. 
# The file temp.htm should be viewed using a browser
# it is the file that is requested by our client from the server.
open ( f1,">temp.htm");

# recdt will contain the incoming parts of file requested by us 
# being sent over by the HTTP server 
# set recdt to a default value to get inside the loop, when the 
# server is done sending over the file, recdt will be empty and 
# the while loop terminates. 
$recdt=1;
while ( $recdt )
{
  print "in \n";
  recv(s_CLIENT,$recdt,100,0);
  print "if receive error: $! \n";
# write data received to disk file.
  print f1 "$recdt";
  print "$recdt";
}

# close our side of the connection 
shutdown(s_CLIENT,2) || print "shutdown error: $! \n";

#close(s_CLIENT) || print "close error: $! \n;

#close the file which contains data sent over by server
close(f1);

exit 0;

Simple Web Server Using the HTTP Protocol

Objective: To listen for and receive clients file requests, and to send the file to the client on the Internet.

The Web server works by listening for a client request, accepting the client request, sending the file requested by the client, and listening for the next request.

The following are the generic steps to be kept in mind while coding the utility:

  1. Create a server HTTP socket, and bind it to a port (80) on your machine.

  2. Listen for client file requests.

  3. Accept the client file request by creating and assigning a temporary socket to identify the client.

  4. If the file requested by the client exists, send it using the temporary socket created specifically for that client.

  5. Close the temporary socket.

  6. Listen for the next client request.

The utility in Listing 3 can be used on Windows as well as UNIX.

Listing 3: Simple Web Server Using HTTP

#!/usr/bin/perl

# Author : Prashant V. Khergaonkar
# Usage : webserver.pl

use Socket;

$buffer   = ' ';

# getprotobyname is the function used to get the number representing 
# TCP, if function fails use 6

$proto   = getprotobyname("tcp")     || 6;

# getservbyname is the function used to get the number representing 
# HTTP, if function fails use 80

$port    = getservbyname("http", "tcp") || 80;
$serverAddr = INADDR_ANY;  

# Create the HTTP Server Socket which we will use to handle HTTP 
# Client requests on.
socket(s_HTTP,AF_INET,SOCK_STREAM,$proto) || die("socket error : $! \n");

# pack format meaning : <unsigned short><short in network order> 
# <null padded 4 char string><8 null bytes>
# check the operating system and assign the pack format 
# accordingly
if ( $^O =~ /Win/ )
{ 
  $packFormat = 'S n a4 x8';  # Windows 95, SunOs 4.1+ : 
}
if ( $^O =~ /solaris/ )
{
  $packFormat = 'S n c4 x8';  # SunOs 5.4+ (Solaris 2)
}

# pack function packs the HTTP Server information according to format 
# specified as explained above.
$s_server = pack($packFormat,AF_INET,$port,$serverAddr);

# Associate the port number to the socket on which it will listen 
# for client requests
# also value of serverAddr as defined above and part of 
# the packed information
# indicates that any Client can try to establish a connection 
# to the server.
bind(s_HTTP,$s_server) || die("bind error: $! \n");

# Here we specify the 3 client requests will be allowed simultaneously 
# and queued for service
listen(s_HTTP,3) || die("listen error: $! \n"); 

# Here our server will be able to service clients one after 
# another i.e when one client is being serviced the others 
# will be queued (max two clients will be queued as# specified above in listen). 


$NoClient = 0;
# begin infinite loop
while ( 1 )
{

# Wait for and accept a Client connection request and create a socket 
# descriptor s_CLIENT for the client
accept(s_CLIENT,s_HTTP) || print "accept error: $! \n";

$NoClient= $NoClient + 1;

# After a client connection is accepted, wait for and receive the 
# request from the client 
recv(s_CLIENT,$buffer,1000,0);
print "recv1 error: $! \n";
print "1 -- $buffer \r\n";

# A check to see if the client request is valid can be added here.
# ex. If the requested file is a valid file on our system.

# if the Client request is valid send the following header to the 
# client to indicate to the client
# that its request is valid and it should be ready to receive its 
# requested information.
$header = "HTTP/1.0 200 OK \r\n Content-Length: 1000 \r\n [ccc]
Content-Type: text/html \r\n\r\n";
send(s_CLIENT,$header,0);
print "if send1 error: $! \n";

$body = " <html>You are connected</html> \r\n";
send(s_CLIENT,$body,0);
print "if send2 error: $! \n";

# Depending on the server operating system, the path to the file 
# requested by client changes .
# Here I have hard coded the file path, it should be changed 
# accordingly.
# If the client request consists of only a "/" then we send over the 
# default index.html file.
# If the client request consists of a path to the file, we append this 
# path to our default path.
if ( $^O =~ /Win/ )
{
   # default home directory where our files are stored 
   # on the windows server.
   $filename = 'c:\perl\bat'; 

  @request = split(/\r\n/,$buffer);  
  @req = split(/ /,$request[0]);  

  if ($req[1] eq "/" )
  {
    $filename = "$filename\\index.html";
    #$filename = join("",$filename,'\index.html');
    print "$filename \n";
  }
  else
  {
   $filename = "$filename$req[1]";
   $filename =~ s/\//\\/;
   print "$filename \n";
 }  
}

if ( $^O =~ /solaris/ )
{
   # default home directory where our files 
   # are stored on the unix server.
   $filename = '/home/perl/bat/'  
@request = split(/\n/,$buffer);
  @req = split(/ /,$request[0]);

  if ($req[1] eq "/" )
  {
    $filename = "$filename/index.html";
    #$filename = join("",$filename,'index.html');
    print "$filename \n";
  }
  else
  {
   $filename = "$filename$req[1]";
   print "$filename \n";
 }
}

$body = $filename;

# open the file requested by client 
open(f1,"$body");

# send over the file to the Client.
while ( $i = <f1> )
{
 send(s_CLIENT,"$i", 0);
}

# close the disk file whose contents have been sent over
close(f1);

# close the temporary socket descriptor after servicing the 
# client request. 
shutdown(s_CLIENT,2) || print "shutdown error: $! \n";
#close(s_CLIENT) || print "close error: $! \n";

}

# close our side of the connection 
shutdown(s_HTTP,2) || print " server shutdown error: $! \n";

exit 0;
  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020