Install Perl 5.8.8
[msysgit.git] / mingw / html / pod / perlfaq9.html
blob28fa3f9020695e6ee9c0a2af8d7eb53785e706fa
1 <?xml version="1.0" ?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml">
4 <head>
5 <title>perlfaq9 - Networking</title>
6 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
7 <link rev="made" href="mailto:" />
8 </head>
10 <body style="background-color: white">
11 <table border="0" width="100%" cellspacing="0" cellpadding="3">
12 <tr><td class="block" style="background-color: #cccccc" valign="middle">
13 <big><strong><span class="block">&nbsp;perlfaq9 - Networking</span></strong></big>
14 </td></tr>
15 </table>
17 <p><a name="__index__"></a></p>
18 <!-- INDEX BEGIN -->
20 <ul>
22 <li><a href="#name">NAME</a></li>
23 <li><a href="#description">DESCRIPTION</a></li>
24 <ul>
26 <li><a href="#what_is_the_correct_form_of_response_from_a_cgi_script">What is the correct form of response from a CGI script?</a></li>
27 <li><a href="#my_cgi_script_runs_from_the_command_line_but_not_the_browser___500_server_error_">My CGI script runs from the command line but not the browser. (500 Server Error)</a></li>
28 <li><a href="#how_can_i_get_better_error_messages_from_a_cgi_program">How can I get better error messages from a CGI program?</a></li>
29 <li><a href="#how_do_i_remove_html_from_a_string">How do I remove HTML from a string?</a></li>
30 <li><a href="#how_do_i_extract_urls">How do I extract URLs?</a></li>
31 <li><a href="#how_do_i_download_a_file_from_the_user_s_machine_how_do_i_open_a_file_on_another_machine">How do I download a file from the user's machine? How do I open a file on another machine?</a></li>
32 <li><a href="#how_do_i_make_a_popup_menu_in_html">How do I make a pop-up menu in HTML?</a></li>
33 <li><a href="#how_do_i_fetch_an_html_file">How do I fetch an HTML file?</a></li>
34 <li><a href="#how_do_i_automate_an_html_form_submission">How do I automate an HTML form submission?</a></li>
35 <li><a href="#how_do_i_decode_or_create_those__encodings_on_the_web">How do I decode or create those %-encodings on the web?</a></li>
36 <li><a href="#how_do_i_redirect_to_another_page">How do I redirect to another page?</a></li>
37 <li><a href="#how_do_i_put_a_password_on_my_web_pages">How do I put a password on my web pages?</a></li>
38 <li><a href="#how_do_i_edit_my__htpasswd_and__htgroup_files_with_perl">How do I edit my .htpasswd and .htgroup files with Perl?</a></li>
39 <li><a href="#how_do_i_make_sure_users_can_t_enter_values_into_a_form_that_cause_my_cgi_script_to_do_bad_things">How do I make sure users can't enter values into a form that cause my CGI script to do bad things?</a></li>
40 <li><a href="#how_do_i_parse_a_mail_header">How do I parse a mail header?</a></li>
41 <li><a href="#how_do_i_decode_a_cgi_form">How do I decode a CGI form?</a></li>
42 <li><a href="#how_do_i_check_a_valid_mail_address">How do I check a valid mail address?</a></li>
43 <li><a href="#how_do_i_decode_a_mime_base64_string">How do I decode a MIME/BASE64 string?</a></li>
44 <li><a href="#how_do_i_return_the_user_s_mail_address">How do I return the user's mail address?</a></li>
45 <li><a href="#how_do_i_send_mail">How do I send mail?</a></li>
46 <li><a href="#how_do_i_use_mime_to_make_an_attachment_to_a_mail_message">How do I use MIME to make an attachment to a mail message?</a></li>
47 <li><a href="#how_do_i_read_mail">How do I read mail?</a></li>
48 <li><a href="#how_do_i_find_out_my_hostname__domainname__or_ip_address">How do I find out my hostname, domainname, or IP address?</a></li>
49 <li><a href="#how_do_i_fetch_a_news_article_or_the_active_newsgroups">How do I fetch a news article or the active newsgroups?</a></li>
50 <li><a href="#how_do_i_fetch_put_an_ftp_file">How do I fetch/put an FTP file?</a></li>
51 <li><a href="#how_can_i_do_rpc_in_perl">How can I do RPC in Perl?</a></li>
52 </ul>
54 <li><a href="#author_and_copyright">AUTHOR AND COPYRIGHT</a></li>
55 </ul>
56 <!-- INDEX END -->
58 <hr />
59 <p>
60 </p>
61 <h1><a name="name">NAME</a></h1>
62 <p>perlfaq9 - Networking ($Revision: 1.28 $, $Date: 2005/12/31 00:54:37 $)</p>
63 <p>
64 </p>
65 <hr />
66 <h1><a name="description">DESCRIPTION</a></h1>
67 <p>This section deals with questions related to networking, the internet,
68 and a few on the web.</p>
69 <p>
70 </p>
71 <h2><a name="what_is_the_correct_form_of_response_from_a_cgi_script">What is the correct form of response from a CGI script?</a></h2>
72 <p>(Alan Flavell &lt;<a href="mailto:flavell+www@a5.ph.gla.ac.uk">flavell+www@a5.ph.gla.ac.uk</a>&gt; answers...)</p>
73 <p>The Common Gateway Interface (CGI) specifies a software interface between
74 a program (``CGI script'') and a web server (HTTPD). It is not specific
75 to Perl, and has its own FAQs and tutorials, and usenet group,
76 comp.infosystems.www.authoring.cgi</p>
77 <p>The CGI specification is outlined in an informational RFC:
78 <a href="http://www.ietf.org/rfc/rfc3875">http://www.ietf.org/rfc/rfc3875</a></p>
79 <p>Other relevant documentation listed in: <a href="http://www.perl.org/CGI_MetaFAQ.html">http://www.perl.org/CGI_MetaFAQ.html</a></p>
80 <p>These Perl FAQs very selectively cover some CGI issues. However, Perl
81 programmers are strongly advised to use the CGI.pm module, to take care
82 of the details for them.</p>
83 <p>The similarity between CGI response headers (defined in the CGI
84 specification) and HTTP response headers (defined in the HTTP
85 specification, RFC2616) is intentional, but can sometimes be confusing.</p>
86 <p>The CGI specification defines two kinds of script: the ``Parsed Header''
87 script, and the ``Non Parsed Header'' (NPH) script. Check your server
88 documentation to see what it supports. ``Parsed Header'' scripts are
89 simpler in various respects. The CGI specification allows any of the
90 usual newline representations in the CGI response (it's the server's
91 job to create an accurate HTTP response based on it). So ``\n'' written in
92 text mode is technically correct, and recommended. NPH scripts are more
93 tricky: they must put out a complete and accurate set of HTTP
94 transaction response headers; the HTTP specification calls for records
95 to be terminated with carriage-return and line-feed, i.e ASCII \015\012
96 written in binary mode.</p>
97 <p>Using CGI.pm gives excellent platform independence, including EBCDIC
98 systems. CGI.pm selects an appropriate newline representation
99 ($CGI::CRLF) and sets binmode as appropriate.</p>
101 </p>
102 <h2><a name="my_cgi_script_runs_from_the_command_line_but_not_the_browser___500_server_error_">My CGI script runs from the command line but not the browser. (500 Server Error)</a></h2>
103 <p>Several things could be wrong. You can go through the ``Troubleshooting
104 Perl CGI scripts'' guide at</p>
105 <pre>
106 <a href="http://www.perl.org/troubleshooting_CGI.html">http://www.perl.org/troubleshooting_CGI.html</a></pre>
107 <p>If, after that, you can demonstrate that you've read the FAQs and that
108 your problem isn't something simple that can be easily answered, you'll
109 probably receive a courteous and useful reply to your question if you
110 post it on comp.infosystems.www.authoring.cgi (if it's something to do
111 with HTTP or the CGI protocols). Questions that appear to be Perl
112 questions but are really CGI ones that are posted to comp.lang.perl.misc
113 are not so well received.</p>
114 <p>The useful FAQs, related documents, and troubleshooting guides are
115 listed in the CGI Meta FAQ:</p>
116 <pre>
117 <a href="http://www.perl.org/CGI_MetaFAQ.html">http://www.perl.org/CGI_MetaFAQ.html</a></pre>
119 </p>
120 <h2><a name="how_can_i_get_better_error_messages_from_a_cgi_program">How can I get better error messages from a CGI program?</a></h2>
121 <p>Use the CGI::Carp module. It replaces <code>warn</code> and <code>die</code>, plus the
122 normal Carp modules <code>carp</code>, <code>croak</code>, and <code>confess</code> functions with
123 more verbose and safer versions. It still sends them to the normal
124 server error log.</p>
125 <pre>
126 use CGI::Carp;
127 warn &quot;This is a complaint&quot;;
128 die &quot;But this one is serious&quot;;</pre>
129 <p>The following use of CGI::Carp also redirects errors to a file of your choice,
130 placed in a BEGIN block to catch compile-time warnings as well:</p>
131 <pre>
132 BEGIN {
133 use CGI::Carp qw(carpout);
134 open(LOG, &quot;&gt;&gt;/var/local/cgi-logs/mycgi-log&quot;)
135 or die &quot;Unable to append to mycgi-log: $!\n&quot;;
136 carpout(*LOG);
137 }</pre>
138 <p>You can even arrange for fatal errors to go back to the client browser,
139 which is nice for your own debugging, but might confuse the end user.</p>
140 <pre>
141 use CGI::Carp qw(fatalsToBrowser);
142 die &quot;Bad error here&quot;;</pre>
143 <p>Even if the error happens before you get the HTTP header out, the module
144 will try to take care of this to avoid the dreaded server 500 errors.
145 Normal warnings still go out to the server error log (or wherever
146 you've sent them with <code>carpout</code>) with the application name and date
147 stamp prepended.</p>
149 </p>
150 <h2><a name="how_do_i_remove_html_from_a_string">How do I remove HTML from a string?</a></h2>
151 <p>The most correct way (albeit not the fastest) is to use HTML::Parser
152 from CPAN. Another mostly correct
153 way is to use HTML::FormatText which not only removes HTML but also
154 attempts to do a little simple formatting of the resulting plain text.</p>
155 <p>Many folks attempt a simple-minded regular expression approach, like
156 <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_s_"><code>s/&lt;.*?&gt;//g</code></a>, but that fails in many cases because the tags
157 may continue over line breaks, they may contain quoted angle-brackets,
158 or HTML comment may be present. Plus, folks forget to convert
159 entities--like <code>&amp;lt;</code> for example.</p>
160 <p>Here's one ``simple-minded'' approach, that works for most files:</p>
161 <pre>
162 #!/usr/bin/perl -p0777
163 s/&lt;(?:[^&gt;'&quot;]*|(['&quot;]).*?\1)*&gt;//gs</pre>
164 <p>If you want a more complete solution, see the 3-stage striphtml
165 program in
166 <a href="http://www.cpan.org/authors/Tom_Christiansen/scripts/striphtml.gz">http://www.cpan.org/authors/Tom_Christiansen/scripts/striphtml.gz</a>
167 .</p>
168 <p>Here are some tricky cases that you should think about when picking
169 a solution:</p>
170 <pre>
171 &lt;IMG SRC = &quot;foo.gif&quot; ALT = &quot;A &gt; B&quot;&gt;</pre>
172 <pre>
173 &lt;IMG SRC = &quot;foo.gif&quot;
174 ALT = &quot;A &gt; B&quot;&gt;</pre>
175 <pre>
176 &lt;!-- &lt;A comment&gt; --&gt;</pre>
177 <pre>
178 &lt;script&gt;if (a&lt;b &amp;&amp; a&gt;c)&lt;/script&gt;</pre>
179 <pre>
180 &lt;# Just data #&gt;</pre>
181 <pre>
182 &lt;![INCLUDE CDATA [ &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; ]]&gt;</pre>
183 <p>If HTML comments include other tags, those solutions would also break
184 on text like this:</p>
185 <pre>
186 &lt;!-- This section commented out.
187 &lt;B&gt;You can't see me!&lt;/B&gt;
188 --&gt;</pre>
190 </p>
191 <h2><a name="how_do_i_extract_urls">How do I extract URLs?</a></h2>
192 <p>You can easily extract all sorts of URLs from HTML with
193 <code>HTML::SimpleLinkExtor</code> which handles anchors, images, objects,
194 frames, and many other tags that can contain a URL. If you need
195 anything more complex, you can create your own subclass of
196 <code>HTML::LinkExtor</code> or <code>HTML::Parser</code>. You might even use
197 <code>HTML::SimpleLinkExtor</code> as an example for something specifically
198 suited to your needs.</p>
199 <p>You can use URI::Find to extract URLs from an arbitrary text document.</p>
200 <p>Less complete solutions involving regular expressions can save
201 you a lot of processing time if you know that the input is simple. One
202 solution from Tom Christiansen runs 100 times faster than most
203 module based approaches but only extracts URLs from anchors where the first
204 attribute is HREF and there are no other attributes.</p>
205 <pre>
206 #!/usr/bin/perl -n00
207 # qxurl - tchrist@perl.com
208 print &quot;$2\n&quot; while m{
209 &lt; \s*
210 A \s+ HREF \s* = \s* ([&quot;']) (.*?) \1
211 \s* &gt;
212 }gsix;</pre>
214 </p>
215 <h2><a name="how_do_i_download_a_file_from_the_user_s_machine_how_do_i_open_a_file_on_another_machine">How do I download a file from the user's machine? How do I open a file on another machine?</a></h2>
216 <p>In this case, download means to use the file upload feature of HTML
217 forms. You allow the web surfer to specify a file to send to your web
218 server. To you it looks like a download, and to the user it looks
219 like an upload. No matter what you call it, you do it with what's
220 known as <strong>multipart/form-data</strong> encoding. The CGI.pm module (which
221 comes with Perl as part of the Standard Library) supports this in the
222 <code>start_multipart_form()</code> method, which isn't the same as the <code>startform()</code>
223 method.</p>
224 <p>See the section in the CGI.pm documentation on file uploads for code
225 examples and details.</p>
227 </p>
228 <h2><a name="how_do_i_make_a_popup_menu_in_html">How do I make a pop-up menu in HTML?</a></h2>
229 <p>Use the <strong>&lt;SELECT</strong> &gt;&gt; and <strong>&lt;OPTION</strong> &gt;&gt; tags. The CGI.pm
230 module (available from CPAN) supports this widget, as well as many
231 others, including some that it cleverly synthesizes on its own.</p>
233 </p>
234 <h2><a name="how_do_i_fetch_an_html_file">How do I fetch an HTML file?</a></h2>
235 <p>One approach, if you have the lynx text-based HTML browser installed
236 on your system, is this:</p>
237 <pre>
238 $html_code = `lynx -source $url`;
239 $text_data = `lynx -dump $url`;</pre>
240 <p>The libwww-perl (LWP) modules from CPAN provide a more powerful way
241 to do this. They don't require lynx, but like lynx, can still work
242 through proxies:</p>
243 <pre>
244 # simplest version
245 use LWP::Simple;
246 $content = get($URL);</pre>
247 <pre>
248 # or print HTML from a URL
249 use LWP::Simple;
250 getprint &quot;<a href="http://www.linpro.no/lwp/&quot">http://www.linpro.no/lwp/&quot</a>;;</pre>
251 <pre>
252 # or print ASCII from HTML from a URL
253 # also need HTML-Tree package from CPAN
254 use LWP::Simple;
255 use HTML::Parser;
256 use HTML::FormatText;
257 my ($html, $ascii);
258 $html = get(&quot;<a href="http://www.perl.com/&quot">http://www.perl.com/&quot</a>;);
259 defined $html
260 or die &quot;Can't fetch HTML from <a href="http://www.perl.com/&quot">http://www.perl.com/&quot</a>;;
261 $ascii = HTML::FormatText-&gt;new-&gt;format(parse_html($html));
262 print $ascii;</pre>
264 </p>
265 <h2><a name="how_do_i_automate_an_html_form_submission">How do I automate an HTML form submission?</a></h2>
266 <p>If you are doing something complex, such as moving through many pages
267 and forms or a web site, you can use <code>WWW::Mechanize</code>. See its
268 documentation for all the details.</p>
269 <p>If you're submitting values using the GET method, create a URL and encode
270 the form using the <code>query_form</code> method:</p>
271 <pre>
272 use LWP::Simple;
273 use URI::URL;</pre>
274 <pre>
275 my $url = url('<a href="http://www.perl.com/cgi-bin/cpan_mod">http://www.perl.com/cgi-bin/cpan_mod</a>');
276 $url-&gt;query_form(module =&gt; 'DB_File', readme =&gt; 1);
277 $content = get($url);</pre>
278 <p>If you're using the POST method, create your own user agent and encode
279 the content appropriately.</p>
280 <pre>
281 use HTTP::Request::Common qw(POST);
282 use LWP::UserAgent;</pre>
283 <pre>
284 $ua = LWP::UserAgent-&gt;new();
285 my $req = POST '<a href="http://www.perl.com/cgi-bin/cpan_mod">http://www.perl.com/cgi-bin/cpan_mod</a>',
286 [ module =&gt; 'DB_File', readme =&gt; 1 ];
287 $content = $ua-&gt;request($req)-&gt;as_string;</pre>
289 </p>
290 <h2><a name="how_do_i_decode_or_create_those__encodings_on_the_web">How do I decode or create those %-encodings on the web?</a></h2>
291 <p>If you are writing a CGI script, you should be using the CGI.pm module
292 that comes with perl, or some other equivalent module. The CGI module
293 automatically decodes queries for you, and provides an <code>escape()</code>
294 function to handle encoding.</p>
295 <p>The best source of detailed information on URI encoding is RFC 2396.
296 Basically, the following substitutions do it:</p>
297 <pre>
298 s/([^\w()'*~!.-])/sprintf '%%%02x', ord $1/eg; # encode</pre>
299 <pre>
300 s/%([A-Fa-f\d]{2})/chr hex $1/eg; # decode
301 s/%([[:xdigit:]]{2})/chr hex $1/eg; # same thing</pre>
302 <p>However, you should only apply them to individual URI components, not
303 the entire URI, otherwise you'll lose information and generally mess
304 things up. If that didn't explain it, don't worry. Just go read
305 section 2 of the RFC, it's probably the best explanation there is.</p>
306 <p>RFC 2396 also contains a lot of other useful information, including a
307 regexp for breaking any arbitrary URI into components (Appendix B).</p>
309 </p>
310 <h2><a name="how_do_i_redirect_to_another_page">How do I redirect to another page?</a></h2>
311 <p>Specify the complete URL of the destination (even if it is on the same
312 server). This is one of the two different kinds of CGI ``Location:''
313 responses which are defined in the CGI specification for a Parsed Headers
314 script. The other kind (an absolute URLpath) is resolved internally to
315 the server without any HTTP redirection. The CGI specifications do not
316 allow relative URLs in either case.</p>
317 <p>Use of CGI.pm is strongly recommended. This example shows redirection
318 with a complete URL. This redirection is handled by the web browser.</p>
319 <pre>
320 use CGI qw/:standard/;</pre>
321 <pre>
322 my $url = '<a href="http://www.cpan.org/">http://www.cpan.org/</a>';
323 print redirect($url);</pre>
324 <p>This example shows a redirection with an absolute URLpath. This
325 redirection is handled by the local web server.</p>
326 <pre>
327 my $url = '/CPAN/index.html';
328 print redirect($url);</pre>
329 <p>But if coded directly, it could be as follows (the final ``\n'' is
330 shown separately, for clarity), using either a complete URL or
331 an absolute URLpath.</p>
332 <pre>
333 print &quot;Location: $url\n&quot;; # CGI response header
334 print &quot;\n&quot;; # end of headers</pre>
336 </p>
337 <h2><a name="how_do_i_put_a_password_on_my_web_pages">How do I put a password on my web pages?</a></h2>
338 <p>To enable authentication for your web server, you need to configure
339 your web server. The configuration is different for different sorts
340 of web servers---apache does it differently from iPlanet which does
341 it differently from IIS. Check your web server documentation for
342 the details for your particular server.</p>
344 </p>
345 <h2><a name="how_do_i_edit_my__htpasswd_and__htgroup_files_with_perl">How do I edit my .htpasswd and .htgroup files with Perl?</a></h2>
346 <p>The HTTPD::UserAdmin and HTTPD::GroupAdmin modules provide a
347 consistent OO interface to these files, regardless of how they're
348 stored. Databases may be text, dbm, Berkeley DB or any database with
349 a DBI compatible driver. HTTPD::UserAdmin supports files used by the
350 ``Basic'' and ``Digest'' authentication schemes. Here's an example:</p>
351 <pre>
352 use HTTPD::UserAdmin ();
353 HTTPD::UserAdmin
354 -&gt;new(DB =&gt; &quot;/foo/.htpasswd&quot;)
355 -&gt;add($username =&gt; $password);</pre>
357 </p>
358 <h2><a name="how_do_i_make_sure_users_can_t_enter_values_into_a_form_that_cause_my_cgi_script_to_do_bad_things">How do I make sure users can't enter values into a form that cause my CGI script to do bad things?</a></h2>
359 <p>See the security references listed in the CGI Meta FAQ</p>
360 <pre>
361 <a href="http://www.perl.org/CGI_MetaFAQ.html">http://www.perl.org/CGI_MetaFAQ.html</a></pre>
363 </p>
364 <h2><a name="how_do_i_parse_a_mail_header">How do I parse a mail header?</a></h2>
365 <p>For a quick-and-dirty solution, try this solution derived
366 from <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_split">split in the perlfunc manpage</a>:</p>
367 <pre>
368 $/ = '';
369 $header = &lt;MSG&gt;;
370 $header =~ s/\n\s+/ /g; # merge continuation lines
371 %head = ( UNIX_FROM_LINE, split /^([-\w]+):\s*/m, $header );</pre>
372 <p>That solution doesn't do well if, for example, you're trying to
373 maintain all the Received lines. A more complete approach is to use
374 the Mail::Header module from CPAN (part of the MailTools package).</p>
376 </p>
377 <h2><a name="how_do_i_decode_a_cgi_form">How do I decode a CGI form?</a></h2>
378 <p>(contributed by brian d foy)</p>
379 <p>Use the CGI.pm module that comes with Perl. It's quick,
380 it's easy, and it actually does quite a bit of work to
381 ensure things happen correctly. It handles GET, POST, and
382 HEAD requests, multipart forms, multivalued fields, query
383 string and message body combinations, and many other things
384 you probably don't want to think about.</p>
385 <p>It doesn't get much easier: the CGI module automatically
386 parses the input and makes each value available through the
387 <code>param()</code> function.</p>
388 <pre>
389 use CGI qw(:standard);</pre>
390 <pre>
391 my $total = param( 'price' ) + param( 'shipping' );</pre>
392 <pre>
393 my @items = param( 'item' ); # multiple values, same field name</pre>
394 <p>If you want an object-oriented approach, CGI.pm can do that too.</p>
395 <pre>
396 use CGI;</pre>
397 <pre>
398 my $cgi = CGI-&gt;new();</pre>
399 <pre>
400 my $total = $cgi-&gt;param( 'price' ) + $cgi-&gt;param( 'shipping' );</pre>
401 <pre>
402 my @items = $cgi-&gt;param( 'item' );</pre>
403 <p>You might also try CGI::Minimal which is a lightweight version
404 of the same thing. Other CGI::* modules on CPAN might work better
405 for you, too.</p>
406 <p>Many people try to write their own decoder (or copy one from
407 another program) and then run into one of the many ``gotchas''
408 of the task. It's much easier and less hassle to use CGI.pm.</p>
410 </p>
411 <h2><a name="how_do_i_check_a_valid_mail_address">How do I check a valid mail address?</a></h2>
412 <p>You can't, at least, not in real time. Bummer, eh?</p>
413 <p>Without sending mail to the address and seeing whether there's a human
414 on the other end to answer you, you cannot determine whether a mail
415 address is valid. Even if you apply the mail header standard, you
416 can have problems, because there are deliverable addresses that aren't
417 RFC-822 (the mail header standard) compliant, and addresses that aren't
418 deliverable which are compliant.</p>
419 <p>You can use the Email::Valid or RFC::RFC822::Address which check
420 the format of the address, although they cannot actually tell you
421 if it is a deliverable address (i.e. that mail to the address
422 will not bounce). Modules like Mail::CheckUser and Mail::EXPN
423 try to interact with the domain name system or particular
424 mail servers to learn even more, but their methods do not
425 work everywhere---especially for security conscious administrators.</p>
426 <p>Many are tempted to try to eliminate many frequently-invalid
427 mail addresses with a simple regex, such as
428 <code>/^[\w.-]+\@(?:[\w-]+\.)+\w+$/</code>. It's a very bad idea. However,
429 this also throws out many valid ones, and says nothing about
430 potential deliverability, so it is not suggested. Instead, see
431 <a href="http://www.cpan.org/authors/Tom_Christiansen/scripts/ckaddr.gz">http://www.cpan.org/authors/Tom_Christiansen/scripts/ckaddr.gz</a> ,
432 which actually checks against the full RFC spec (except for nested
433 comments), looks for addresses you may not wish to accept mail to
434 (say, Bill Clinton or your postmaster), and then makes sure that the
435 hostname given can be looked up in the DNS MX records. It's not fast,
436 but it works for what it tries to do.</p>
437 <p>Our best advice for verifying a person's mail address is to have them
438 enter their address twice, just as you normally do to change a password.
439 This usually weeds out typos. If both versions match, send
440 mail to that address with a personal message that looks somewhat like:</p>
441 <pre>
442 Dear someuser@host.com,</pre>
443 <pre>
444 Please confirm the mail address you gave us Wed May 6 09:38:41
445 MDT 1998 by replying to this message. Include the string
446 &quot;Rumpelstiltskin&quot; in that reply, but spelled in reverse; that is,
447 start with &quot;Nik...&quot;. Once this is done, your confirmed address will
448 be entered into our records.</pre>
449 <p>If you get the message back and they've followed your directions,
450 you can be reasonably assured that it's real.</p>
451 <p>A related strategy that's less open to forgery is to give them a PIN
452 (personal ID number). Record the address and PIN (best that it be a
453 random one) for later processing. In the mail you send, ask them to
454 include the PIN in their reply. But if it bounces, or the message is
455 included via a ``vacation'' script, it'll be there anyway. So it's
456 best to ask them to mail back a slight alteration of the PIN, such as
457 with the characters reversed, one added or subtracted to each digit, etc.</p>
459 </p>
460 <h2><a name="how_do_i_decode_a_mime_base64_string">How do I decode a MIME/BASE64 string?</a></h2>
461 <p>The MIME-Base64 package (available from CPAN) handles this as well as
462 the MIME/QP encoding. Decoding BASE64 becomes as simple as:</p>
463 <pre>
464 use MIME::Base64;
465 $decoded = decode_base64($encoded);</pre>
466 <p>The MIME-Tools package (available from CPAN) supports extraction with
467 decoding of BASE64 encoded attachments and content directly from email
468 messages.</p>
469 <p>If the string to decode is short (less than 84 bytes long)
470 a more direct approach is to use the <code>unpack()</code> function's ``u''
471 format after minor transliterations:</p>
472 <pre>
473 tr#A-Za-z0-9+/##cd; # remove non-base64 chars
474 tr#A-Za-z0-9+/# -_#; # convert to uuencoded format
475 $len = pack(&quot;c&quot;, 32 + 0.75*length); # compute length byte
476 print unpack(&quot;u&quot;, $len . $_); # uudecode and print</pre>
478 </p>
479 <h2><a name="how_do_i_return_the_user_s_mail_address">How do I return the user's mail address?</a></h2>
480 <p>On systems that support getpwuid, the $&lt; variable, and the
481 Sys::Hostname module (which is part of the standard perl distribution),
482 you can probably try using something like this:</p>
483 <pre>
484 use Sys::Hostname;
485 $address = sprintf('%s@%s', scalar getpwuid($&lt;), hostname);</pre>
486 <p>Company policies on mail address can mean that this generates addresses
487 that the company's mail system will not accept, so you should ask for
488 users' mail addresses when this matters. Furthermore, not all systems
489 on which Perl runs are so forthcoming with this information as is Unix.</p>
490 <p>The Mail::Util module from CPAN (part of the MailTools package) provides a
491 <code>mailaddress()</code> function that tries to guess the mail address of the user.
492 It makes a more intelligent guess than the code above, using information
493 given when the module was installed, but it could still be incorrect.
494 Again, the best way is often just to ask the user.</p>
496 </p>
497 <h2><a name="how_do_i_send_mail">How do I send mail?</a></h2>
498 <p>Use the <code>sendmail</code> program directly:</p>
499 <pre>
500 open(SENDMAIL, &quot;|/usr/lib/sendmail -oi -t -odq&quot;)
501 or die &quot;Can't fork for sendmail: $!\n&quot;;
502 print SENDMAIL &lt;&lt;&quot;EOF&quot;;
503 From: User Originating Mail &lt;me\@host&gt;
504 To: Final Destination &lt;you\@otherhost&gt;
505 Subject: A relevant subject line</pre>
506 <pre>
507 Body of the message goes here after the blank line
508 in as many lines as you like.
510 close(SENDMAIL) or warn &quot;sendmail didn't close nicely&quot;;</pre>
511 <p>The <strong>-oi</strong> option prevents sendmail from interpreting a line consisting
512 of a single dot as ``end of message''. The <strong>-t</strong> option says to use the
513 headers to decide who to send the message to, and <strong>-odq</strong> says to put
514 the message into the queue. This last option means your message won't
515 be immediately delivered, so leave it out if you want immediate
516 delivery.</p>
517 <p>Alternate, less convenient approaches include calling mail (sometimes
518 called mailx) directly or simply opening up port 25 have having an
519 intimate conversation between just you and the remote SMTP daemon,
520 probably sendmail.</p>
521 <p>Or you might be able use the CPAN module Mail::Mailer:</p>
522 <pre>
523 use Mail::Mailer;</pre>
524 <pre>
525 $mailer = Mail::Mailer-&gt;new();
526 $mailer-&gt;open({ From =&gt; $from_address,
527 To =&gt; $to_address,
528 Subject =&gt; $subject,
530 or die &quot;Can't open: $!\n&quot;;
531 print $mailer $body;
532 $mailer-&gt;close();</pre>
533 <p>The Mail::Internet module uses Net::SMTP which is less Unix-centric than
534 Mail::Mailer, but less reliable. Avoid raw SMTP commands. There
535 are many reasons to use a mail transport agent like sendmail. These
536 include queuing, MX records, and security.</p>
538 </p>
539 <h2><a name="how_do_i_use_mime_to_make_an_attachment_to_a_mail_message">How do I use MIME to make an attachment to a mail message?</a></h2>
540 <p>This answer is extracted directly from the MIME::Lite documentation.
541 Create a multipart message (i.e., one with attachments).</p>
542 <pre>
543 use MIME::Lite;</pre>
544 <pre>
545 ### Create a new multipart message:
546 $msg = MIME::Lite-&gt;new(
547 From =&gt;'me@myhost.com',
548 To =&gt;'you@yourhost.com',
549 Cc =&gt;'some@other.com, some@more.com',
550 Subject =&gt;'A message with 2 parts...',
551 Type =&gt;'multipart/mixed'
552 );</pre>
553 <pre>
554 ### Add parts (each &quot;attach&quot; has same arguments as &quot;new&quot;):
555 $msg-&gt;attach(Type =&gt;'TEXT',
556 Data =&gt;&quot;Here's the GIF file you wanted&quot;
558 $msg-&gt;attach(Type =&gt;'image/gif',
559 Path =&gt;'aaa000123.gif',
560 Filename =&gt;'logo.gif'
561 );</pre>
562 <pre>
563 $text = $msg-&gt;as_string;</pre>
564 <p>MIME::Lite also includes a method for sending these things.</p>
565 <pre>
566 $msg-&gt;send;</pre>
567 <p>This defaults to using <em>sendmail</em> but can be customized to use
568 SMTP via <a href="file://C|\msysgit\mingw\html/lib/Net/SMTP.html">the Net::SMTP manpage</a>.</p>
570 </p>
571 <h2><a name="how_do_i_read_mail">How do I read mail?</a></h2>
572 <p>While you could use the Mail::Folder module from CPAN (part of the
573 MailFolder package) or the Mail::Internet module from CPAN (part
574 of the MailTools package), often a module is overkill. Here's a
575 mail sorter.</p>
576 <pre>
577 #!/usr/bin/perl</pre>
578 <pre>
579 my(@msgs, @sub);
580 my $msgno = -1;
581 $/ = ''; # paragraph reads
582 while (&lt;&gt;) {
583 if (/^From /m) {
584 /^Subject:\s*(?:Re:\s*)*(.*)/mi;
585 $sub[++$msgno] = lc($1) || '';
587 $msgs[$msgno] .= $_;
589 for my $i (sort { $sub[$a] cmp $sub[$b] || $a &lt;=&gt; $b } (0 .. $#msgs)) {
590 print $msgs[$i];
591 }</pre>
592 <p>Or more succinctly,</p>
593 <pre>
594 #!/usr/bin/perl -n00
595 # bysub2 - awkish sort-by-subject
596 BEGIN { $msgno = -1 }
597 $sub[++$msgno] = (/^Subject:\s*(?:Re:\s*)*(.*)/mi)[0] if /^From/m;
598 $msg[$msgno] .= $_;
599 END { print @msg[ sort { $sub[$a] cmp $sub[$b] || $a &lt;=&gt; $b } (0 .. $#msg) ] }</pre>
601 </p>
602 <h2><a name="how_do_i_find_out_my_hostname__domainname__or_ip_address_x_hostname__domainname__ip_address__host__domain__hostfqdn__inet_ntoa__gethostbyname__socket__net__domain__sys__hostname_">How do I find out my hostname, domainname, or IP address?
603 </a></h2>
604 <p>(contributed by brian d foy)</p>
605 <p>The Net::Domain module, which is part of the standard distribution starting
606 in perl5.7.3, can get you the fully qualified domain name (FQDN), the host
607 name, or the domain name.</p>
608 <pre>
609 use Net::Domain qw(hostname hostfqdn hostdomain);</pre>
610 <pre>
611 my $host = hostfqdn();</pre>
612 <p>The <code>Sys::Hostname</code> module, included in the standard distribution since
613 perl5.6, can also get the hostname.</p>
614 <pre>
615 use Sys::Hostname;</pre>
616 <pre>
617 $host = hostname();</pre>
618 <p>To get the IP address, you can use the <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_gethostbyname"><code>gethostbyname</code></a> built-in function
619 to turn the name into a number. To turn that number into the dotted octet
620 form (a.b.c.d) that most people expect, use the <code>inet_ntoa</code> function
621 from the &lt;Socket&gt; module, which also comes with perl.</p>
622 <pre>
623 use Socket;</pre>
624 <pre>
625 my $address = inet_ntoa(
626 scalar gethostbyname( $host || 'localhost' )
627 );</pre>
629 </p>
630 <h2><a name="how_do_i_fetch_a_news_article_or_the_active_newsgroups">How do I fetch a news article or the active newsgroups?</a></h2>
631 <p>Use the Net::NNTP or News::NNTPClient modules, both available from CPAN.
632 This can make tasks like fetching the newsgroup list as simple as</p>
633 <pre>
634 perl -MNews::NNTPClient
635 -e 'print News::NNTPClient-&gt;new-&gt;list(&quot;newsgroups&quot;)'</pre>
637 </p>
638 <h2><a name="how_do_i_fetch_put_an_ftp_file">How do I fetch/put an FTP file?</a></h2>
639 <p>LWP::Simple (available from CPAN) can fetch but not put. Net::FTP (also
640 available from CPAN) is more complex but can put as well as fetch.</p>
642 </p>
643 <h2><a name="how_can_i_do_rpc_in_perl">How can I do RPC in Perl?</a></h2>
644 <p>(Contributed by brian d foy)</p>
645 <p>Use one of the RPC modules you can find on CPAN (
646 <a href="http://search.cpan.org/search?query=RPC&mode=all">http://search.cpan.org/search?query=RPC&mode=all</a> ).</p>
648 </p>
649 <hr />
650 <h1><a name="author_and_copyright">AUTHOR AND COPYRIGHT</a></h1>
651 <p>Copyright (c) 1997-2006 Tom Christiansen, Nathan Torkington, and
652 other authors as noted. All rights reserved.</p>
653 <p>This documentation is free; you can redistribute it and/or modify it
654 under the same terms as Perl itself.</p>
655 <p>Irrespective of its distribution, all code examples in this file
656 are hereby placed into the public domain. You are permitted and
657 encouraged to use this code in your own programs for fun
658 or for profit as you see fit. A simple comment in the code giving
659 credit would be courteous but is not required.</p>
660 <table border="0" width="100%" cellspacing="0" cellpadding="3">
661 <tr><td class="block" style="background-color: #cccccc" valign="middle">
662 <big><strong><span class="block">&nbsp;perlfaq9 - Networking</span></strong></big>
663 </td></tr>
664 </table>
666 </body>
668 </html>