Course contentsShow
← C
Lesson 1108 of 1,21915. Systems ProgrammingFree lesson

Socket domains and types

Socket domains and types

What you'll learn: How to choose the communication medium and the delivery style for your network connection.

Before you can send data over a network, you have to decide two things: "Where is this going?" and "How should the data behave?" In C, we define these using Domains and Types.

The Domain: The Address Family

Think of the domain as the "neighborhood" or the medium your data travels through. When calling the socket() function, you specify a domain to tell the OS which protocol suite to use.

  • AF_INET: This is the most common. It uses IPv4 addresses (like 192.168.1.1). Use this to talk to computers over the internet.
  • AF_UNIX: Also called "Local" sockets. This is used for two programs running on the same physical machine. It’s faster because the data never actually hits the network hardware.

The Type: The Delivery Method

Once you know the neighborhood, you need to choose the "vehicle." This defines how your data is delivered.

  • SOCK_STREAM (TCP): Think of this like a phone call. You establish a dedicated connection, and data arrives in the exact order it was sent. If a packet gets lost, the system automatically asks for a retry. It is reliable but has a little bit of overhead.
  • SOCK_DGRAM (UDP): Think of this like sending postcards. Each packet (datagram) is independent. They might arrive out of order, or not at all. It is incredibly fast, making it perfect for video streaming or gaming where speed matters more than perfect reliability.

Putting it together in C

When you create a socket, you combine these two choices. Here is how you initialize a standard internet-based TCP socket:

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

int main() {
    // Create a socket: Internet Domain, Stream Type, Protocol 0 (Auto)
    int network_socket = socket(AF_INET, SOCK_STREAM, 0);

    if (network_socket == -1) {
        printf("Error creating the socket.\n");
        return 1;
    }

    printf("Socket created successfully!\n");
    return 0;
}

By changing AF_INET to AF_UNIX or SOCK_STREAM to SOCK_DGRAM, you completely change how your program interacts with the world without changing the rest of your logic.

Key takeaway

The Domain (AF) defines the destination's reach, while the Type (SOCK) defines the reliability and speed of the data transfer.