Create a TCP socket with socket(AF_INET, SOCK_STREAM, 0)
Create an IPv4 TCP socket with socket(AF_INET, SOCK_STREAM, 0) on Linux with glibc 2.39, check for -1, and see why the protocol argument can stay 0.
This is how you ask the kernel for an IPv4 TCP endpoint. On Linux 6.8 with glibc 2.39, socket() returns the lowest unused file descriptor, or -1 with errno set.
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
int main(void)
{
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) {
perror("socket");
return 1;
}
printf("fd=%d\n", fd);
close(fd);
return 0;
}fd=3The third argument selects a protocol within the family and type. Passing 0 means "the default", and for AF_INET plus SOCK_STREAM the default is TCP, so you do not need IPPROTO_TCP. Descriptors 0, 1 and 2 are already taken by standard input, output and error, which is why the first socket in a fresh process is 3. The socket(2) manual page lists the other defaults.
Pass the protocol explicitly when a type has more than one choice, for example SOCK_STREAM with IPPROTO_SCTP. Also note that a bare socket() leaves the descriptor inheritable across exec; see the SOCK_CLOEXEC flag if the process spawns children.