Interview Questions

How to use "socket" function ?

Perl, Sockets and TCP/IP Networking


(Continued from previous question...)

How to use "socket" function ?

A client program must first call socket to get a socket descriptor or, in the case of Perl, a file handle. This function specifies a particular communications protocol to use and sets up an endpoint for communication--that is, a place to plug in a connection--a ``socket'', for lack of a better term. The syntax of this function is:

socket SOCKET, DOMAIN, TYPE, PROTOCOL

SOCKET is the file handle. DOMAIN and TYPE are integers that specify the address domain (or family) and the socket type. In Perl 4, you had to set these numbers explicitly, but Perl 5 defines them in the Socket module. To access the Socket module, add the following line to the top of your program:

use Socket;

For Internet applications, set DOMAIN to AF_INET (usually 2) and TYPE to SOCK_STREAM (usually 1). This basically means the address of the server will have the familiar Internet form (e.g., 192.42.55.55) and you'll read from and write to the socket like any I/O stream. You can set the PROTOCOL argument to 0 for most applications, but it's easy to get the correct value with the getprotobyname function.

(Continued on next question...)

Other Interview Questions