Hello,

Question regarding the connect function (in Socket), how to specify a specific port? The function only accepts two arguments, the socket and the ip. I have multiple devices on the same ip but different ports that I need to connect to, how to do this in Perl?

Thanks.

Hi ,.

I think there is no way in specify port in connect function. But In IO::Socket module we can specify the port no like,

In server.pl

my $main_sock = new IO::Socket::INET (LocalHost => '192.168.8.20',
    LocalPort => 1200,
    Listen    => 5,
    Proto     => 'tcp',
    Reuse     => 1,
);

die "Socket could not be created. Reason: $!\n" unless ($main_sock);

In client.pl
# Create a socket.
my $main_sock = new IO::Socket::INET (PeerAddr => '192.168.8.20',
    PeerPort => 1200,
    Proto     => 'tcp',
);

# Error then exit with error message.
die "Socket could not be created. Reason: $!\n" unless ($main_sock);

Note:
In IO::Socket module there is no need of connect function at all.

Try it. If it is not working Please revert me back.

I certainly agree with "abinila" that there is a crisp way in IO::Socket. But isnt there a way in to use the port # in Connect function indirectly? How about the following sample?

#!/usr/bin/perl -w
    use strict;
    use Socket;
    
    my ($remote,$port, $iaddr, $paddr, $proto, $line);
    
    $remote  = shift || 'localhost';
    $port    = shift || 2345;  # random port    
    
    if ($port =~ /\D/) {
    	$port = getservbyname($port, 'tcp')
    }    die "No port" unless $port;
    
    $iaddr   = inet_aton($remote) || die "no host: $remote";
    $paddr   = sockaddr_in($port, $iaddr);
    $proto   = getprotobyname('tcp');
    
    socket(SOCK, PF_INET, SOCK_STREAM, $proto) || die "socket: $!";
    
    connect(SOCK, $paddr) || die "connect: $!";
    
    while (defined($line = <SOCK>)) {
    	print $line;
    }
    
    close (SOCK) || die "close: $!";
    
    exit;

We are embedding the portnumber to $paddr. Wont this work?

Thanks,
~RDX~

Hi rdxblast,I agree with your answer.Yeah,we can give port number indirectly to connect function.I thought that Iteckid asking is there any way to directly give port number as an argument to connect function.That's why,I meant that there is no specific way to directly.I gave an another way as giving the port number informations using IO::Socket.

This article has been dead for over six months. Start a new discussion instead.