Subsections

- 1 Types, Constants and variables :
- 2 Functions and Procedures
  - 1 Accept
  - 2 Accept
  - 3 Accept
  - 4 Accept
  - 5 Bind
  - 6 Bind
  - 7 Connect
  - 8 Connect
  - 9 Connect
  - 10 Connect
  - 11 GetPeerName
  - 12 GetSocketName
  - 13 GetSocketOptions
  - 14 Listen
  - 15 Recv
  - 16 Send
  - 17 SetSocketOptions
  - 18 Shutdown
  - 19 Sock2File
  - 20 Sock2Text
  - 21 Socket
  - 22 SocketPair
  - 23 Str2UnixSockAddr

# 20 The SOCKETS unit.

This chapter describes the SOCKETS unit for Free Pascal. it was written for LINUX by Michaël Van Canneyt, and ported to WINDOWS by Florian Klaempfl. The chapter is divided in 2 sections:

- The first section lists types, constants and variables from the interface part of the unit.
- The second section describes the functions defined in the unit.

# 1 Types, Constants and variables :

The following constants identify the different socket types, as needed in the Socket call.

    SOCK_STREAM     = 1; { stream (connection) socket   }
    SOCK_DGRAM      = 2; { datagram (conn.less) socket  }
    SOCK_RAW        = 3; { raw socket                   }
    SOCK_RDM        = 4; { reliably-delivered message   }
    SOCK_SEQPACKET  = 5; { sequential packet socket     }
    SOCK_PACKET     =10;

