Socket

From Spectrum
Revision as of 21:07, 28 March 2008 by Winston (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

socket (HLCALL 0x3E00) - Create an end point for communication.

Synopsis

Assembly language

   ld c, socket_type
   ld hl, 0x3E00
   call HLCALL

C

int socket(int domain, int type, int protocol);

The socket function opens an end point for communication, and returns a file descriptor on success. Only AF_INET sockets are supported. In the C interface, the domain and protocol parameters are provided for compatibility with the BSD socket library and are ignored. The protocol parameter should be set to zero; it is very possible that the protocol parameter will be used in a later release of the library.

The socket function allocates the resources required to communicate. It allocates a descriptor ('socket handle'), and associates this with the appropriate hardware registers.

Return value

On success, a file descriptor for the new socket is returned in the A register (asm interface) or as the return code (C interface). On error, the asm interface returns the error code in A, and the C interface returns -1 and sets errno to the error number.

Examples

The following example shows how to open a socket that will be used for a TCP connection (either one that listens for incoming connections, or will be used to connect to a remote host). The socket() function just opens the socket - it doesn't decide whether it's to be used for a server or client connection. To open a UDP connection, the type parameter should be set to SOCK_DGRAM.

Assembly language:

ld c, SOCK_STREAM       ; A reliable stream - TCP
ld hl, SOCKET           ; Call table for socket() - 0x3E00
call HLCALL             ; Trigger ROM page in
bit 7, a                ; Check for a negative return code (MSB set)
jr nz, .handle_error    ; failed to allocate a socket if the return code < 0

; at this point, A contains the file descriptor (aka socket handle)

C:

int sock;
sock=socket(AF_INET, SOCK_STREAM, 0);
if(sock > 0)
{
   /* socket opened successfully, do something */
}
else
{
   /* handle the error */
}