home *** CD-ROM | disk | FTP | other *** search
/ Chip 2000 May / Chip_2000-05_cd1.bin / zkuste / Perl / ActivePerl-5.6.0.613.msi / 䆊䌷䈹䈙䏵-䞅䞆䞀㡆䞃䄦䠥 / _714565a561c24a63ad3d956f4e7573ad < prev    next >
Encoding:
Text File  |  2000-03-23  |  29.8 KB  |  556 lines

  1. <HTML>
  2. <HEAD>
  3. <TITLE>perlfaq9 - Networking</TITLE>
  4. <LINK REL="stylesheet" HREF="../../Active.css" TYPE="text/css">
  5. <LINK REV="made" HREF="mailto:">
  6. </HEAD>
  7.  
  8. <BODY>
  9. <TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0 WIDTH=100%>
  10. <TR><TD CLASS=block VALIGN=MIDDLE WIDTH=100% BGCOLOR="#cccccc">
  11. <STRONG><P CLASS=block> perlfaq9 - Networking</P></STRONG>
  12. </TD></TR>
  13. </TABLE>
  14.  
  15. <A NAME="__index__"></A>
  16. <!-- INDEX BEGIN -->
  17.  
  18. <UL>
  19.  
  20.     <LI><A HREF="#name">NAME</A></LI>
  21.     <LI><A HREF="#description">DESCRIPTION</A></LI>
  22.     <UL>
  23.  
  24.         <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>
  25.         <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>
  26.         <LI><A HREF="#how do i remove html from a string">How do I remove HTML from a string?</A></LI>
  27.         <LI><A HREF="#how do i extract urls">How do I extract URLs?</A></LI>
  28.         <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>
  29.         <LI><A HREF="#how do i make a popup menu in html">How do I make a pop-up menu in HTML?</A></LI>
  30.         <LI><A HREF="#how do i fetch an html file">How do I fetch an HTML file?</A></LI>
  31.         <LI><A HREF="#how do i automate an html form submission">How do I automate an HTML form submission?</A></LI>
  32.         <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>
  33.         <LI><A HREF="#how do i redirect to another page">How do I redirect to another page?</A></LI>
  34.         <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>
  35.         <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>
  36.         <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>
  37.         <LI><A HREF="#how do i parse a mail header">How do I parse a mail header?</A></LI>
  38.         <LI><A HREF="#how do i decode a cgi form">How do I decode a CGI form?</A></LI>
  39.         <LI><A HREF="#how do i check a valid mail address">How do I check a valid mail address?</A></LI>
  40.         <LI><A HREF="#how do i decode a mime/base64 string">How do I decode a MIME/BASE64 string?</A></LI>
  41.         <LI><A HREF="#how do i return the user's mail address">How do I return the user's mail address?</A></LI>
  42.         <LI><A HREF="#how do i send mail">How do I send mail?</A></LI>
  43.         <LI><A HREF="#how do i read mail">How do I read mail?</A></LI>
  44.         <LI><A HREF="#how do i find out my hostname/domainname/ip address">How do I find out my hostname/domainname/IP address?</A></LI>
  45.         <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>
  46.         <LI><A HREF="#how do i fetch/put an ftp file">How do I fetch/put an FTP file?</A></LI>
  47.         <LI><A HREF="#how can i do rpc in perl">How can I do RPC in Perl?</A></LI>
  48.     </UL>
  49.  
  50.     <LI><A HREF="#author and copyright">AUTHOR AND COPYRIGHT</A></LI>
  51. </UL>
  52. <!-- INDEX END -->
  53.  
  54. <HR>
  55. <P>
  56. <H1><A NAME="name">NAME</A></H1>
  57. <P>perlfaq9 - Networking ($Revision: 1.26 $, $Date: 1999/05/23 16:08:30 $)</P>
  58. <P>
  59. <HR>
  60. <H1><A NAME="description">DESCRIPTION</A></H1>
  61. <P>This section deals with questions related to networking, the internet,
  62. and a few on the web.</P>
  63. <P>
  64. <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>
  65. <P>If you can demonstrate that you've read the following FAQs and that
  66. your problem isn't something simple that can be easily answered, you'll
  67. probably receive a courteous and useful reply to your question if you
  68. post it on comp.infosystems.www.authoring.cgi (if it's something to do
  69. with HTTP, HTML, or the CGI protocols).  Questions that appear to be Perl
  70. questions but are really CGI ones that are posted to comp.lang.perl.misc
  71. may not be so well received.</P>
  72. <P>The useful FAQs and related documents are:</P>
  73. <PRE>
  74.     CGI FAQ
  75.         <A HREF="http://www.webthing.com/tutorials/cgifaq.html">http://www.webthing.com/tutorials/cgifaq.html</A></PRE>
  76. <PRE>
  77.     Web FAQ
  78.         <A HREF="http://www.boutell.com/faq/">http://www.boutell.com/faq/</A></PRE>
  79. <PRE>
  80.     WWW Security FAQ
  81.         <A HREF="http://www.w3.org/Security/Faq/">http://www.w3.org/Security/Faq/</A></PRE>
  82. <PRE>
  83.     HTTP Spec
  84.         <A HREF="http://www.w3.org/pub/WWW/Protocols/HTTP/">http://www.w3.org/pub/WWW/Protocols/HTTP/</A></PRE>
  85. <PRE>
  86.     HTML Spec
  87.         <A HREF="http://www.w3.org/TR/REC-html40/">http://www.w3.org/TR/REC-html40/</A>
  88.         <A HREF="http://www.w3.org/pub/WWW/MarkUp/">http://www.w3.org/pub/WWW/MarkUp/</A></PRE>
  89. <PRE>
  90.     CGI Spec
  91.         <A HREF="http://www.w3.org/CGI/">http://www.w3.org/CGI/</A></PRE>
  92. <PRE>
  93.     CGI Security FAQ
  94.         <A HREF="http://www.go2net.com/people/paulp/cgi-security/safe-cgi.txt">http://www.go2net.com/people/paulp/cgi-security/safe-cgi.txt</A></PRE>
  95. <P>
  96. <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>
  97. <P>Use the CGI::Carp module.  It replaces <A HREF="../../lib/Pod/perlfunc.html#item_warn"><CODE>warn</CODE></A> and <A HREF="../../lib/Pod/perlfunc.html#item_die"><CODE>die</CODE></A>, plus the
  98. normal Carp modules <CODE>carp</CODE>, <CODE>croak</CODE>, and <CODE>confess</CODE> functions with
  99. more verbose and safer versions.  It still sends them to the normal
  100. server error log.</P>
  101. <PRE>
  102.     use CGI::Carp;
  103.     warn "This is a complaint";
  104.     die "But this one is serious";</PRE>
  105. <P>The following use of CGI::Carp also redirects errors to a file of your choice,
  106. placed in a BEGIN block to catch compile-time warnings as well:</P>
  107. <PRE>
  108.     BEGIN {
  109.         use CGI::Carp qw(carpout);
  110.         open(LOG, ">>/var/local/cgi-logs/mycgi-log")
  111.             or die "Unable to append to mycgi-log: $!\n";
  112.         carpout(*LOG);
  113.     }</PRE>
  114. <P>You can even arrange for fatal errors to go back to the client browser,
  115. which is nice for your own debugging, but might confuse the end user.</P>
  116. <PRE>
  117.     use CGI::Carp qw(fatalsToBrowser);
  118.     die "Bad error here";</PRE>
  119. <P>Even if the error happens before you get the HTTP header out, the module
  120. will try to take care of this to avoid the dreaded server 500 errors.
  121. Normal warnings still go out to the server error log (or wherever
  122. you've sent them with <CODE>carpout</CODE>) with the application name and date
  123. stamp prepended.</P>
  124. <P>
  125. <H2><A NAME="how do i remove html from a string">How do I remove HTML from a string?</A></H2>
  126. <P>The most correct way (albeit not the fastest) is to use HTML::Parser
  127. from CPAN.  Another mostly correct
  128. way is to use HTML::FormatText which not only removes HTML but also
  129. attempts to do a little simple formatting of the resulting plain text.</P>
  130. <P>Many folks attempt a simple-minded regular expression approach, like
  131. <CODE>s/<.*?>//g</CODE>, but that fails in many cases because the tags
  132. may continue over line breaks, they may contain quoted angle-brackets,
  133. or HTML comment may be present.  Plus folks forget to convert
  134. entities, like <CODE>&lt;</CODE> for example.</P>
  135. <P>Here's one ``simple-minded'' approach, that works for most files:</P>
  136. <PRE>
  137.     #!/usr/bin/perl -p0777
  138.     s/<(?:[^>'"]*|(['"]).*?\1)*>//gs</PRE>
  139. <P>If you want a more complete solution, see the 3-stage striphtml
  140. program in
  141. <A HREF="http://www.perl.com/CPAN/authors/Tom_Christiansen/scripts/striphtml.gz">http://www.perl.com/CPAN/authors/Tom_Christiansen/scripts/striphtml.gz</A>
  142. .</P>
  143. <P>Here are some tricky cases that you should think about when picking
  144. a solution:</P>
  145. <PRE>
  146.     <IMG SRC = "foo.gif" ALT = "A > B"></PRE>
  147. <PRE>
  148.     <IMG SRC = "foo.gif"
  149.          ALT = "A > B"></PRE>
  150. <PRE>
  151.     <!-- <A comment> --></PRE>
  152. <PRE>
  153.     <script>if (a<b && a>c)</script></PRE>
  154. <PRE>
  155.     <# Just data #></PRE>
  156. <PRE>
  157.     <![INCLUDE CDATA [ >>>>>>>>>>>> ]]></PRE>
  158. <P>If HTML comments include other tags, those solutions would also break
  159. on text like this:</P>
  160. <PRE>
  161.     <!-- This section commented out.
  162.         <B>You can't see me!</B>
  163.     --></PRE>
  164. <P>
  165. <H2><A NAME="how do i extract urls">How do I extract URLs?</A></H2>
  166. <P>A quick but imperfect approach is</P>
  167. <PRE>
  168.     #!/usr/bin/perl -n00
  169.     # qxurl - tchrist@perl.com
  170.     print "$2\n" while m{
  171.         < \s*
  172.           A \s+ HREF \s* = \s* (["']) (.*?) \1
  173.         \s* >
  174.     }gsix;</PRE>
  175. <P>This version does not adjust relative URLs, understand alternate
  176. bases, deal with HTML comments, deal with HREF and NAME attributes
  177. in the same tag, understand extra qualifiers like TARGET, or accept
  178. URLs themselves as arguments.  It also runs about 100x faster than a
  179. more ``complete'' solution using the LWP suite of modules, such as the
  180. <A HREF="http://www.perl.com/CPAN/authors/Tom_Christiansen/scripts/xurl.gz">http://www.perl.com/CPAN/authors/Tom_Christiansen/scripts/xurl.gz</A> program.</P>
  181. <P>
  182. <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>
  183. <P>In the context of an HTML form, you can use what's known as
  184. <STRONG>multipart/form-data</STRONG> encoding.  The CGI.pm module (available from
  185. CPAN) supports this in the <CODE>start_multipart_form()</CODE> method, which isn't
  186. the same as the <CODE>startform()</CODE> method.</P>
  187. <P>
  188. <H2><A NAME="how do i make a popup menu in html">How do I make a pop-up menu in HTML?</A></H2>
  189. <P>Use the <STRONG><SELECT</STRONG> >> and <STRONG><OPTION</STRONG> >> tags.  The CGI.pm
  190. module (available from CPAN) supports this widget, as well as many
  191. others, including some that it cleverly synthesizes on its own.</P>
  192. <P>
  193. <H2><A NAME="how do i fetch an html file">How do I fetch an HTML file?</A></H2>
  194. <P>One approach, if you have the lynx text-based HTML browser installed
  195. on your system, is this:</P>
  196. <PRE>
  197.     $html_code = `lynx -source $url`;
  198.     $text_data = `lynx -dump $url`;</PRE>
  199. <P>The libwww-perl (LWP) modules from CPAN provide a more powerful way
  200. to do this.  They don't require lynx, but like lynx, can still work
  201. through proxies:</P>
  202. <PRE>
  203.     # simplest version
  204.     use LWP::Simple;
  205.     $content = get($URL);</PRE>
  206. <PRE>
  207.     # or print HTML from a URL
  208.     use LWP::Simple;
  209.     getprint "<A HREF="http://www.linpro.no/lwp/"">http://www.linpro.no/lwp/"</A>;;</PRE>
  210. <PRE>
  211.     # or print ASCII from HTML from a URL
  212.     # also need HTML-Tree package from CPAN
  213.     use LWP::Simple;
  214.     use HTML::Parser;
  215.     use HTML::FormatText;
  216.     my ($html, $ascii);
  217.     $html = get("<A HREF="http://www.perl.com/"">http://www.perl.com/"</A>;);
  218.     defined $html
  219.         or die "Can't fetch HTML from <A HREF="http://www.perl.com/"">http://www.perl.com/"</A>;;
  220.     $ascii = HTML::FormatText->new->format(parse_html($html));
  221.     print $ascii;</PRE>
  222. <P>
  223. <H2><A NAME="how do i automate an html form submission">How do I automate an HTML form submission?</A></H2>
  224. <P>If you're submitting values using the GET method, create a URL and encode
  225. the form using the <CODE>query_form</CODE> method:</P>
  226. <PRE>
  227.     use LWP::Simple;
  228.     use URI::URL;</PRE>
  229. <PRE>
  230.     my $url = url('<A HREF="http://www.perl.com/cgi-bin/cpan_mod">http://www.perl.com/cgi-bin/cpan_mod</A>');
  231.     $url->query_form(module => 'DB_File', readme => 1);
  232.     $content = get($url);</PRE>
  233. <P>If you're using the POST method, create your own user agent and encode
  234. the content appropriately.</P>
  235. <PRE>
  236.     use HTTP::Request::Common qw(POST);
  237.     use LWP::UserAgent;</PRE>
  238. <PRE>
  239.     $ua = LWP::UserAgent->new();
  240.     my $req = POST '<A HREF="http://www.perl.com/cgi-bin/cpan_mod">http://www.perl.com/cgi-bin/cpan_mod</A>',
  241.                    [ module => 'DB_File', readme => 1 ];
  242.     $content = $ua->request($req)->as_string;</PRE>
  243. <P>
  244. <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>
  245. <P>Here's an example of decoding:</P>
  246. <PRE>
  247.     $string = "<A HREF="http://altavista.digital.com/cgi-bin/query?pg=q&">http://altavista.digital.com/cgi-bin/query?pg=q&</A>;what=news&fmt=.&q=%2Bcgi-bin+%2Bperl.exe";
  248.     $string =~ s/%([a-fA-F0-9]{2})/chr(hex($1))/ge;</PRE>
  249. <P>Encoding is a bit harder, because you can't just blindly change
  250. all the non-alphanumunder character (<CODE>\W</CODE>) into their hex escapes.
  251. It's important that characters with special meaning like <CODE>/</CODE> and <CODE>?</CODE>
  252. <EM>not</EM> be translated.  Probably the easiest way to get this right is
  253. to avoid reinventing the wheel and just use the URI::Escape module,
  254. available from CPAN.</P>
  255. <P>
  256. <H2><A NAME="how do i redirect to another page">How do I redirect to another page?</A></H2>
  257. <P>Instead of sending back a <CODE>Content-Type</CODE> as the headers of your
  258. reply, send back a <CODE>Location:</CODE> header.  Officially this should be a
  259. <CODE>URI:</CODE> header, so the CGI.pm module (available from CPAN) sends back
  260. both:</P>
  261. <PRE>
  262.     Location: <A HREF="http://www.domain.com/newpage">http://www.domain.com/newpage</A>
  263.     URI: <A HREF="http://www.domain.com/newpage">http://www.domain.com/newpage</A></PRE>
  264. <P>Note that relative URLs in these headers can cause strange effects
  265. because of ``optimizations'' that servers do.</P>
  266. <PRE>
  267.     $url = "<A HREF="http://www.perl.com/CPAN/"">http://www.perl.com/CPAN/"</A>;;
  268.     print "Location: $url\n\n";
  269.     exit;</PRE>
  270. <P>To target a particular frame in a frameset, include the ``Window-target:''
  271. in the header.</P>
  272. <PRE>
  273.     print <<EOF;
  274.     Location: <A HREF="http://www.domain.com/newpage">http://www.domain.com/newpage</A>
  275.     Window-target: <FrameName></PRE>
  276. <PRE>
  277.     EOF</PRE>
  278. <P>To be correct to the spec, each of those virtual newlines should really be
  279. physical <CODE>"\015\012"</CODE> sequences by the time you hit the client browser.
  280. Except for NPH scripts, though, that local newline should get translated
  281. by your server into standard form, so you shouldn't have a problem
  282. here, even if you are stuck on MacOS.  Everybody else probably won't
  283. even notice.</P>
  284. <P>
  285. <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>
  286. <P>That depends.  You'll need to read the documentation for your web
  287. server, or perhaps check some of the other FAQs referenced above.</P>
  288. <P>
  289. <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>
  290. <P>The HTTPD::UserAdmin and HTTPD::GroupAdmin modules provide a
  291. consistent OO interface to these files, regardless of how they're
  292. stored.  Databases may be text, dbm, Berkley DB or any database with a
  293. DBI compatible driver.  HTTPD::UserAdmin supports files used by the
  294. `Basic' and `Digest' authentication schemes.  Here's an example:</P>
  295. <PRE>
  296.     use HTTPD::UserAdmin ();
  297.     HTTPD::UserAdmin
  298.           ->new(DB => "/foo/.htpasswd")
  299.           ->add($username => $password);</PRE>
  300. <P>
  301. <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>
  302. <P>Read the CGI security FAQ, at
  303. <A HREF="http://www-genome.wi.mit.edu/WWW/faqs/www-security-faq.html,">http://www-genome.wi.mit.edu/WWW/faqs/www-security-faq.html,</A> and the
  304. Perl/CGI FAQ at
  305. <A HREF="http://www.perl.com/CPAN/doc/FAQs/cgi/perl-cgi-faq.html.">http://www.perl.com/CPAN/doc/FAQs/cgi/perl-cgi-faq.html.</A></P>
  306. <P>In brief: use tainting (see <A HREF="../../lib/Pod/perlsec.html">the perlsec manpage</A>), which makes sure that data
  307. from outside your script (eg, CGI parameters) are never used in
  308. <A HREF="../../lib/Pod/perlfunc.html#item_eval"><CODE>eval</CODE></A> or <A HREF="../../lib/Pod/perlfunc.html#item_system"><CODE>system</CODE></A> calls.  In addition to tainting, never use the
  309. single-argument form of <A HREF="../../lib/Pod/perlfunc.html#item_system"><CODE>system()</CODE></A> or exec().  Instead, supply the
  310. command and arguments as a list, which prevents shell globbing.</P>
  311. <P>
  312. <H2><A NAME="how do i parse a mail header">How do I parse a mail header?</A></H2>
  313. <P>For a quick-and-dirty solution, try this solution derived
  314. from page 222 of the 2nd edition of ``Programming Perl'':</P>
  315. <PRE>
  316.     $/ = '';
  317.     $header = <MSG>;
  318.     $header =~ s/\n\s+/ /g;      # merge continuation lines
  319.     %head = ( UNIX_FROM_LINE, split /^([-\w]+):\s*/m, $header );</PRE>
  320. <P>That solution doesn't do well if, for example, you're trying to
  321. maintain all the Received lines.  A more complete approach is to use
  322. the Mail::Header module from CPAN (part of the MailTools package).</P>
  323. <P>
  324. <H2><A NAME="how do i decode a cgi form">How do I decode a CGI form?</A></H2>
  325. <P>You use a standard module, probably CGI.pm.  Under no circumstances
  326. should you attempt to do so by hand!</P>
  327. <P>You'll see a lot of CGI programs that blindly read from STDIN the number
  328. of bytes equal to CONTENT_LENGTH for POSTs, or grab QUERY_STRING for
  329. decoding GETs.  These programs are very poorly written.  They only work
  330. sometimes.  They typically forget to check the return value of the <A HREF="../../lib/Pod/perlfunc.html#item_read"><CODE>read()</CODE></A>
  331. system call, which is a cardinal sin.  They don't handle HEAD requests.
  332. They don't handle multipart forms used for file uploads.  They don't deal
  333. with GET/POST combinations where query fields are in more than one place.
  334. They don't deal with keywords in the query string.</P>
  335. <P>In short, they're bad hacks.  Resist them at all costs.  Please do not be
  336. tempted to reinvent the wheel.  Instead, use the CGI.pm or CGI_Lite.pm
  337. (available from CPAN), or if you're trapped in the module-free land
  338. of perl1 .. perl4, you might look into cgi-lib.pl (available from
  339. <A HREF="http://cgi-lib.stanford.edu/cgi-lib/">http://cgi-lib.stanford.edu/cgi-lib/</A> ).</P>
  340. <P>Make sure you know whether to use a GET or a POST in your form.
  341. GETs should only be used for something that doesn't update the server.
  342. Otherwise you can get mangled databases and repeated feedback mail
  343. messages.  The fancy word for this is ``idempotency''.  This simply
  344. means that there should be no difference between making a GET request
  345. for a particular URL once or multiple times.  This is because the
  346. HTTP protocol definition says that a GET request may be cached by the
  347. browser, or server, or an intervening proxy.  POST requests cannot be
  348. cached, because each request is independent and matters.  Typically,
  349. POST requests change or depend on state on the server (query or update
  350. a database, send mail, or purchase a computer).</P>
  351. <P>
  352. <H2><A NAME="how do i check a valid mail address">How do I check a valid mail address?</A></H2>
  353. <P>You can't, at least, not in real time.  Bummer, eh?</P>
  354. <P>Without sending mail to the address and seeing whether there's a human
  355. on the other hand to answer you, you cannot determine whether a mail
  356. address is valid.  Even if you apply the mail header standard, you
  357. can have problems, because there are deliverable addresses that aren't
  358. RFC-822 (the mail header standard) compliant, and addresses that aren't
  359. deliverable which are compliant.</P>
  360. <P>Many are tempted to try to eliminate many frequently-invalid
  361. mail addresses with a simple regex, such as
  362. <CODE>/^[\w.-]+\@([\w.-]\.)+\w+$/</CODE>.  It's a very bad idea.  However,
  363. this also throws out many valid ones, and says nothing about
  364. potential deliverability, so is not suggested.  Instead, see
  365. <A HREF="http://www.perl.com/CPAN/authors/Tom_Christiansen/scripts/ckaddr.gz">http://www.perl.com/CPAN/authors/Tom_Christiansen/scripts/ckaddr.gz</A> ,
  366. which actually checks against the full RFC spec (except for nested
  367. comments), looks for addresses you may not wish to accept mail to
  368. (say, Bill Clinton or your postmaster), and then makes sure that the
  369. hostname given can be looked up in the DNS MX records.  It's not fast,
  370. but it works for what it tries to do.</P>
  371. <P>Our best advice for verifying a person's mail address is to have them
  372. enter their address twice, just as you normally do to change a password.
  373. This usually weeds out typos.  If both versions match, send
  374. mail to that address with a personal message that looks somewhat like:</P>
  375. <PRE>
  376.     Dear someuser@host.com,</PRE>
  377. <PRE>
  378.     Please confirm the mail address you gave us Wed May  6 09:38:41
  379.     MDT 1998 by replying to this message.  Include the string
  380.     "Rumpelstiltskin" in that reply, but spelled in reverse; that is,
  381.     start with "Nik...".  Once this is done, your confirmed address will
  382.     be entered into our records.</PRE>
  383. <P>If you get the message back and they've followed your directions,
  384. you can be reasonably assured that it's real.</P>
  385. <P>A related strategy that's less open to forgery is to give them a PIN
  386. (personal ID number).  Record the address and PIN (best that it be a
  387. random one) for later processing.  In the mail you send, ask them to
  388. include the PIN in their reply.  But if it bounces, or the message is
  389. included via a ``vacation'' script, it'll be there anyway.  So it's
  390. best to ask them to mail back a slight alteration of the PIN, such as
  391. with the characters reversed, one added or subtracted to each digit, etc.</P>
  392. <P>
  393. <H2><A NAME="how do i decode a mime/base64 string">How do I decode a MIME/BASE64 string?</A></H2>
  394. <P>The MIME-tools package (available from CPAN) handles this and a lot
  395. more.  Decoding BASE64 becomes as simple as:</P>
  396. <PRE>
  397.     use MIME::base64;
  398.     $decoded = decode_base64($encoded);</PRE>
  399. <P>A more direct approach is to use the <A HREF="../../lib/Pod/perlfunc.html#item_unpack"><CODE>unpack()</CODE></A> function's ``u''
  400. format after minor transliterations:</P>
  401. <PRE>
  402.     tr#A-Za-z0-9+/##cd;                   # remove non-base64 chars
  403.     tr#A-Za-z0-9+/# -_#;                  # convert to uuencoded format
  404.     $len = pack("c", 32 + 0.75*length);   # compute length byte
  405.     print unpack("u", $len . $_);         # uudecode and print</PRE>
  406. <P>
  407. <H2><A NAME="how do i return the user's mail address">How do I return the user's mail address?</A></H2>
  408. <P>On systems that support getpwuid, the $< variable and the
  409. Sys::Hostname module (which is part of the standard perl distribution),
  410. you can probably try using something like this:</P>
  411. <PRE>
  412.     use Sys::Hostname;
  413.     $address = sprintf('%s@%s', scalar getpwuid($<), hostname);</PRE>
  414. <P>Company policies on mail address can mean that this generates addresses
  415. that the company's mail system will not accept, so you should ask for
  416. users' mail addresses when this matters.  Furthermore, not all systems
  417. on which Perl runs are so forthcoming with this information as is Unix.</P>
  418. <P>The Mail::Util module from CPAN (part of the MailTools package) provides a
  419. <CODE>mailaddress()</CODE> function that tries to guess the mail address of the user.
  420. It makes a more intelligent guess than the code above, using information
  421. given when the module was installed, but it could still be incorrect.
  422. Again, the best way is often just to ask the user.</P>
  423. <P>
  424. <H2><A NAME="how do i send mail">How do I send mail?</A></H2>
  425. <P>Use the <CODE>sendmail</CODE> program directly:</P>
  426. <PRE>
  427.     open(SENDMAIL, "|/usr/lib/sendmail -oi -t -odq")
  428.                         or die "Can't fork for sendmail: $!\n";
  429.     print SENDMAIL <<"EOF";
  430.     From: User Originating Mail <me\@host>
  431.     To: Final Destination <you\@otherhost>
  432.     Subject: A relevant subject line</PRE>
  433. <PRE>
  434.     Body of the message goes here after the blank line
  435.     in as many lines as you like.
  436.     EOF
  437.     close(SENDMAIL)     or warn "sendmail didn't close nicely";</PRE>
  438. <P>The <STRONG>-oi</STRONG> option prevents sendmail from interpreting a line consisting
  439. of a single dot as ``end of message''.  The <STRONG>-t</STRONG> option says to use the
  440. headers to decide who to send the message to, and <STRONG>-odq</STRONG> says to put
  441. the message into the queue.  This last option means your message won't
  442. be immediately delivered, so leave it out if you want immediate
  443. delivery.</P>
  444. <P>Alternate, less convenient approaches include calling mail (sometimes
  445. called mailx) directly or simply opening up port 25 have having an
  446. intimate conversation between just you and the remote SMTP daemon,
  447. probably sendmail.</P>
  448. <P>Or you might be able use the CPAN module Mail::Mailer:</P>
  449. <PRE>
  450.     use Mail::Mailer;</PRE>
  451. <PRE>
  452.     $mailer = Mail::Mailer->new();
  453.     $mailer->open({ From    => $from_address,
  454.                     To      => $to_address,
  455.                     Subject => $subject,
  456.                   })
  457.         or die "Can't open: $!\n";
  458.     print $mailer $body;
  459.     $mailer->close();</PRE>
  460. <P>The Mail::Internet module uses Net::SMTP which is less Unix-centric than
  461. Mail::Mailer, but less reliable.  Avoid raw SMTP commands.  There
  462. are many reasons to use a mail transport agent like sendmail.  These
  463. include queueing, MX records, and security.</P>
  464. <P>
  465. <H2><A NAME="how do i read mail">How do I read mail?</A></H2>
  466. <P>While you could use the Mail::Folder module from CPAN (part of the
  467. MailFolder package) or the Mail::Internet module from CPAN (also part
  468. of the MailTools package), often a module is overkill, though.  Here's a
  469. mail sorter.</P>
  470. <PRE>
  471.     #!/usr/bin/perl
  472.     # bysub1 - simple sort by subject
  473.     my(@msgs, @sub);
  474.     my $msgno = -1;
  475.     $/ = '';                    # paragraph reads
  476.     while (<>) {
  477.         if (/^From/m) {
  478.             /^Subject:\s*(?:Re:\s*)*(.*)/mi;
  479.             $sub[++$msgno] = lc($1) || '';
  480.         }
  481.         $msgs[$msgno] .= $_;
  482.     }
  483.     for my $i (sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msgs)) {
  484.         print $msgs[$i];
  485.     }</PRE>
  486. <P>Or more succinctly,</P>
  487. <PRE>
  488.     #!/usr/bin/perl -n00
  489.     # bysub2 - awkish sort-by-subject
  490.     BEGIN { $msgno = -1 }
  491.     $sub[++$msgno] = (/^Subject:\s*(?:Re:\s*)*(.*)/mi)[0] if /^From/m;
  492.     $msg[$msgno] .= $_;
  493.     END { print @msg[ sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msg) ] }</PRE>
  494. <P>
  495. <H2><A NAME="how do i find out my hostname/domainname/ip address">How do I find out my hostname/domainname/IP address?</A></H2>
  496. <P>The normal way to find your own hostname is to call the <CODE>`hostname`</CODE>
  497. program.  While sometimes expedient, this has some problems, such as
  498. not knowing whether you've got the canonical name or not.  It's one of
  499. those tradeoffs of convenience versus portability.</P>
  500. <P>The Sys::Hostname module (part of the standard perl distribution) will
  501. give you the hostname after which you can find out the IP address
  502. (assuming you have working DNS) with a <A HREF="../../lib/Pod/perlfunc.html#item_gethostbyname"><CODE>gethostbyname()</CODE></A> call.</P>
  503. <PRE>
  504.     use Socket;
  505.     use Sys::Hostname;
  506.     my $host = hostname();
  507.     my $addr = inet_ntoa(scalar gethostbyname($host || 'localhost'));</PRE>
  508. <P>Probably the simplest way to learn your DNS domain name is to grok
  509. it out of /etc/resolv.conf, at least under Unix.  Of course, this
  510. assumes several things about your resolv.conf configuration, including
  511. that it exists.</P>
  512. <P>(We still need a good DNS domain name-learning method for non-Unix
  513. systems.)</P>
  514. <P>
  515. <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>
  516. <P>Use the Net::NNTP or News::NNTPClient modules, both available from CPAN.
  517. This can make tasks like fetching the newsgroup list as simple as:</P>
  518. <PRE>
  519.     perl -MNews::NNTPClient
  520.       -e 'print News::NNTPClient->new->list("newsgroups")'</PRE>
  521. <P>
  522. <H2><A NAME="how do i fetch/put an ftp file">How do I fetch/put an FTP file?</A></H2>
  523. <P>LWP::Simple (available from CPAN) can fetch but not put.  Net::FTP (also
  524. available from CPAN) is more complex but can put as well as fetch.</P>
  525. <P>
  526. <H2><A NAME="how can i do rpc in perl">How can I do RPC in Perl?</A></H2>
  527. <P>A DCE::RPC module is being developed (but is not yet available), and
  528. will be released as part of the DCE-Perl package (available from
  529. CPAN).  The rpcgen suite, available from CPAN/authors/id/JAKE/, is
  530. an RPC stub generator and includes an RPC::ONC module.</P>
  531. <P>
  532. <HR>
  533. <H1><A NAME="author and copyright">AUTHOR AND COPYRIGHT</A></H1>
  534. <P>Copyright (c) 1997-1999 Tom Christiansen and Nathan Torkington.
  535. All rights reserved.</P>
  536. <P>When included as part of the Standard Version of Perl, or as part of
  537. its complete documentation whether printed or otherwise, this work
  538. may be distributed only under the terms of Perl's Artistic License.
  539. Any distribution of this file or derivatives thereof <EM>outside</EM>
  540. of that package require that special arrangements be made with
  541. copyright holder.</P>
  542. <P>Irrespective of its distribution, all code examples in this file
  543. are hereby placed into the public domain.  You are permitted and
  544. encouraged to use this code in your own programs for fun
  545. or for profit as you see fit.  A simple comment in the code giving
  546. credit would be courteous but is not required.</P>
  547. <TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0 WIDTH=100%>
  548. <TR><TD CLASS=block VALIGN=MIDDLE WIDTH=100% BGCOLOR="#cccccc">
  549. <STRONG><P CLASS=block> perlfaq9 - Networking</P></STRONG>
  550. </TD></TR>
  551. </TABLE>
  552.  
  553. </BODY>
  554.  
  555. </HTML>
  556.