Networking in C · beginner · ~6 min
Call socket() to obtain a fresh, unbound socket fd.
int socket(int family, int type, int proto) asks the kernel to allocate a new socket and returns a file descriptor for it.
family = AF_INET (IPv4) or AF_INET6 (IPv6). Stick to AF_INET for this course.type = SOCK_STREAM (TCP) or SOCK_DGRAM (UDP).proto = 0 lets the kernel pick the default for the family/type pair (TCP for stream, UDP for dgram).Returns the new fd, or -1 with errno set. Always check.
#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() the fd on error paths. Sockets are fds; they leak the same way.socket() with connect() — socket() only allocates; you still need bind/listen or connect.socket(AF_INET, SOCK_STREAM, 0) creates a TCP socket fd. Returns -1 on error.