CodeBlanks Logo Icon CodeBlanks

Socket basics

Learn socket programming basics in C++.

What is a socket?

A socket is an endpoint for communication between two programs. It is used to send and receive data over a network. In C++ the POSIX socket API provides the socket() function, which creates a socket and returns a file descriptor (int).

Example: int sock = socket(AF_INET, SOCK_STREAM, 0);. Here AF_INET means the IPv4 address family, SOCK_STREAM means a reliable TCP connection, and 0 picks the default protocol. A negative return value signals an error. After creating the socket you use connect (client) or bind + listen (server). This lesson focuses on socket creation only.

AF_INET and the socket descriptor

AF_INET specifies the IPv4 address family. When a socket is created the returned int is a file descriptor. This value is used in all subsequent socket operations (connect, bind, send, recv).

Example: int sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) { /* error */ }. A negative value means an error. To close the socket you call close(sock);. A socket must always be closed when done; otherwise a resource leak occurs. This is like file operations: open, use, close.

Practice Create a socket

Add #include <sys/socket.h>. Create a TCP socket with int sock = socket(AF_INET, SOCK_STREAM, 0);. Print the status with std::cout << "Socket ready";.

Starter code

main.cpp
#include <iostream>

// Add the socket header and create a socket

int main() {
    // Add the socket call and output
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <sys/socket.h>

int main() {
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    std::cout << "Socket ready";
    return 0;
}

Expected output

Socket ready

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?

  • UDP
  • ICMP
  • TCP Correct answer
  • ARP

Explanation: SOCK_STREAM means a reliable TCP connection.

2 Match each piece to its role

Term Meaning
AF_INET IPv4 address family
SOCK_STREAM TCP stream
socket() Creates a socket
close(sock) Closes the socket

3 Complete the socket type

Question
int sock = socket(AF_INET, ____, 0);
Answer
int sock = socket(AF_INET, SOCK_STREAM, 0);

Explanation: SOCK_STREAM gives a reliable TCP based stream.

All lessons in Advanced