Sign in with Google to keep private notes

Networking Basics with C code

Everything in Unix is a file descriptor

Example (network connection, FIFO, pipe, terminal, an actual on-the-disk file). Use socket() to connect with the files, read() and write() to read or write stuff to your file, but send() and receive() for some greater control over what you send to the file.

Stream socket. Stream sockets are what you imagine a IP+TCP+TLS connection to be (packets arrive in the order they were intended).

Datagram socket. Raw dogging it in life. Slap and IP address destination and just send it out like one of god's roombas towards its final destination. It may or may not arrive. It may or may not arrive out of order. "If it arrives the packet will be error free". used by tftp or bootp. If reception was succesful use ack protocol.

ok im going to try to let an LLM generate summaries from this point onwards because this is getting unwieldy...

All you have to do for datagram sockets is encapsulate the packetin the method of your choosing and sendto() it out. The kernel builds the Transport Layer and Internet Layer on for you and the hardware does the Network Access Layer. Ah, modern technology.

Also

  • send() (Stream Sockets / TCP): You must call connect() first to establish a dedicated, two-way connection. Because the operating system already knows who is on the other end of that connection, you don't need to specify the destination address every time you transmit—send() just takes the socket descriptor and the data.
  • sendto() (Datagram Sockets / UDP): UDP does not maintain an active connection. Each packet is an independent envelope tossed onto the network, so the OS has no inherent idea where it's supposed to go unless you tell it. sendto() requires you to pass the destination struct sockaddr directly with every single call.

socketaddress information

struct sockaddr {
    unsigned short sa_family; // address family, e.g. AF_INET, AF_INET6
    char           sa_data[14]; // 14 bytes of protocol address
};

to eat this in a more paltable manner: sockaddr_in

struct sockaddr_in {
short int          sin_family; // Address family
unsigned short int sin_port; // Port number
struct in_addr     sin_addr; // Internet address
unsigned char      sin_zero[8]; // Same size as struct sockaddr
};

sin_zero will help pad sockaddr up into a sockaddr_in, i think.

3.1. Host ↔ Network Byte Order Conversion

Network protocols use big-endian byte order, while a host may use big-endian or little-endian. Convert integers to network byte order before transmitting them.

Function Conversion
htons() Host → Network, 16-bit
htonl() Host → Network, 32-bit
ntohs() Network → Host, 16-bit
ntohl() Network → Host, 32-bit
  • 16-bit (short): Typically used for port numbers.
  • 32-bit (long in function names): Used for IPv4 addresses. The functions operate on 32-bit integers, even on platforms where C long is 64-bit.
  • 8-bit (char): No conversion needed because byte order is irrelevant to a single byte.
  • Portability: Always use these conversion functions, even on big-endian machines (where they perform no byte swapping).

struct sockaddr_in fields:

  • sin_port: Network byte order, because the port is encoded in the transport-layer header.
  • sin_addr: Network byte order, because the IP address is encoded in the IP header.
  • sin_family: Host byte order, because it is used locally by the kernel and never transmitted.

Working with sockaddr_in

Topic HFT relevance Recommendation
Endianness (big vs little) Very high Understand thoroughly
htons, htonl, ntohs, ntohl High Learn
sockaddr_in structure High Learn
inet_addr, inet_aton Low Skim
inet_ntoa Low Skim; understand its static-buffer pitfall
inet_pton, inet_ntop High Learn instead of the older APIs

3.1. Socket Address Structures

struct sockaddr_in represents an IPv4 socket endpoint.

sockaddr_in addr{};
addr.sin_family = AF_INET;              // IPv4, host byte order
addr.sin_port = htons(8080);            // Port, network byte order
inet_pton(AF_INET, "192.168.1.10",
          &addr.sin_addr);              // IP, network byte order
  • sin_family: Identifies the address family for the kernel; remains in host byte order.
  • sin_port: 16-bit port number; must use network byte order.
  • sin_addr: 32-bit IPv4 address; must use network byte order.
  • inet_pton(): Converts an IP address string into its binary representation.
  • inet_ntop(): Converts a binary IP address into a readable string.

Prefer inet_pton() / inet_ntop() over the older inet_addr() / inet_ntoa() APIs.

