Networking in C · beginner · ~6 min
Call `socket()` to obtain a fresh, unbound socket file descriptor.
socket() doesint socket(int family, int type, int proto) asks the kernel to allocate a new socket. It returns a file descriptor (an integer the kernel uses to identify an open resource) for that socket.
The socket starts out empty: it is not yet tied to an address or a peer.
family — the address family.AF_INET for IPv4.AF_INET6 for IPv6.AF_INET throughout this course.type — the kind of communication.SOCK_STREAM for TCP (reliable, connection-based).SOCK_DGRAM for UDP (message-based, no connection).proto — the protocol.0 to let the kernel choose the default for the family/type pair.SOCK_STREAM and UDP for SOCK_DGRAM.socket() returns the new file descriptor on success.
On failure it returns -1 and sets errno. Always check the result before using the descriptor.
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <unistd.h>
int main(void) {
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) { perror("socket"); return 1; }
printf("got socket fd %d\n", fd);
close(fd);
return 0;
}
close() it, it leaks exactly like any other open file descriptor.socket() with connect(). socket() only allocates the socket. You still need bind() and listen() (for a server) or connect() (for a client) before any communication happens.socket(AF_INET, SOCK_STREAM, 0) creates a TCP socket and returns its file descriptor.family picks IPv4/IPv6, type picks TCP/UDP, and proto = 0 selects the default protocol.-1 and sets errno — always check.