Interview Questions

How to write a simple client program using sockets and Perl ?

Perl, Sockets and TCP/IP Networking

(Continued from previous question...)

How to write a simple client program using sockets and Perl ?

Perl works well for writing prototypes or full-fledged applications because it is so complete. The language seldom needs to be extended to do the sorts of things you'd expect to do with C or C++ on a Linux system. One notable example is the Berkeley socket functions, which Perl included even back when the Internet was just a cool bit of technology rather than a global cultural phenomenon.

Sockets are a general-purpose inter-process communication (IPC) mechanism. When processes run on separate machines, they can employ sockets to communicate using Internet protocols. This is the basis for most Internet clients and servers. Many Internet protocols are based on exchanging simple text; so is much of the interesting content. Since Perl excels at processing text, it's ideal for writing applications like web servers or any type of client which parses or searches for text.

Sample Code:

   $domain = 2; # Internet domain
   $type = 1; # Sequenced, reliable, two-way connection, byte streams
   $proto = 6; # Transmission Control Protocol (TCP)
   $host = pack('C4', 127,0,0,1); # localhost =
   $port = 1024; 
   $address = pack('S n a4 x8', $domain, $port, $host);
   bind(SOCK, $address);
   print STDOUT "Client host: ",join('.',unpack('C4', $host)),"\n";
   print STDOUT "Client port: $port\n";
   $sHost = pack('C4', 127,0,0,1); # localhost =
   $sPort = 8888; 
   $sAddress = pack('S n a4 x8', $domain, $sPort, $sHost);
   connect(SOCK, $sAddress);
   print STDOUT "Server host: ",join('.',unpack('C4', $sHost)),"\n";
   print STDOUT "Server port: $sPort\n";
   select(SOCK); $| = 1; select(STDOUT);
   while ($m=<SOCK>) {
      print STDOUT $m;
      $m = <STDIN>;
      print SOCK $m;

Other Interview Questions