# Programmer's Reference/Sockets

## INTRODUCTION

Introduction to socket system calls and error numbers

#### Syntax

    #include <sys/errno.h>

#### Description

This section describes all of the socket system calls used by NetCon. All of these system calls are accessible from the socket library, libsocket. The link editor ld(M) and the C compiler cc search this library under the `-lsocket' option. Most of these calls have one or more error returns, and some of the error codes are socket specific. An error condition is indicated by an otherwise impossible return value. This is almost always -1; the individual descriptions specify the details. Note that a number of system calls overload the meanings of these error numbers, and that the meanings must be interpreted according to the type and circumstances of the call.

As with normal arguments, all return codes and values from functions are of type integer unless otherwise noted. An error number is also made available in the external variable errno, which is not cleared on successful calls. Thus errno should be tested only after an error has occurred.

The following is a complete list of the socket errors and their names as given in < sys/errno.h >. See the standard System V manual page for intro for additional error codes.

> 63 ENOBUFS - No buffer space available

> An operation on a socket or pipe was not performed because the system lacked sufficient buffer space or because a queue was full. ENOBUFS is defined to have the same value as ENOSR.

> 90 TCPERR

or

> 90 IPXERR

> The starting value of socket related error codes.

> 90 EWOULDBLOCK - Operation would block

> An operation that would cause a process was attempted on an object in non-blocking mode (see fcntl(S)).

> 91 EINPROGRESS - Operation now in progress

> An operation that takes a long time to complete (such as a connect()) was attempted on a non-blocking object (see fcntl(S)).

> 92 EALREADY - Operation already in progress

> An operation was attempted on a non-blocking object that already had an operation in progress.

> 93 ENOTSOCK - Socket operation on non-socket

> Self-explanatory

> 94 EDESTADDRREQ - Destination address required

> A required address was omitted from an operation on a socket.

> 95 EMSGSIZE - Message too long

> A message sent on a socket was larger than the internal message buffer or some other network limit.

> 96 EPROTOTYPE - Protocol wrong type for socket

> A protocol was specified that does not support the semantics of the socket type requested. For example, you cannot use the ARPA Internet UDP protocol with type SOCK_STREAM.

> 97 EPROTONOSUPPORT - Protocol not supported

> The protocol has not been configured into the system or no implementation for it exists.

> 98 ESOCKTNOSUPPORT - Socket type not supported

> The support for the socket type has not been configured into the system or no implementation for it exists.

> 99 EOPNOTSUPP - Operation not supported on socket

> For example, trying to accept a connection on a datagram socket.

> 100 EPFNOSUPPORT - Protocol family not supported

> The protocol family has not been configured into the system or no implementation for it exists.

> 101 EAFNOSUPPORT - Address family not supported by protocol family

> An address incompatible with the requested protocol was used. For example, you shouldn't necessarily expect to be able to use NS addresses with ARPA Internet protocols.

> 102 EADDRINUSE - Address already in use

> Only one usage of each address is normally permitted.

> 103 EADDRNOTAVAIL - Can't assign requested address

> Normally results from an attempt to create a socket with an address not on this machine.

> 104 ENETDOWN - Network is down

> A socket operation encountered a dead network.

> 105 ENETUNREACH - Network is unreachable

> A socket operation was attempted to an unreachable network.

> 106 ENETRESET - Network dropped connection on reset

> The host you were connected to crashed and rebooted.

> 107 ECONNABORTED - Software caused connection abort

> A connection abort was caused internal to your host machine.

> 108 ECONNRESET - Connection reset by peer

> A connection was forcibly closed by a peer. This normally results from a loss of the connection on the remote socket due to a timeout or a reboot.

> 109 unused

> 110 EISCONN - Socket is already connected

> A connect request was made on an already connected socket; or a sendto or sendmsg request on a connected socket specified a destination when already connected.

> 111 ENOTCONN - Socket is not connected

> An request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket) no address was supplied.

> 112 ESHUTDOWN - Can't send after socket shutdown

> A request to send data was disallowed because the socket had already been shut down with a previous shutdown(SSC) call.

> 113 unused

> 114 ETIMEDOUT - Connection timed out

> A connect or send request failed because the connected party did not properly respond after a period of time. (The timeout period is dependent on the communication protocol.) Usually the wrong IPX network address

> 115 ECONNREFUSED - Connection refused

> No connection could be made because the target machine actively refused it. This usually results from trying to connect to a service that is inactive on the foreign host or the wrong IPX network address has been configured.

> 116 EHOSTDOWN - Host is down

> A socket operation failed because the destination host was down.

> 117 EHOSTUNREACH - Host is unreachable

> A socket operation was attempted to an unreachable host. This usally results from a bad entry in netcpasswd file.

> 118 ENOPROTOOPT - Option not supported by protocol

> A bad option or level was specified in a getsockopt or setsockopt call.

#### Files

    /usr/lib/libsocket.a

#### Definitions

Socket Descriptor

> An integer assigned by the system when a socket is referenced by dup(S), or when a socket is created by socket, which uniquely identifies an access path to that socket from a given process or any of its children.

Sockets and Address Families

> A socket is an endpoint for communication between processes. Each socket has queues for sending and receiving data.

> Sockets is an endpoint for communication between processes. Each socket has queues for sending and receiving data.

> Sockets are typed according to their communications properties. These properties include whether messages sent and received at a socket require the name of the partner, whether communication is reliable, the format used in naming message recipients, etc.

> Each instance of the system supports some collection of socket types; consult socket for more information about the types available and their properties.

> Each instance of the system supports some number of sets of communications protocols. Each protocol set supports addresses of a certain format. An Address Family is the set of addresses for a specific group of protocols. Each socket has an address chosen from the address family in which the socket was created.

#### See Also

intro()

#### List of Functions

Name Appears on Page Description

accept ACCEPT accept a connection on a socket

bind BIND bind a name to a socket

connect CONNECT initiate a connection on a socket

getpeername GETPEERNAME get name of connected peer

get sockname GETSOCKNAME get socket name

getsockopt GETSOCKOPT get and set options on sockets

listen LISTEN listen for connections on a socket

recv RECV receive a message from a socket

recvfrom RECV receive a message from a socket

select SELECT synchronous I/O multiplexing

send SEND send a message from a socket

sendto SENT send a message from a socket

setsockopt GETSOCKOPT get and set options on sockets

shutdown SHUTDOWN shut down part of a full-duplex connection

socket SOCKET create an endpoint for communication

## accept

Accept a connection on a socket

#### Syntax

    #include <sys/types.h>
    #include <socket.h>
    #include "ns.h"

    int accept(s, addr, addrlen)
    int s;
    struct sockaddr_ns *addr;
    int *addrlen;

#### Description

accept accepts a connection on a socket. The argument s is a socket which has been created with socket, bound to an address with bind, and is listening for connections after a listen. accept extracts the first connection on the queue of pending connections, creates a new socket with the same properties of s and allocates a new file descriptor for the socket. If no pending connections are present on the queue, and the socket is not marked as non-blocking, accept blocks the caller until a connection is present. If the socket is marked non-blocking and no pending connections are present on the queue, accept returns an error as described below. The accepted socket, ns, may not be used to accept more connections. The original socket s remains open.

The argument addr is a result parameter which is filled in with the address of the connecting entity, as known to the communications layer. The exact format of the addr parameter is determined by the communications domain [see protocols]. The addrlen is a value-result parameter; it should initially contain the amount of space pointed to by addr; on return it will contain the actual length (in bytes) of the address returned. This call is used with connection-based socket types, currently with SOCK_STREAM.

#### Return Value

The call returns -1 on error. If it succeeds it returns a non-negative integer which is a descriptor for the accepted socket (ns, described above).

#### Errors

The accept will fail if:

`[EBADF] The descriptor is invalid.`

[ENOTSOCK] The descriptor references a file, not a socket.

[EOPNOTSUPP] The referenced socket is not of type SOCK_STREAM.

[EFAULT] The addr parameter is not in a writable part of the user address space.

#### See Also

bind, connect, intro, listen, socket

## bind

Bind a name to a socket

#### Syntax

    #include <sys/types.h>
    #include <sys/socket.h>
    #include "ns.h"

    int bind (s, name, namelen)
    int s;
    struct sockaddr_ns *name;
    int namelen;

#### Description

bind assigns a name to an unnamed socket. When a socket is created with socket, it exists in a name space (address family) but has no name assigned. (Currently, only the Internet address family is supported.) bind requests that name be assigned to the socket.

#### Notes

The rules used in name binding vary between communication domains [see protocols].

#### Return Value

If the bind is successful, a 0 value is returned. A return value of -1 indicates an error, which is further specified in the global errno.

#### Errors

The bind call will fail if:

`[EBADF] S is not a valid descriptor.`

[ENOTSOCK] S is not a socket.

[EADDRNOTAVAIL] The specified address is not available from the local machine.

[EADDRINUSE] The specified address is already in use.

[EINVAL] The socket is already bound to an address.

[EACCESS] The requested address is protected, and the current user has inadequate permission to access it.

[EFAULT] The name parameter is not in a valid part of the user address space.

#### See Also

connect, getsockname, intro, listen, socket, inet, intro

## connect

Initiate a connection on a socket

#### Syntax

    #include <sys/types.h>
    #Include <sys/socket.h>
    #include "ns.h"

    int connect (s, name, namelen)
    int s;
    struct sockaddr_ns *name;
    int namelen;

#### Description

connect initiates a connection on a socket. The parameter s is a socket. If it is of type SOCK_DGRAM, then this call permanently specifies the peer to which datagrams are to be sent; if it is of type SOCK_STREAM, then this call attempts to make a connection to another socket. The other socket is specified by name; namelen is the length of name, which is an address in the address family of the socket. Each address family interprets the name parameter in its own way.

#### Return Value

If the connection or binding succeeds, then 0 is returned. Otherwise a -1 is returned, and a more specific error code is stored in errno.

#### Errors

The call fails if:

`[EBADF] S is not a valid descriptor.`

[ENOTSOCK] S is a descriptor for a file, not a socket/

[EADDRNOTAVAIL] The specified address is not available on this machine.

[EAFNOSUPPORT] Addresses in the specified address family cannot be used with this socket.

[EISCONN] The socket is already connected.

[ETIMEDOUT] Connection establishment timed out without establishing a connection.

[ECONNREFUSED] The attempt to connect was forcefully rejected.

[EADDRINUSE] The address is already in use.

[EFAULT] The name parameter specifies an area outside the process address space.

#### See Also

getsockname, intro, socket

## getpeername

Get name of connected peer

#### Syntax

    int getpeername(s, name, namelen)
    int s;
    struct sockaddr_ns *name;
    int *namelen;

#### Description

getpeername returns the name of the peer connected to socket s. The namelen parameter should be initialized to indicate the amount of space pointed to by name. On return it contains the actual size of the name returned (in bytes). The interpretation of name depends on the communication domain [see protocols]. Only the Internet domain is currently supported.

#### Diagnostics

A 0 is returned if the call succeeds, -1 if it fails.

#### Errors

The call succeeds unless:

`[EBADF] The argument s is not a valid descriptor.`

[ENOTSOCK] The argument s is a file, not a socket.

[ENOTCONN] The socket is not connected.

[ENOBUFS] Insufficient resources were available in the system to perform the operation.

[EFAULT] The name parameter points to memory not in a valid part of the process address space.

#### See Also

bind, getsockname, intro, socket

## getsocketname

Get socket name

#### Syntax

    int getsockname(s, name, namelen)
    int s;
    struct sockaddr_ns *name;
    int *namelen;

#### Description

getsockname returns the current name for the specified socket (s). The namelen parameter should be initialized to indicate the amount of space pointed to by name. On return namelen contains the actual size of the name returned (in bytes).

#### Return Value

A 0 is returned if the call succeeds, -1 if it fails.

#### Errors

The call succeeds unless:

`[EBADF] The argument s is not a valid descriptor.`

[ENOTSOCK] The argument s is a file, not a socket.

[ENOBUFS] Insufficient resources were available in the system to perform the operation.

[EFAULT] The name parameter points to memory not in a valid part of the process address space.

#### See Also

bind, intro, socket, intro

## getsockopt, setsockopt

get and set options on sockets

#### Syntax

    #include <sys/types.h>
    #include <sys/socket.h>
    #include "ns.h"

    int getsockopt(s, level, optname, optval, optlen)
    int s, level, optname;
    char *optval;
    int *optlen;

    int setsockopt(s, level, optname, optval, optlen)
    int s, level, optname;
    char *optval;
    int optlen;

#### Description

getsockopt and setsockopt manipulate options associated with a socket. Options may exist at multiple protocols levels; they are always present at the uppermost socket level.

When manipulating socket options the level at which the option resides and the name of the option must be specified. To manipulate options at the socket level, level is specified as SQL_SOCKET. To manipulate options at any other level the protocol number of the appropriate protocol controlling the option is supplied.

The parameters optval and optlen are used to access option values for setsockopt. For getsockopt they identify a buffer in which the value for the requested option(s) are to be returned. For getsockopt, optlen is a value-result parameter, initially containing the size of the buffer pointed to by optval, and modified on return to indicate the actual size of the value returned. If no option value is to be supplied or returned, optval may be supplied as 0.

optname and any specified options are passed uninterpreted to the appropriate protocol module for interpretation. The include file ,sys/socket.h> contains definitions for socket level options, described below. Options at other protocol levels vary in format and name; consult the appropriate entries in the section (SFF).

Most socket-level options take an int parameter for optval. For setsockopt, the parameter should be non-zero to enable a boolean option, or zero if the option is to be disabled. SO_LINGER uses a struct linger parameter, defined in <sys/socket.h>, which specifies the desired state of the option and the linger interval (see below).

The following options are recognized at the socket level. Except as noted, each may be examined with getsockopt and set with setsockopt.

SO_DEBUG toggle recording of debugging information

SO_REUSEADDR toggle on/off local address reuse

SO_KEEPALIVE toggle keep connection alive

SO_DONTROUTE toggle routing bypass for outgoing messages

SO_LINGER linger on close if data present

SO_BROADCAST toggle permission to transmit broadcast messages

SO_OOBINLINE toggle reception of out-of-band data in band

SO_SNDBUF set buffer size for output

SO_RCVBUF set buffer size for input

SO_TYPE get the type of the socket (get only)

SO_ERROR get and clear error on the socket (get only)

SO_PROTOTYPE get/set the protocol number associated with the stream

``

SO_DEBUG enables debugging in the underlying protocol modules.

SO_REUSEADDR indicates that the rules used in validating addresses supplied in a bind call should allow reuse of local addresses.

SO_KEEPALIVE enables the periodic transmission of messages on a connected socket. Should the connected party fail to respond to these messages, the connection is considered broken and processes using the socket are notified via a SIGPIPE signal.

SO_DONTROUTE indicates that outgoing messages should bypass the standard routing facilities. Instead, messages are directed to the appropriate network interface according to the network portion of the destination address.

SO_LINGER controls the action taken when unsent messages are queued on socket and a close is performed. If the socket promises reliable delivery of data and SO_LINGER is set, the system will block the process on the close attempt until it is able to transmit the data or until it decides it is unable to deliver the information (a timeout period, termed the linger interval, is specified in the setsockopt call when SO_LINGER is requested). If SO_LINGER is disabled and a close is issued, the system will process the close in a manner that allows the process to continue as quickly as possible.

SO_BROADCAST request permission to send broadcast datagrams on the socket. Broadcast was a privileged operation in earlier versions of the system.

With protocols that support out-of-band data, SO_OOBINLINE requests that out-of-band data be placed in the normal data input queue as received; it will then be accessible with recv or read calls without the MSG_OOB flag.

SO_SNDBUF are options to adjust the normal buffer sizes

and SO_RCVBUF allocated for output and input buffers, respectively. The buffer size may be increased for high-volume connections, or may be decreased to limit the possible backlog of incoming data. The system places an absolute limit on these values.

`SO_TYPE are options used only with setsockopt,`

and SO_ERROR SO_TYPE returns the type of the socket, such as SOCK_STREAM; it is useful for servers that inherit sockets on startup. SO_ERROR returns any pending error on the socket and clears the error status. It may be used to check for asynchronous errors on connected datagram sockets for other asynchronous errors.

SO_PROTOTYPE binds a protocol number to the socket. This option is necessary to support raw IP sockets (for example) and, as such, is used primarily by the BSD compatibility module.

#### Return Value

A 0 is returned if the call succeeds, -1 if it fails.

#### Errors

The call succeeds unless:

`[EBADF] The argument s is not a valid descriptor.`

[ENOTSOCK] The argument s is a file, not a socket.

[ENOPROTOOPT] The option is unknown at the level indicated.

[EFAULT] The address pointed to by optval is not in a valid part of the process address space. For getsockopt, this error may also be returned if optlen is not in a valid part of the process address space.

#### See Also

ioctl, socket, getprotoent

#### Notes

Several of the socket options should be handled at lower levels of the system.

## listen

listen for connections on a socket

#### Syntax

    int listen(s, backlog)
    int s, backlog;

#### Description

To accept connections, a socket is first created with socket, a backlog for incoming connections is specified with listen, and then the connections are accepted with accept. The listen call applies only to sockets of type SOCK_STREAM.

The backlog parameter defines the maximum length to which the queue of pending connections may grow. If a connection request arrives with the queue full, the client will receive an error with an indication of ECONNREFUSED.

#### Return Value

A 0 return value indicates success; -1 indicates an error

#### Errors

The call fails if:

`[EBADF] The argument s is not a valid descriptor.`

[ENOTSOCK] The argument s is not a socket.

[EOPNOTSUPP] The socket is not of a type that supports the operation listen.

#### See Also

accept, connect, socket

#### Notes

The backlog is currently limited (silently) to 5.

## recv, recvfrom

receive a message from a socket

#### Syntax

    #include <sys/types.h>
    #include <sys/socket.h>
    #include "ns.h"

    int recv(s, buf, len, flags)
    int s;
    char *buf;
    int len flags;

    int recvfrom(s, buf, len, flags, from, fromlen)
    int s;
    char *buf;
    int len, flags;
    struct sockaddr_ns *from;
    int *fromlen;

#### Description

recv and recvfrom are used to receive messages from a socket. The recv call may be used only on a connected socket (see connect), while recvfrom may be used to receive data on a socket whether it is in a connected state or not. If from is non-zero, the source address of the message is filled in. fromlen is a value-result parameter, initialized to the size of the buffer associated with from, and modified on return to indicate the actual size of the address stored there. The length of the message is returned in cc. If a message is too long to fit in the supplied buffer, excess bytes may be discarded depending on the type of socket the message is received from; see socket. If no messages are available at the socket, the receive call waits for a message to arrive.

The flags argument to a send call is formed by or'ing one or more of the values:

#defineMSG_OOB 0x1/* process out-of-band data */

#defineMSG_PEEK 0x2/* peek at incoming message */

####

Return Value

These calls return the number of bytes received, or -1 if an error occurred.

#### Errors

The calls fail if:

`[EBADF] The argument s is an invalid descriptor.`

[ENOTSOCK] The argument s is not a socket.

[EINTR] The receive was interrupted by delivery of a signal before any data was available for the receive.

[EFAULT] The data was specified to be received into a non-existent or protected part of the process address space.

#### See Also

connect, intro, read, send, socket, intro

## select

synchronous i/o multiplexing

#### Syntax

Warning, must be done right or you will suffer a big performance hit.

    #include <sys/types.h>
    #include <sys/time.h>

    nfound = select(nfds, readfds, writefds, exceptfds, timeout)
    int nfound, nfds;
    fd_set *readfds, *writefds, *exceptfds;
    struct timeval *timeout;

    FD_SET(fd, &fdset);
    FD_CLR(fd, &fdset);
    FD_ISSET(fd, &fdset);
    FD_ZERO(&fdset);
    int fd;
    fd_set fdset;

#### Description

Select examines the file descriptor sets whose addresses are passed in readfds, writefds, and exceptfds to see if some of their file descriptors are ready for reading, are ready for writing, or have an exceptional condition pending, respectively. The first nfds file descriptors are checked in each set, i.e. the descriptors from 0 through nfds-1 in the file descriptor sets are examined. On return, select replaces the given file descriptor sets with subsets consisting of those file descriptors that are ready for the requested operation. The total number of ready file descriptors is returned in nfound.

The file descriptor sets are stored as bit fields in arrays of integers. The following macros are provided for manipulating such file descriptor sets: FD_ZERO(&fdset) initializes a file descriptor set fdset to the null set. FD_SET(fd, &fdset) includes a particular file descriptor fd in fdset. FD_CLR(fd, &fdset) removes fd from fdset. FD_ISSET(fd, &fdset) is nonzero if fd is a member of fdset, zero otherwise. The behavior of these macros is undefined if a socket descriptor value is less than zero or greater than or equal to FD_SETSIZE, which is normally at least equal to the maximum number of file descriptors supported by the system.

If timeout is a non-zero pointer, it specifies a maximum interval to wait for the selection to complete. If timeout is a zero pointer, the select blocks indefinitely. To affect a poll, the timeout argument should be non-zero, pointing to a zero valued timeval structure.

Any of readfds, writefds, and exceptfds may be given as zero pointers if no file descriptors are of interest.

#### Return Value

Select returns the number of file descriptors which are contained in the file descriptor sets, or -1 if an error occurred. If the time limit expires then select returns 0.

#### Errors

An error return from select indicates:

`[EBADF] One of the file descriptor sets specified an invalid file descriptor.`

[EINTR] A signal was delivered before any of the selected for events occurred or the time limit expired.

[EFAULT] The memory pointed to by readfds, writefds, exceptfds, or timeout lies outside the valid address space for the process.

#### See Also

accept, connect, read, write, recv, send

#### Bugs

The file descriptor sets are always modified on return, even if the call returns as the result of the timeout.

## send, sendto

send a message to a socket

#### Syntax

    #include <sys/types.h>
    #include <sys/socket.h>
    #include "ns.h"

    int send(s, msg, len, flags)
    int s;
    char *msg;
    int len, flags;

    int sendto(s, msg, len, flags, to, tolen)
    int s;
    char *msg;
    int len, flags;
    struct sockaddr_ns *to;
    int tolen;

#### Description

send and sendto are used to transmit a message to another socket(s). send may be used only when the socket is in a connected state, while sendto may be used at any time.

The address of the target is given by to with tolen specifying its size. The length of the message is given by len. If the message is too long to pass automatically through the underlying protocol, then the error EMSGSIZE is returned, and the message is not transmitted.

No indication of failure to deliver is implicit in a send. Return values of -1 indicate some locally detected errors.

If no message space is available at the socket to hold the message to be transmitted, then send blocks.

The flags parameter may be set to MSG_OOB to send "out-of-band" data on sockets which support this notion (for example, SOCK_STREAM).

#### Return Value

The call returns the number of characters sent, or -1 if an error occurred.

#### Errors

`[EBADF] An invalid descriptor was specified.`

[ENOTSOCK] The argument s is not a socket.

[EFAULT] An invalid user space address was specified for a parameter.

[EMSGSIZE] The socket requires that message be sent automatically, and the size of the message to be sent made this impossible.

#### See Also

intro, recv, socket, intro

## shutdown

shut down part of a full-duplex connection

#### Syntax

    int shutdown(s, how)
    int s, how;

#### Description

The shutdown call causes all or part of a full-duplex connection on the socket associated with s to be shut down. If how is 0, then further receives will be disallowed. If how is 1, then further sends will be disallowed. If how is 2, then further sends and receives will be disallowed.

#### Diagnostics

A 0 is returned if the call succeeds, -1 if it fails.

#### Errors

The call succeeds unless:

`[EBADF] S is not a valid descriptor.`

[ENOTSOCK] S is a file, not a socket.

[ENOTCONN] The specified socket is not connected.

#### See Also

connect, socket

## socket

create an endpoint for communication

#### Syntax

    #include <sys/types.h>
    #include <sys/socket.h>

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

#### Description

socket creates an endpoint for communication and returns a descriptor.

s is a file descriptor returned by the socket system call.

The domain parameter specifies a communication domain within which communication will take place; this selects the protocol family which should be used. The protocol family generally is the same as the address family for the addresses supplied in later operations on the socket. These families are defined in the include file <sys/socket.h>. The only currently supported format is AF_NS (NOVELL IPX, XEROX XNS protocols).

The socket has the indicated type, which specifies the semantics of communication. Currently defined types include:

> SOCK_STREAM

> SOCK_DGRAM

> SOCK_RAW

Note that not all types are supported by all protocol families.

The NetCon Software currently only supports SOCK_DGRAM.

A SOCK_STREAM type provides sequenced, reliable, two-way connection-based byte streams with an out-of-band data transmission mechanism. A SOCK_DGRAM socket supports datagrams (connectionless, unreliable messages of a fixed maximum length).

SOCK_RAW sockets provide access to internal network protocols and interfaces. This type is available only to the super-user.

The protocol specifies a particular protocol to be used with the socket. Normally only a single protocol exists to support a particular socket type within a given protocol family. However, it is possible that many protocols may exist, in which case a particular protocol must be specified in this manner. The protocol number to use is particular to the "communication domain" in which communication is to take place; see protocols.

Sockets of type SOCK_STREAM are full-duplex byte streams, similar to pipes. A stream socket must be in a connected state before any data may be sent or received on it. A connection to another socket is created with a connect call. Once connected, data may be transferred using read and write call or some variant of the send and recv calls. When a session has been completed a close may be performed. Out-of-band data may also be transmitted as described in send and received as described in recv.

The communications protocols used to implement a SOCK_STREAM insure that data is not lost or duplicated. If a piece of data for which the peer protocol has buffer space cannot be successfully transmitted within a reasonable length of time, then the connection is considered broken and calls will indicate an error with -1 returns and with ETIMEDOUT as the specific code in the global variable errno. The protocols optionally keep sockets "warm" by forcing transmissions roughly every minute in the absence of other activity. An error is then indicated if no response can be elicited on an otherwise idle connection for a extended period (for example, 5 minutes). A SIGPIPE signal is raised if a process sends on a broken stream; this causes native processes, which do not handle the signal, to exit.

SOCK_DGRAM and SOCK_RAW sockets allow sending of datagrams to correspondents named in send calls. Datagrams are generally received with recv, which returns the next datagram with its return address.

An ioctl call can be used to specify a process group to receive a SIGUSE1 signal when the out-of-band data arrives.

The operation of sockets is controlled by socket level options. These options are defined in the file , sys/socket.h>. setsockopt and getsockopt [see getsockopt are used to set and get options, respectively. The following options are recognized at the socket level:

SO_DEBUG toggle recording of debugging information

SO_REUSEADDR toggle on/off local address reuse

SO_KEEPALIVE toggle keep connections alive

SO_DONTROUTE toggle routing bypass for outgoing messages

SO_LINGER linger on close if data present

SO_BROADCAST toggle permission to transmit broadcast messages

SO_OOBINLINE toggle reception of out-of-band in band

SO_SNDBUF set buffer size for output

SO_RCVBUF set buffer size for input

SO_TYPE get the type of the socket (get only)

SO_ERROR get and clear error on the socket (get only)

SO_PROTOTYPE get/set the protocol number associated with the stream

`SO_DEBUG enables debugging in the underlying protocol modules.`

SO_REUSEADDR indicates that the rules used in validating addresses supplied in a bind call should allow reuse of local addresses.

SO_KEEPALIVE enables the periodic transmission of messages on a connected socket. Should the connected party fail to respond to these messages, the connection is considered broken and processes using the socket are notified via a SIGPIPE signal.

SO_DONTROUTE indicates that outgoing messages should bypass the standard routing facilities. Instead, messages are directed to the appropriate network interface according to the network portion of the destination address.

SO_LINGER controls the action taken when unsent messages are queued on socket and a close is performed. If the socket promises reliable delivery of data and SO_LINGER is set, the system will block the process on the close attempt until it is able to transmit the data or until it decides it is unable to deliver the information (a timeout period, termed the linger interval, is specified in the setsockopt call when SO_LINGER is requested). If SO_LINGER is disabled and a close is issued, the system will process the close in a manner that allows the process to continue as quickly as possible.

SO_BROADCAST requests permission to send broadcast datagrams on the socket. Broadcast was a privileged operation in earlier versions of the system.

With protocols that support out-of-band data, SO_OOBINLINE requests that out-of-band data be placed in the normal data input queue as received; it will then be accessible with recv or read calls without the MSG_OOB flag.

SO_SNDBUF are options to adjust the normal buffer sizes

and SO_RCVBUF allocated for output and input buffers, respectively. The buffer size may be increased for high-volume connections, or may be decreased to limit the possible backlog of incoming data. The system places an absolute limit on these values.

SO_TYPE are options used only with setsockopt.

and SO_ERROR SO_TYPE returns the type of the socket, such as SOCK_STREAM; it is useful for servers that inherit sockets on startup. SO_ERROR returns any pending error on the socket and clears the error status. It may be used to check for asynchronous errors on connected datagram sockets or for other asynchronous errors.

SO_PROTOTYPE binds a protocol number to the socket. This option is necessary to support raw IP sockets (for example) and, as such, is used primarily by the BSD compatibility module.

#### Return Value

A -1 returned if an error occurs, otherwise the return value is a descriptor referencing the socket.