socket()¶
Purpose¶
socket() creates a communication endpoint and returns a file descriptor.
For TCP/IPv4 examples, it is typically called with AF_INET and SOCK_STREAM.
Header¶
Prototype¶
Minimal Example¶
int fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
if (fd < 0) {
perror("socket");
return -1;
}
Common Pitfalls¶
- Forgetting that sockets are file descriptors.
- Not setting
SOCK_CLOEXECorFD_CLOEXECwhen appropriate. - Forgetting to make sockets non-blocking in event-loop designs.