What are sockets?
- C course
- Advanced
- Lesson 25/83
- 5 min
Learn the socket concept and its role in network communication.
What are sockets?
A socket is an endpoint for communication between processes or over a network. In POSIX, sockets are also file descriptors; they work with read and write.
Two main types exist: SOCK_STREAM (TCP, reliable connection) and SOCK_DGRAM (UDP, connectionless datagram). Sockets are defined in <sys/socket.h>. A server follows socket, bind, listen and accept; a client uses socket and connect.
Socket addresses
Each socket is bound to an address. AF_UNIX uses a local file path, AF_INET uses an IPv4 network. The address structures are struct sockaddr_un and struct sockaddr_in respectively.
In this lesson we use AF_UNIX; it has no network dependency and is fast on the same machine. Socket functions take the address as struct sockaddr *; so you need to cast. Clearing the address struct with memset is a good habit.
Practice Print socket types
Print two socket types, one per line, with printf: printf("SOCK_STREAM\n"); and printf("SOCK_DGRAM\n");.
Starter code
#include <stdio.h>
#include <sys/socket.h>
// Print SOCK_STREAM
// Print SOCK_DGRAM
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <sys/socket.h>
int main(void) {
printf("SOCK_STREAM\n");
printf("SOCK_DGRAM\n");
return 0;
}Expected output
SOCK_STREAM SOCK_DGRAM
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which protocol does SOCK_STREAM correspond to?
- TCP Correct answer
- UDP
- ICMP
- ARP
Explanation: SOCK_STREAM corresponds to TCP's reliable connection.
2 Socket type
int fd = socket(AF_UNIX, ____, 0);
int fd = socket(AF_UNIX, SOCK_STREAM, 0);
Explanation: SOCK_STREAM provides a reliable connection.
3 Match socket types
| Term | Meaning |
|---|---|
SOCK_STREAM |
TCP reliable |
SOCK_DGRAM |
UDP connectionless |
AF_UNIX |
Local socket |
AF_INET |
IPv4 network |