3.2. Byte Order and Endianness

Endianness determines how multi-byte integers are stored in memory or encoded in network messages.

  • Big-endian: Most significant byte first (standard network byte order).
  • Little-endian: Least significant byte first (used by x86-64 CPUs).
  • HFT relevance: Binary trading protocols specify their own byte order. For example, Nasdaq ITCH uses big-endian, while CME SBE uses little-endian.

Byte-order conversion functions:

Function Purpose
htons() Host → Network, 16-bit
htonl() Host → Network, 32-bit
ntohs() Network → Host, 16-bit
ntohl() Network → Host, 32-bit

For modern C++, std::endian (C++20) identifies native byte order, while std::byteswap (C++23) reverses integer byte order. An 8-bit value never needs swapping.

3.3. Important Parts

Binary market-data feeds require interpreting integer fields according to the exchange protocol's specification.

uint32_t raw;
std::memcpy(&raw, buffer, sizeof(raw));

uint32_t value = ntohl(raw); // If protocol specifies big-endian
  • std::memcpy avoids alignment and strict-aliasing issues when extracting fields from binary buffers.
  • ntohl() converts big-endian network data to host byte order.
  • Never assume all trading protocols use big-endian. Follow each protocol's specification to avoid incorrect prices, quantities, or timestamps.

Private IP Addresses and Network Address Translation (NAT)

NAT (Network Address Translation) allows multiple devices on a private network to access the Internet using a single public IP address.

  • Private IP address: Identifies a device within its local network (e.g., 10.0.0.5).
  • Public IP address: Identifies the network's externally reachable address (e.g., 64.81.52.10).
  • NAT router/firewall: Translates private addresses to a public address for outbound traffic, and maps returning traffic back to the correct internal device, typically using port numbers (NAPT/PAT).
  • Transparency: NAT generally requires no special handling by applications making ordinary outbound connections.

Reserved private IPv4 address ranges (RFC 1918):

Range CIDR notation
10.0.0.0 – 10.255.255.255 10.0.0.0/8
172.16.0.0 – 172.31.255.255 172.16.0.0/12
192.168.0.0 – 192.168.255.255 192.168.0.0/16

These addresses are not globally routable on the public Internet and can be reused independently across different private networks.

Example: A computer at 10.0.0.5:50000 connects to an Internet server. The NAT router may translate its source to 64.81.52.10:60000 and maintain a mapping so returning packets reach 10.0.0.5:50000.

System Call Stuff

Technologies such as DPDK and AMD Solarflare ef_vi allow userspace packet processing without a syscall for every received packet. In an ef_vi implementation, you may not use a conventional socket file descriptor for the accelerated data path at all.

4.1. socket() — Create a Socket File Descriptor

#include <sys/socket.h>

int socket(int domain, int type, int protocol);

Creates a socket and returns a file descriptor (non-negative integer) used in subsequent socket system calls.

Parameter Description
domain Address family, e.g. AF_INET (IPv4), AF_INET6 (IPv6)
type SOCK_STREAM (TCP) or SOCK_DGRAM (UDP)
protocol 0 selects the default protocol for the given domain and type
  • AF_INET and PF_INET have the same value on common platforms; AF_INET is conventionally used for both.
  • Returns -1 on failure and sets errno.
  • Creating a socket does not establish a connection or assign a specific local address.

4.2. bind() — Associate a Socket with a Local Address

#include <sys/socket.h>

int bind(int sockfd, const struct sockaddr *addr,
         socklen_t addrlen);

Associates an existing socket with a local IP address and port, allowing the kernel to determine which socket should receive incoming traffic.

Parameter Description
sockfd File descriptor returned by socket()
addr Pointer to a socket address containing IP and port
addrlen Size of the socket address structure

Putting 2 and 2 together: Bind a TCP socket to port 3490 on all local IPv4 interfaces.

int sockfd = socket(AF_INET, SOCK_STREAM, 0);

sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(3490);
addr.sin_addr.s_addr = htonl(INADDR_ANY); //now binds to ALL local IPv4

