in reply to Problem with Socket Programming Perl Script

accept is for listening sockets, i.e. servers. Your constructor usage, however, looks like you want to connect to an existing service.  This is why the accept call fails and returns undef.  (If you had checked for errors, you'd have gotten "Invalid argument" in $!)

See perlipc for examples of client-side code.

Replies are listed 'Best First'.
Re^2: Problem with Socket Programming Perl Script
by ashok.g (Beadle) on Jan 24, 2011 at 10:47 UTC
    After modifications my script will look like
    #usr/bin/perl use strict; use warnings; use IO::Socket; $| = 1; my $client; my $socket= new IO::Socket::INET( LocalPort => '4500', Proto => 'tcp', Listen => 1, Reuse => 1 ); die "Couln't open socket: $!" unless $socket; while(1) { $client = $socket->accept() or die sprintf "ERRRR(%d)(%s)(%d)( +%s)", $!,$!,$^E,$^E; print "Socket Accepted:$client....\n"; $client->autoflush(1); my $addr = $client->peerhost(); my $port = $client->peerport(); print "Got Connection from \"$addr\" at port $port\n"; while( <$client> ) { print "$client" } }
    When I run this script I'm getting the error as
    Couln't open socket: Address already in use at servertest.pl line 14. FYR
    [root@station34 Socket]# netstat -anp | grep 4500 tcp 0 0 192.168.0.34:4500 0.0.0.0:* + LISTEN 22948/nco_objserv tcp 0 0 192.168.0.34:32997 192.168.0.34:4500 + ESTABLISHED 22990/nco_p_syslog tcp 0 0 192.168.0.34:32996 192.168.0.34:4500 + ESTABLISHED 22991/nco_p_mttrapd tcp 0 0 192.168.0.34:4500 192.168.0.34:32997 + ESTABLISHED 22948/nco_objserv tcp 0 0 192.168.0.34:4500 192.168.0.34:32996 + ESTABLISHED 22948/nco_objserv unix 2 [ ACC ] STREAM LISTENING 4500 1934/gpm + /dev/gpmctl
      tcp        0      0 192.168.0.34:4500           0.0.0.0:*                   LISTEN      22948/nco_objserv

      As you've confirmed yourself, the socket/port is already in use by another process, which is why you get the "Address already in use" error.  You need to kill that process if you want to start another one listening on the same port.

      The Reuse => 1 option only means that the socket is immediately being freed for reuse when the process exists, not that you can have several processes listening on the same socket (in case that's what you thought).

      (I'm a little confused as to what exactly you're trying to do. Your first post looked like you wanted to connect to an existing service. Now it seems you want to write one yourself, but there's already nco_objserv listening on that port...(?))

        I'm confused by "The Reuse => 1 option only means that the socket is immediately being freed for reuse when the process exists" Do you mean "when the process exits"?
        See,
        nco_objserv is the process which send the data via port 4500.
        So, I need to catch that data. If I kill that process then I won't have any data on that port.
        In this scenario how can I achieve this functionality?