" />

mikerochford.com Being technical

27May/090

Connecting to a machine using sockets

I work with a api system that connects on a high port. My co-work Matt came up with a great way to set the socket up and verify if the socket isn’t stale. This sub-routine is specific to the api but you can use the theory and apply it to pretty much your socket needs.

sub cp_connect {
     ###############
     #
     # This function connects to a cp server
     #
     # Accepts:
     # $remote_host The server to connect to
     # $remote_port The port to connect to
     #
     # Returns:
     # A critical Path mail server socket connection.
     #
     ###############

     my $remote_host = shift;
     my $remote_port = shift;
     my $remote_password = shift;
     my $remote_conneciton_type = shift;
     my $EOL = shift;

     if($remote_conneciton_type =~ m/^rw$/){
          $remote_password = $remote_password ." write";
     }
     
     my $socket = IO::Socket::INET->new(
          PeerAddr => $remote_host,
          PeerPort        => $remote_port,
          Proto           => "tcp",
          Type            => SOCK_STREAM,
          Timeout         => 5 )
          || die "Couldn’t open socket!\n\n";

     my $answer = <$socket>;
     print $socket "LOGIN $remote_password" . $EOL;
     $answer = <$socket>;
     if ($answer !~ /^OK/) {
          print "Failed to login to $remote_host : $remote_port : $answer\n\n";
          exit(1);
     }
     return $socket;
}
 

Once you have the understanding of how the sub-routine works. Building a script that interacts with the api is a piece of cake.

Here is an example of how we use the sub-routine in a script. This example will check to see if the socket is defined, if not it will try to connect and define the socket. Once the socket is defined it will issue a command and read the socket.

if(!defined $socket) {
    $socket = cp_connect($remote_host, $remote_port, $remote_rwpass,"rw",$EOL);
}
print $socket "DOMAIN ENUMERATE". $EOL;
while (defined (chomp($answer = <$socket>))){
    if($answer =~ /\*\s+(.+)\s/) {
        $domains{$1}{‘users’} = ();
    }
    elsif($answer =~ /^ERROR/){
        $error = $answer;
        return 0;
        last;
    }
    elsif($answer =~ /OK/) {
        return 1;
        last;
    }
}
 

Popularity: 6% [?]

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)

No trackbacks yet.