int result = bind(sockfd,
                  (sockaddr*)&addr,
                  sizeof(addr));
  • htons(3490): Converts the port to network byte order.
  • INADDR_ANY (0.0.0.0): Binds to all local IPv4 interfaces, not just one specific IP address.
  • sin_port = htons(0): Asks the kernel to assign an available ephemeral port.
  • bind() returns 0 on success or -1 on error, setting errno.

Additional details:

  • Port restrictions: Ports 0–1023 generally require elevated privileges on Unix-like systems. Ports 1024–65535 are generally available, subject to permissions and existing bindings.
  • SO_REUSEADDR: Socket option commonly set before bind() to allow restarting a TCP server when previous connections remain in TIME_WAIT.
int yes = 1;
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
           &yes, sizeof(yes));
  • Client sockets: Explicit bind() is usually unnecessary before connect(). The kernel automatically selects a suitable local IP address and ephemeral port.

Key distinction: socket() creates the communication endpoint; bind() assigns its local IP address and port. For a TCP server, listen() is subsequently needed to accept incoming connections.

connect() takes many of the same arguments as bind and takes in and #define DEST_IP and a #define DEST_PORT. you don't need to call bind() on it, it does it automaitcally. also this works for both datagram and stream socket.

//this sets up a queue for you to handle incoming connections
int listen(int socketfd, int backlog);
//backlog refers to how many other files you can subscribe to
in the in the order you should call it

socket();
bind();
listen();

and then when two machines love each other very much, or, like, when one machine calls connect() to another that called listen()...

int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);

which allows you to have that connect()ing machine allocated to one specific port.

4.6. send() and recv() — Communicating Over Connected Sockets

Used to exchange data over TCP sockets or connected UDP sockets.

ssize_t send(int sockfd, const void *buf, size_t len, int flags);
ssize_t recv(int sockfd, void *buf, size_t len, int flags);
Parameter Description
sockfd Socket file descriptor
buf Pointer to outgoing data (send) or incoming buffer (recv)
len Bytes to send, or maximum bytes to receive
flags Usually 0

Return values:

  • send() returns bytes successfully accepted for sending, potentially fewer than requested. It becomes the caller's responsibility to handle the remainignn data during a partial send.
  • recv() returns bytes received, potentially fewer than requested, even if more data will arrive later.
  • recv() returning 0 on a TCP socket means the peer has performed an orderly shutdown of its sending side (EOF).
  • Both return -1 on error and set errno.

Important: TCP is a byte stream, not a message protocol. A single send() does not necessarily correspond to a single recv(), so applications must implement their own message framing.

4.7. sendto() and recvfrom() — Communicating Over Unconnected Datagram Sockets

Used for datagram. As mentioned above. You can use this without establishing a connection.

//the only difference is the struct sockaddr* and the socklen_t * for both of these
ssize_t sendto(int sockfd, const void *buf, size_t len,
               int flags, const struct sockaddr *to,
               socklen_t tolen);

ssize_t recvfrom(int sockfd, void *buf, size_t len,
                 int flags, struct sockaddr *from,
                 socklen_t *fromlen);

Now note that you can still use udp if you use send() and recv(). Provided you make use of the connect() function.

Connected vs. Unconnected Sockets

Connected TCP Unconnected UDP Connected UDP
Sending send() sendto() send()
Receiving recv() recvfrom() recv()
Destination Established connection Specified per datagram Stored by connect()
Data semantics Byte stream Datagrams Datagrams

Key distinction: Calling connect() on a UDP socket does not establish a TCP-style connection or change UDP's protocol semantics. It simply associates a default remote address, allowing send() and recv() without specifying addresses each time.

And then shutdown() closes the connection (either the connect()er or the listen()er.)

close() must still be called for the guy on this side of the curve

DNS

DNS is a distributed system, not a single database that everyone has a copy of.

When you call gethostbyname("google.com"), roughly:

  1. Your computer checks local sources, such as /etc/hosts and any applicable DNS cache.
  2. A DNS resolver (usually operated by your ISP or a service like Google DNS) is queried if the answer isn't available locally.
  3. The resolver may contact other DNS servers through the DNS hierarchy to find the address.
  4. The IP address is returned to your program and may be cached for future requests.

 

Articles to read next