What is the socket() system call and what do AF_INET, SOCK_STREAM, and SOCK_DGRAM mean?
The socket() system call creates a communication endpoint and returns a file descriptor. It is the first step in all network programming.
Signature: int socket(int domain, int type, int protocol);
Domain (Address Family):
AF_INET-- IPv4 Internet protocolsAF_INET6-- IPv6 Internet protocolsAF_UNIX(orAF_LOCAL) -- Local communication (same machine)
Type (Socket Type):
SOCK_STREAM-- Reliable, connection-oriented, byte stream (TCP). Guarantees in-order delivery. You mustconnect()before sending data.SOCK_DGRAM-- Connectionless, unreliable datagrams (UDP). Eachsendto()is independent. No connection setup needed.SOCK_RAW-- Raw network access (requires root/CAP_NET_RAW).
Protocol: Usually 0 to auto-select the default protocol for the given domain+type pair (TCP for STREAM, UDP for DGRAM).
The returned file descriptor behaves like any other fd -- you can use read()/write(), close(), select()/poll() on it. On error, socket() returns -1 and sets errno.
1. Call socket(AF_INET, SOCK_STREAM, 0) for TCP
2. Call socket(AF_INET, SOCK_DGRAM, 0) for UDP
3. Check return value: >= 0 is valid fd, -1 is error
4. Use the fd with bind/listen/accept (server) or connect (client)
5. Close the fd when done with close()
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
int main(void) {
/* Create a TCP socket */
int tcp_fd = socket(AF_INET, SOCK_STREAM, 0);
if (tcp_fd == -1) {
perror("socket (TCP)");
exit(EXIT_FAILURE);
}
printf("TCP socket fd: %d\n", tcp_fd);
/* Create a UDP socket */
int udp_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (udp_fd == -1) {
perror("socket (UDP)");
close(tcp_fd);
exit(EXIT_FAILURE);
}
printf("UDP socket fd: %d\n", udp_fd);
close(tcp_fd);
close(udp_fd);
return 0;
}
- •socket() returns a file descriptor or -1 on error
- •AF_INET = IPv4, AF_INET6 = IPv6, AF_UNIX = local IPC
- •SOCK_STREAM = TCP (reliable, ordered, connection-oriented)
- •SOCK_DGRAM = UDP (unreliable, connectionless, message-oriented)
- •Protocol 0 auto-selects the default (TCP for STREAM, UDP for DGRAM)
- •Always check the return value -- socket() can fail if the system runs out of file descriptors
- •Sockets must be closed with close() to avoid fd leaks, just like regular files
- •SOCK_STREAM does not preserve message boundaries -- TCP is a byte stream, not a message stream