create an endpoint for communication
#include <sys/types.h> #include <sys/socket.h> int socket( int domain, int type, int protocol );
The socket() function creates an endpoint for communication and returns a descriptor.
The domain parameter specifies a communications domain; this selects the protocol family that should be used. These families are defined in the include file <sys/socket.h>.
The type assigned to the socket determines the semantics of communication. Here are the currently defined types:
The protocol parameter 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. But if many protocols exist, you must specify a particular protocol with protocol. The protocol number you give is particular to the communication domain where communication is to take place.
SOCK_STREAM sockets 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() calls 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 socket ensure that data isn't lost or duplicated. If a piece of data that the peer protocol has buffer space for can't be successfully transmitted within a reasonable length of time, 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.
With SOCK_DGRAM and SOCK_RAW sockets, datagrams can be sent to correspondents named in send() calls. Datagrams are generally received with recvfrom(), which returns the next datagram with its return address.
You can use the ioctl() call to specify a process group to receive a SIGURG signal when the out-of-band data arrives. The call may also enable nonblocking I/O and asynchronous notification of I/O events via SIGIO.
The operation of sockets is controlled by socket-level options. These options are defined in the file <sys/socket.h>. You use setsockopt() and getsockopt() to set and get options, respectively.
A descriptor referencing the socket, or -1 if an error occurred (errno is set).
If an error occurred, errno could contain one of the following:
POSIX 1003.1g (draft)
Safety: | |
---|---|
Interrupt handler | No |
Signal handler | No |
Thread | Yes |
ICMP, IP, TCP, and UDP protocols, accept(), bind(), connect(), getprotoent(), getsockname(), getsockopt(), ioctl(), listen(), recv(), send(), shutdown(), socketpair(),
close(), read(), select(), write() in the C Library Reference