Networking in C · beginner · ~6 min

socket() — creating an endpoint

Call `socket()` to obtain a fresh, unbound socket file descriptor.

Lesson

What socket() does

int 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.

The three arguments

  • family — the address family.
    • AF_INET for IPv4.
    • AF_INET6 for IPv6.
    • Use 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.
    • Pass 0 to let the kernel choose the default for the family/type pair.
    • That default is TCP for SOCK_STREAM and UDP for SOCK_DGRAM.

Return value

socket() returns the new file descriptor on success.

On failure it returns -1 and sets errno. Always check the result before using the descriptor.

Code examples

#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;
}

Common mistakes

  • Leaking the descriptor on error paths. A socket is a file descriptor. If you do not close() it, it leaks exactly like any other open file descriptor.
  • Confusing 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.

Summary

  • 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.
  • On error it returns -1 and sets errno — always check.
  • A new socket is unbound; you still need bind/listen or connect to use it.

Practice with these exercises