- Sockets are an abstraction for network communication.
- Enable communication between processes over the network.
- Support multiple protocols: TCP, UDP (IPv4, IPv6).
SOCK_STREAM– TCP (reliable, connection-oriented).SOCK_DGRAM– UDP (connectionless, unreliable).SOCK_SEQPACKET– sequenced, reliable datagrams (less common).SOCK_RAW– raw access to IP packets (used in advanced networking).
int socket(int domain, int type, int protocol);- Create a new socket descriptor.
int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);- Assign an address/port to a socket (server side).
int listen(int sockfd, int backlog);- Mark socket as passive (ready to accept connections).
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);- Accept a new incoming connection (blocking call).
int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);- Establish connection to a server (client side).
ssize_t read(int sockfd, void *buf, size_t count);ssize_t write(int sockfd, const void *buf, size_t count);ssize_t recv(int sockfd, void *buf, size_t len, int flags);ssize_t send(int sockfd, const void *buf, size_t len, int flags);int close(int sockfd);- Close the socket and free resources.
-
IPv4:
struct sockaddr_instruct sockaddr_in { sa_family_t sin_family; // AF_INET in_port_t sin_port; // port number (network byte order) struct in_addr sin_addr; // IP address };
-
IPv6:
struct sockaddr_in6 -
Generic:
struct sockaddrfor compatibility.
htons(),htonl(): host to network byte order (short/long)ntohs(),ntohl(): network to host byte orderinet_pton(): convert string IP tostruct in_addrorstruct in6_addrinet_ntop(): convert address structure to string
Server:
socket()bind()listen()accept()→ handle clientread()/write()→ communicateclose()
Client:
socket()connect()read()/write()→ communicateclose()
- Connectionless: no
listen()/accept(). - Use
sendto()andrecvfrom()for communication. - No guarantee of delivery; suitable for lightweight or real-time protocols.
- Process-based:
fork()for each client - Thread-based:
pthread_create()for each client - I/O multiplexing:
select(),poll(),epoll()
- Check return values of all socket calls.
- Use
perror()orstrerror()for diagnostics. - Handle
EINTRfor interruptible syscalls.
- Sockets abstract network communication using familiar file descriptor semantics.
- TCP ensures reliable, ordered delivery; UDP is fast but unreliable.
- Address conversions (
inet_pton,inet_ntop) are essential for portability. - Concurrency requires careful design: processes, threads, or event loops.
- Practice writing small client-server programs to solidify concepts.