Daniel
Daniel

Reputation: 641

Why does my Perl server fail to bind to port 80?

I copied the following script and run it to have it listen on port 80. But netstat doesn't show port 80. Why does netstat not sow it, or the Perl script is not correct?

#!/usr/bin/perl -w
use Socket;
use IO::Handle; 

$port=80; 
$host='localhost'; 
$packhost=inet_aton($host); 
$address=sockaddr_in($port,$packhost); 

socket(SERVER,AF_INET,SOCK_STREAM,getprotobyname('tcp')); 
bind(SERVER,$address); 
listen(SERVER,10); 

while( 1 ) {
    next unless (accept(CLIENT,SERVER)); 
    CLIENT->autoflush(1); 
    $msg_out="WHAT DO YOU WANT?\n"; 
    send(CLIENT,$msg_out,0); 
    close CLIENT;
} 

close SERVER; 
exit 1;

Upvotes: 0

Views: 2937

Answers (3)

Daniel
Daniel

Reputation: 641

Sorry, my fault, when I run netstat, I didn't put the option -a. When use netstat -a, it shows that port.

Upvotes: 0

Sinan Ünür
Sinan Ünür

Reputation: 118166

What platform are you on? How are you invoking netstat?

On Windows XP, after running the script with admin privileges, netstat -a gives me:

TCP    aardvarkvi:http        aardvarkvi:0           LISTENING

Binding to ports below 1024 requires root privileges on *nix systems. Since you do not (or, shall I say, code you seem to have blindly copied does not) check the return values of various calls, you would not know if they failed.

In general, you should not have to use Socket.pm. Stick with IO::Socket and avoid blindly copying code without knowing what it does.

You might also want to look into HTTP::Daemon.

Upvotes: 3

kdgregory
kdgregory

Reputation: 39606

It's likely that netstat is replacing the numeric port number by the name from /etc/services. For example:

    ~, 503> netstat -a | more
    Active Internet connections (servers and established)
    Proto Recv-Q Send-Q Local Address           Foreign Address         State
    tcp        0      0 *:svn                   *:*                     LISTEN

One thing that you can do is grep netstat's output to find all sockets where it's listening:

    netstat -a | grep LISTEN | grep tcp

You can also tell netstat to show numeric addresses rather than doing a hostname or services lookup (and there's another option where you can limit just port numbers; do man netstat):

    netstat -an | grep LISTEN | grep tcp

Upvotes: 0

Related Questions