CodeBlanks Logo Icon CodeBlanks

What are sockets?

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

main.c
#include <stdio.h>
#include <sys/socket.h>

// Print SOCK_STREAM
// Print SOCK_DGRAM

int main(void) {
    return 0;
}

Sample solution

main.c
#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

Question
int fd = socket(AF_UNIX, ____, 0);
Answer
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

All lessons in Advanced