The following constants determine the socket domain, they are used in the Socket call.

    AF_UNSPEC       = 0;
    AF_UNIX         = 1; { Unix domain sockets          }
    AF_INET         = 2; { Internet IP Protocol         }
    AF_AX25         = 3; { Amateur Radio AX.25          }
    AF_IPX          = 4; { Novell IPX                   }
    AF_APPLETALK    = 5; { Appletalk DDP                }
    AF_NETROM       = 6; { Amateur radio NetROM         }
    AF_BRIDGE       = 7; { Multiprotocol bridge         }
    AF_AAL5         = 8; { Reserved for Werner's ATM    }
    AF_X25          = 9; { Reserved for X.25 project    }
    AF_INET6        = 10; { IP version 6                 }
    AF_MAX          = 12;

The following constants determine the protocol family, they are used in the Socket call.

    PF_UNSPEC       = AF_UNSPEC;
    PF_UNIX         = AF_UNIX;
    PF_INET         = AF_INET;
    PF_AX25         = AF_AX25;
    PF_IPX          = AF_IPX;
    PF_APPLETALK    = AF_APPLETALK;
    PF_NETROM       = AF_NETROM;
    PF_BRIDGE       = AF_BRIDGE;
    PF_AAL5         = AF_AAL5;
    PF_X25          = AF_X25;
    PF_INET6        = AF_INET6;
    PF_MAX          = AF_MAX;

The following types are used to store different kinds of eddresses for the Bind, Recv and Send calls.

    TSockAddr = packed Record
      family:word;
      data  :array [0..13] of char;
      end;
    TUnixSockAddr = packed Record
      family:word;
      path:array[0..108] of char;
      end;
    TInetSockAddr = packed Record
      family:Word;
      port  :Word;
      addr  :Cardinal;
      pad   :array [1..8] of byte;
      end;

The following type is returned by the SocketPair call.

    TSockArray = Array[1..2] of Longint;

# 2 Functions and Procedures

##
1 Accept

Declaration
  `Function Accept (Sock:Longint;Var Addr;Var Addrlen:Longint) : Longint;`

  ``

Description
  Accept accepts a connection from a socket `Sock`, which was listening for a connection. If a connection is accepted, a file descriptor is returned. On error `-1` is returned. The returned socket may NOT be used to accept more connections. The original socket remains open.

  The `Accept` call fills the address of the connecting entity in `Addr`, and sets its length in `Addrlen`. `Addr` should be pointing to enough space, and `Addrlen` should be set to the amount of space available, prior to the call.

Errors
  On error, `-1` is returned, and errors are reported in `SocketError`, and include the following:
  SYS_EBADF
    The socket descriptor is invalid.
  SYS_ENOTSOCK
    The descriptor is not a socket.
  SYS_EOPNOTSUPP
    The socket type doesn't support the `Listen` operation.
  SYS_EFAULT
    `Addr` points outside your address space.
  SYS_EWOULDBLOCK
    The requested operation would block the process.

See also
  Listen, Connect

Example

      Program server;

      {
        Program to test Sockets unit by Michael van Canneyt and Peter Vreman
        Server Version, First Run sock_svr to let it create a socket and then
        sock_cli to connect to that socket
      }

      uses Linux,Sockets;
      const
        SPath='ServerSoc';

      Var
        FromName : string;
        Buffer   : string[255];
        S        : Longint;
        Sin,Sout : Text;

      procedure perror (const S:string);
      begin
        writeln (S,SocketError);
        halt(100);
      end;

      begin
        S:=Socket (AF_UNIX,SOCK_STREAM,0);
        if SocketError<>0 then
         Perror ('Server : Socket : ');
        UnLink(SPath);
        if not Bind(S,SPath) then
         PError ('Server : Bind : ');
        if not Listen (S,1) then
         PError ('Server : Listen : ');
        Writeln('Waiting for Connect from Client, run now sock_cli in an other tty');
        if not Accept (S,FromName,Sin,Sout) then
         PError ('Server : Accept : '+fromname);
        Reset(Sin);
        ReWrite(Sout);
        Writeln(Sout,'Message From Server');
        Flush(SOut);
        while not eof(sin) do
         begin
           Readln(Sin,Buffer);
           Writeln('Server : read : ',buffer);
         end;
        Unlink(SPath);
      end.

##
2 Accept

Declaration
  `Function Accept (Sock:longint;var addr:string;var SockIn,SockOut:text) : Boolean;`

  ``

Description
  This is an alternate form of the Accept command. It is equivalent to subsequently calling the regular Accept function and the Sock2Text function. The function returns `True` if successfull, `False` otherwise.

Errors
  The errors are those of Accept.
See also
  Accept

##
3 Accept

Declaration
  `Function Accept (Sock:longint;var addr:string;var SockIn,SockOut:File) : Boolean;`

  ``

Description
  This is an alternate form of the Accept command. It is equivalent to subsequently calling the regular Accept function and the Sock2File function. The `Addr` parameter contains the name of the unix socket file to be opened. The function returns `True` if successfull, `False` otherwise.

Errors
  The errors are those of Accept.
See also
  Accept

##
4 Accept

Declaration
  `Function Accept (Sock:longint;var addr:TInetSockAddr;var SockIn,SockOut:File) : Boolean;`
Description
  This is an alternate form of the Accept command. It is equivalent to subsequently calling the regular Accept function and the Sock2File function. The `Addr` parameter contains the parameters of the internet socket that should be opened. The function returns `True` if successfull, `False` otherwise.

Errors
  The errors are those of Accept.
See also
  Accept

##
5 Bind

Declaration
  `Function Bind (Sock:Longint;Var Addr;AddrLen:Longint) : Boolean;`

  ``

Description
  Bind binds the socket `Sock` to address `Addr`. `Addr` has length `Addrlen`. The function returns `True` if the call was succesful, `False` if not.

Errors
  Errors are returned in `SocketError` and include the following:
  SYS_EBADF
    The socket descriptor is invalid.
  SYS_EINVAL
    The socket is already bound to an address,
  SYS_EACCESS
    Address is protected and you don't have permission to open it.
  More arrors can be found in the Unix man pages.

See also
  Socket

##
6 Bind

Declaration
  `Function Bind (Sock:longint;const addr:string) : boolean;`

  ``

Description
  This is an alternate form of the `Bind` command. This form of the `Bind` command is equivalent to subsequently calling Str2UnixSockAddr and the regular Bind function. The function returns `True` if successfull, `False` otherwise.

Errors
  Errors are those of the regular Bind command.
See also
  Bind

##
7 Connect

Declaration
  `Function Connect (Sock:Longint;Var Addr;Addrlen:Longint) : Longint;`

  ``

Description
  Connect opens a connection to a peer, whose address is described by `Addr`. `AddrLen` contains the length of the address. The type of `Addr` depends on the kind of connection you're trying to make, but is generally one of `TSockAddr` or `TUnixSockAddr`.

  The `Connect` function returns a file descriptor if the call was successfull, `-1` in case of error.

Errors
  On error, `-1` is returned and errors are reported in `SocketError`.
See also
  Listen, Bind,Accept

Example

      Program Client;

      {
        Program to test Sockets unit by Michael van Canneyt and Peter Vreman
        Client Version, First Run sock_svr to let it create a socket and then
        sock_cli to connect to that socket
      }

      uses Sockets,Linux;

      procedure PError(const S : string);
      begin
        writeln(S,SocketError);
        halt(100);
      end;

      Var
        Saddr    : String[25];
        Buffer   : string [255];
        S        : Longint;
        Sin,Sout : Text;
        i        : integer;
      begin
        S:=Socket (AF_UNIX,SOCK_STREAM,0);
        if SocketError<>0 then
         Perror('Client : Socket : ');
        Saddr:='ServerSoc';
        if not Connect (S,SAddr,Sin,Sout) then
         PError('Client : Connect : ');
        Reset(Sin);
        ReWrite(Sout);
        Buffer:='This is a textstring sent by the Client.';
        for i:=1 to 10 do
         Writeln(Sout,Buffer);
        Flush(Sout);
        Readln(SIn,Buffer);
        WriteLn(Buffer);
        Close(sout);
      end.

##
8 Connect

Declaration
  `Function Connect (Sock:longint;const addr:string;var SockIn,SockOut:text) : Boolean;`

  ``

Description
  This is an alternate form of the Connect command. It is equivalent to subsequently calling the regular Connect function and the Sock2Text function. The function returns `True` if successfull, `False` otherwise.

Errors
  The errors are those of Connect.
See also
  Connect

##
9 Connect

Declaration
  `Function Connect (Sock:longint;const addr:string;var SockIn,SockOut:file) : Boolean;`

  ``

Description
  This is an alternate form of the Connect command. The parameter `addr` contains the name of the unix socket file to be opened. It is equivalent to subsequently calling the regular Connect function and the Sock2File function. The function returns `True` if successfull, `False` otherwise.

Errors
  The errors are those of Connect.
See also
  Connect

##
10 Connect

Declaration
  `Function Connect (Sock:longint;const addr: TInetSockAddr;var SockIn,SockOut:file) : Boolean;`

  ``

Description
  This is another alternate form of the Connect command. It is equivalent to subsequently calling the regular Connect function and the Sock2File function. The `Addr` parameter contains the parameters of the internet socket to connect to. The function returns `True` if successfull, `False` otherwise.

Errors
  The errors are those of Connect.
See also
  Connect

Example

      program pfinger;

      uses sockets,errors;

      Var Addr : TInetSockAddr;
       S : Longint;
          Sin,Sout : Text;
          Line : string;

      begin
        Addr.family:=AF_INET;
        { port 79 in network order }
        Addr.port:=79 shl 8;
        { localhost : 127.0.0.1 in network order }
        Addr.addr:=((1 shl 24) or 127);
        S:=Socket(AF_INET,SOCK_STREAM,0);
        If Not Connect (S,ADDR,SIN,SOUT) Then
          begin
          Writeln ('Couldn''t connect to localhost');
          Writeln ('Socket error : ',strerror(SocketError));
          halt(1);
          end;
        rewrite (sout);
        reset(sin);
        writeln (sout,paramstr(1));
        flush(sout);
        while not eof(sin) do
          begin
          readln (Sin,line);
          writeln (line);
          end;
        Shutdown(s,2);
        close (sin);
        close (sout);
      end.

##
11 GetPeerName

Declaration
  `Function GetPeerName (Sock:Longint;Var Addr;Var Addrlen:Longint) : Longint;`

  ``

Description
  GetPeerName returns the name of the entity connected to the specified socket `Sock`. The Socket must be connected for this call to work. `Addr` should point to enough space to store the name, the amount of space pointed to should be set in `Addrlen`. When the function returns succesfully, `Addr` will be filled with the name, and `Addrlen` will be set to the length of `Addr`.

Errors
  Errors are reported in `SocketError`, and include the following:
  SYS_EBADF
    The socket descriptor is invalid.
  SYS_ENOBUFS
    The system doesn't have enough buffers to perform the operation.
  SYS_ENOTSOCK
    The descriptor is not a socket.
  SYS_EFAULT
    `Addr` points outside your address space.
  SYS_ENOTCONN
    The socket isn't connected.

See also
  Connect, Socket, `connect` (2)

##
12 GetSocketName

Declaration
  `Function GetSocketName (Sock:Longint;Var Addr;Var Addrlen:Longint) : Longint;`

  ``

Description
  GetSockName returns the current name of the specified socket `Sock`. `Addr` should point to enough space to store the name, the amount of space pointed to should be set in `Addrlen`. When the function returns succesfully, `Addr` will be filled with the name, and `Addrlen` will be set to the length of `Addr`.
Errors
  Errors are reported in `SocketError`, and include the following:
  SYS_EBADF
    The socket descriptor is invalid.
  SYS_ENOBUFS
    The system doesn't have enough buffers to perform the operation.
  SYS_ENOTSOCK
    The descriptor is not a socket.
  SYS_EFAULT
    `Addr` points outside your address space.

See also
  Bind

##
13 GetSocketOptions

Declaration
  `Function GetSocketOptions (Sock,Level,OptName:Longint;Var OptVal;optlen:longint) : Longint;`

  ``

Description
  GetSocketOptions gets the connection options for socket `Sock`. The socket may be obtained from different levels, indicated by `Level`, which can be one of the following:
  SOL_SOCKET
    From the socket itself.
  XXX
    set `Level` to `XXX`, the protocol number of the protocol which should interprete the option.
  For more information on this call, refer to the unix manual page `getsockopt` (2) .

Errors
  Errors are reported in `SocketError`, and include the following:
  SYS_EBADF
    The socket descriptor is invalid.
  SYS_ENOTSOCK
    The descriptor is not a socket.
  SYS_EFAULT
    `OptVal` points outside your address space.

See also
  GetSocketOptions

##
14 Listen

Declaration
  `Function Listen (Sock,MaxConnect:Longint) : Boolean;`

  ``

Description
  Listen listens for up to `MaxConnect` connections from socket `Sock`. The socket `Sock` must be of type `SOCK_STREAM` or `Sock_SEQPACKET`. The function returns `True` if a connection was accepted, `False` if an error occurred.

Errors
  Errors are reported in `SocketError`, and include the following:
  SYS_EBADF
    The socket descriptor is invalid.
  SYS_ENOTSOCK
    The descriptor is not a socket.
  SYS_EOPNOTSUPP
    The socket type doesn't support the `Listen` operation.

See also
  Socket, Bind, Connect

##
15 Recv

Declaration
  `Function Recv (Sock:Longint;Var Addr;AddrLen,Flags:Longint) : Longint;`

  ``

Description
  Recv reads at most `Addrlen` bytes from socket `Sock` into address `Addr`. The socket must be in a connected state. `Flags` can be one of the following:
  1
    : Process out-of band data.
  4
    : Bypass routing, use a direct interface.
  ??
    : Wait for full request or report an error.
  The functions returns the number of bytes actually read from the socket, or -1 if a detectable error occurred.
Errors
  Errors are reported in `SocketError`, and include the following:
  SYS_EBADF
    The socket descriptor is invalid.
  SYS_ENOTCONN
    The socket isn't connected.
  SYS_ENOTSOCK
    The descriptor is not a socket.
  SYS_EFAULT
    The address is outside your address space.
  SYS_EMSGSIZE
    The message cannot be sent atomically.
  SYS_EWOULDBLOCK
    The requested operation would block the process.
  SYS_ENOBUFS
    The system doesn't have enough free buffers available.

See also
  Send

##
16 Send

Declaration
  `Function Send (Sock:Longint;Var Addr;AddrLen,Flags:Longint) : Longint;`

  ``

Description
  Send sends `AddrLen` bytes starting from address `Addr` to socket `Sock`. `Sock` must be in a connected state. The function returns the number of bytes sent, or -1 if a detectable error occurred. `Flags` can be one of the following:
  1
    : Process out-of band data.
  4
    : Bypass routing, use a direct interface.

Errors
  Errors are reported in `SocketError`, and include the following:
  SYS_EBADF
    The socket descriptor is invalid.
  SYS_ENOTSOCK
    The descriptor is not a socket.
  SYS_EFAULT
    The address is outside your address space.
  SYS_EMSGSIZE
    The message cannot be sent atomically.
  SYS_EWOULDBLOCK
    The requested operation would block the process.
  SYS_ENOBUFS
    The system doesn't have enough free buffers available.

See also
  Recv, `send` (2)

##
17 SetSocketOptions

Declaration
  `Function SetSocketOptions (Sock,Level,OptName:Longint;Var OptVal;optlen:longint) : Longint;`

  ``

Description
  SetSocketOptions sets the connection options for socket `Sock`. The socket may be manipulated at different levels, indicated by `Level`, which can be one of the following:
  SOL_SOCKET
    To manipulate the socket itself.
  XXX
    set `Level` to `XXX`, the protocol number of the protocol which should interprete the option.
  For more information on this call, refer to the unix manual page `setsockopt` (2) .

Errors
  Errors are reported in `SocketError`, and include the following:
  SYS_EBADF
    The socket descriptor is invalid.
  SYS_ENOTSOCK
    The descriptor is not a socket.
  SYS_EFAULT
    `OptVal` points outside your address space.

See also
  GetSocketOptions

##
18 Shutdown

Declaration
  `Function Shutdown (Sock:Longint;How:Longint) : Longint;`

  ``

Description
  ShutDown closes one end of a full duplex socket connection, described by `Sock`. `How` determines how the connection will be shut down, and can be one of the following:
  0
    : Further receives are disallowed.
  1
    : Further sends are disallowed.
  2
    : Sending nor receiving are allowed.
  On succes, the function returns 0, on error -1 is returned.

Errors
  `SocketError` is used to report errors, and includes the following:
  SYS_EBADF
    The socket descriptor is invalid.
  SYS_ENOTCONN
    The socket isn't connected.
  SYS_ENOTSOCK
    The descriptor is not a socket.

See also
  Socket, Connect

##
19 Sock2File

Declaration
  `Procedure Sock2File (Sock:Longint;Var SockIn,SockOut:File);`

  ``

Description
  Sock2File transforms a socket `Sock` into 2 Pascal file descriptors of type `File`, one for reading from the socket (`SockIn`), one for writing to the socket (`SockOut`).
Errors
  None.
See also
  Socket, Sock2Text

##
20 Sock2Text

Declaration
  `Procedure Sock2Text (Sock:Longint;Var SockIn,SockOut: Text);`

  ``

Description
  Sock2Text transforms a socket `Sock` into 2 Pascal file descriptors of type `Text`, one for reading from the socket (`SockIn`), one for writing to the socket (`SockOut`).
Errors
  None.
See also
  Socket, Sock2File

##
21 Socket

Declaration
  `Function Socket (Domain,SocketType,Protocol:Longint) : Longint;`

  ``

Description
  Socket creates a new socket in domain `Domain`, from type `SocketType` using protocol `Protocol`. The Domain, Socket type and Protocol can be specified using predefined constants (see the section on constants for available constants) If succesfull, the function returns a socket descriptor, which can be passed to a subsequent Bind call. If unsuccesfull, the function returns -1.

Errors
  Errors are returned in `SocketError`, and include the follwing:
  SYS_EPROTONOSUPPORT
    The protocol type or the specified protocol is not supported within this domain.
  SYS_EMFILE
    The per-process descriptor table is full.
  SYS_ENFILE
    The system file table is full.
  SYS_EACCESS
    Permission to create a socket of the specified type and/or protocol is denied.
  SYS_ENOBUFS
    Insufficient buffer space is available. The socket cannot be created until sufficient resources are freed.
See also
  SocketPair, `socket` (2)

for an example, see Accept.

##
22 SocketPair

Declaration
  `Function SocketPair (Domain,SocketType,Protocol:Longint;var Pair:TSockArray) : Longint;`
Description
  SocketPair creates 2 sockets in domain `Domain`, from type `SocketType` and using protocol `Protocol`. The pair is returned in `Pair`, and they are indistinguishable. The function returns -1 upon error and 0 upon success.
Errors
  Errors are reported in `SocketError`, and are the same as in Socket
See also
  Str2UnixSockAddr

##
23 Str2UnixSockAddr

Declaration
  `Procedure Str2UnixSockAddr(const addr:string;var t:TUnixSockAddr;var len:longint)`
Description
  Str2UnixSockAddr transforms a Unix socket address in a string to a `TUnixSockAddr` structure which can be passed to the Bind call.
Errors
  None.
See also
  Socket, Bind