This function creates an endpoint for communication. To establish communication, every process needs a socket at the end of the communication line. Also, the two communicating processes must have the same socket type and both should be in the same domain. Here is the syntax for creating a socket:
int socket(int domain, int type, int protocol);
Here, domain represents the communication domain in which a socket is to be created. Basically, the address family or protocol family is specified, which will be used in the communication.
A few of the popular address family are listed as follows:
- AF_LOCAL: This is used for local communication.
- AF_INET: This is used for IPv4 internet protocols.
- AF_INET6: This is used for IPv6 internet protocols.
- AF_IPX: This is used for protocols that use standard IPX (short for Internetwork Packet Exchange) socket addressing.
- AF_PACKET: This is used for packet interface.
- type: Represents the type of socket to be created. The following are the popular socket types:
- SOCK_STREAM: Stream sockets communicate as a continuous stream of characters using a Transmission Control Protocol (TCP). TCP is a reliable stream-oriented protocol. So, the SOCK_STREAM type provides reliable, bidirectional, and connection-based byte streams.
- SOCK_DGRAM: Datagram sockets read the entire messages at once using a User Datagram Protocol (UDP). UDP is an unreliable, connectionless, and message-oriented protocol. These messages are of a fixed maximum length.
- SOCK_SEQPACKET: Provides reliable, bidirectional, and connection-based transmission paths for datagrams.
- protocol: Represents the protocol to be used with the socket. A 0 value is specified so that you can use the default protocol that's suitable for the requested socket type.
You can replace the AF_ prefix in the preceding list with PF_ for protocol family.
On successful execution, the socket function returns a file descriptor that can be used to manage sockets.