add Beej's Guide to Network Programming - webdump_tests - Testfiles for webdump
HTML git clone git://git.codemadness.org/webdump_tests
DIR Log
DIR Files
DIR Refs
DIR README
---
DIR commit 837749abc02f28e1584e5f2cf2b274ae1c69d8e6
DIR parent 0d1f5751607b86b26908901a9291268845dd110c
HTML Author: Hiltjo Posthuma <hiltjo@codemadness.org>
Date: Thu, 4 Jul 2024 18:36:29 +0200
add Beej's Guide to Network Programming
https://beej.us/guide/bgnet/html/
Diffstat:
A realworld/bgnet.html | 4888 +++++++++++++++++++++++++++++++
1 file changed, 4888 insertions(+), 0 deletions(-)
---
DIR diff --git a/realworld/bgnet.html b/realworld/bgnet.html
@@ -0,0 +1,4888 @@
+<!DOCTYPE html>
+<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
+<head>
+ <meta charset="utf-8" />
+ <meta name="generator" content="pandoc" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
+ <title>Beej's Guide to Network Programming</title>
+ <style>
+ html {
+ color: #1a1a1a;
+ background-color: #fdfdfd;
+ }
+ body {
+ margin: 0 auto;
+ max-width: 36em;
+ padding-left: 50px;
+ padding-right: 50px;
+ padding-top: 50px;
+ padding-bottom: 50px;
+ hyphens: auto;
+ overflow-wrap: break-word;
+ text-rendering: optimizeLegibility;
+ font-kerning: normal;
+ }
+ @media (max-width: 600px) {
+ body {
+ font-size: 0.9em;
+ padding: 12px;
+ }
+ h1 {
+ font-size: 1.8em;
+ }
+ }
+ @media print {
+ html {
+ background-color: white;
+ }
+ body {
+ background-color: transparent;
+ color: black;
+ font-size: 12pt;
+ }
+ p, h2, h3 {
+ orphans: 3;
+ widows: 3;
+ }
+ h2, h3, h4 {
+ page-break-after: avoid;
+ }
+ }
+ p {
+ margin: 1em 0;
+ }
+ a {
+ color: #1a1a1a;
+ }
+ a:visited {
+ color: #1a1a1a;
+ }
+ img {
+ max-width: 100%;
+ }
+ h1, h2, h3, h4, h5, h6 {
+ margin-top: 1.4em;
+ }
+ h5, h6 {
+ font-size: 1em;
+ font-style: italic;
+ }
+ h6 {
+ font-weight: normal;
+ }
+ ol, ul {
+ padding-left: 1.7em;
+ margin-top: 1em;
+ }
+ li > ol, li > ul {
+ margin-top: 0;
+ }
+ blockquote {
+ margin: 1em 0 1em 1.7em;
+ padding-left: 1em;
+ border-left: 2px solid #e6e6e6;
+ color: #606060;
+ }
+ code {
+ font-family: Menlo, Monaco, Consolas, 'Lucida Console', monospace;
+ font-size: 85%;
+ margin: 0;
+ hyphens: manual;
+ }
+ pre {
+ margin: 1em 0;
+ overflow: auto;
+ }
+ pre code {
+ padding: 0;
+ overflow: visible;
+ overflow-wrap: normal;
+ }
+ .sourceCode {
+ background-color: transparent;
+ overflow: visible;
+ }
+ hr {
+ background-color: #1a1a1a;
+ border: none;
+ height: 1px;
+ margin: 1em 0;
+ }
+ table {
+ margin: 1em 0;
+ border-collapse: collapse;
+ width: 100%;
+ overflow-x: auto;
+ display: block;
+ font-variant-numeric: lining-nums tabular-nums;
+ }
+ table caption {
+ margin-bottom: 0.75em;
+ }
+ tbody {
+ margin-top: 0.5em;
+ border-top: 1px solid #1a1a1a;
+ border-bottom: 1px solid #1a1a1a;
+ }
+ th {
+ border-top: 1px solid #1a1a1a;
+ padding: 0.25em 0.5em 0.25em 0.5em;
+ }
+ td {
+ padding: 0.125em 0.5em 0.25em 0.5em;
+ }
+ header {
+ margin-bottom: 4em;
+ text-align: center;
+ }
+ #TOC li {
+ list-style: none;
+ }
+ #TOC ul {
+ padding-left: 1.3em;
+ }
+ #TOC > ul {
+ padding-left: 0;
+ }
+ #TOC a:not(:hover) {
+ text-decoration: none;
+ }
+ code{white-space: pre-wrap;}
+ span.smallcaps{font-variant: small-caps;}
+ div.columns{display: flex; gap: min(4vw, 1.5em);}
+ div.column{flex: auto; overflow-x: auto;}
+ div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
+ ul.task-list{list-style: none;}
+ ul.task-list li input[type="checkbox"] {
+ width: 0.8em;
+ margin: 0 0.8em 0.2em -1.6em;
+ vertical-align: middle;
+ }
+ /* CSS for syntax highlighting */
+ pre > code.sourceCode { white-space: pre; position: relative; }
+ pre > code.sourceCode > span { display: inline-block; line-height: 1.25; }
+ pre > code.sourceCode > span:empty { height: 1.2em; }
+ .sourceCode { overflow: visible; }
+ code.sourceCode > span { color: inherit; text-decoration: inherit; }
+ div.sourceCode { margin: 1em 0; }
+ pre.sourceCode { margin: 0; }
+ @media screen {
+ div.sourceCode { overflow: auto; }
+ }
+ @media print {
+ pre > code.sourceCode { white-space: pre-wrap; }
+ pre > code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
+ }
+ pre.numberSource code
+ { counter-reset: source-line 0; }
+ pre.numberSource code > span
+ { position: relative; left: -4em; counter-increment: source-line; }
+ pre.numberSource code > span > a:first-child::before
+ { content: counter(source-line);
+ position: relative; left: -1em; text-align: right; vertical-align: baseline;
+ border: none; display: inline-block;
+ -webkit-touch-callout: none; -webkit-user-select: none;
+ -khtml-user-select: none; -moz-user-select: none;
+ -ms-user-select: none; user-select: none;
+ padding: 0 4px; width: 4em;
+ color: #aaaaaa;
+ }
+ pre.numberSource { margin-left: 3em; border-left: 1px solid #aaaaaa; padding-left: 4px; }
+ div.sourceCode
+ { }
+ @media screen {
+ pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
+ }
+ code span.al { color: #ff0000; font-weight: bold; } /* Alert */
+ code span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
+ code span.at { color: #7d9029; } /* Attribute */
+ code span.bn { color: #40a070; } /* BaseN */
+ code span.bu { color: #008000; } /* BuiltIn */
+ code span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
+ code span.ch { color: #4070a0; } /* Char */
+ code span.cn { color: #880000; } /* Constant */
+ code span.co { color: #60a0b0; font-style: italic; } /* Comment */
+ code span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
+ code span.do { color: #ba2121; font-style: italic; } /* Documentation */
+ code span.dt { color: #902000; } /* DataType */
+ code span.dv { color: #40a070; } /* DecVal */
+ code span.er { color: #ff0000; font-weight: bold; } /* Error */
+ code span.ex { } /* Extension */
+ code span.fl { color: #40a070; } /* Float */
+ code span.fu { color: #06287e; } /* Function */
+ code span.im { color: #008000; font-weight: bold; } /* Import */
+ code span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
+ code span.kw { color: #007020; font-weight: bold; } /* Keyword */
+ code span.op { color: #666666; } /* Operator */
+ code span.ot { color: #007020; } /* Other */
+ code span.pp { color: #bc7a00; } /* Preprocessor */
+ code span.sc { color: #4070a0; } /* SpecialChar */
+ code span.ss { color: #bb6688; } /* SpecialString */
+ code span.st { color: #4070a0; } /* String */
+ code span.va { color: #19177c; } /* Variable */
+ code span.vs { color: #4070a0; } /* VerbatimString */
+ code span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
+ </style>
+ <link href="https://fonts.googleapis.com/css?family=Roboto|Roboto+Mono&display=swap" rel="stylesheet">
+
+ <!-- BG custom styling -->
+ <style type="text/css">
+ /* Fix for line numbers not visible */
+ pre.numberSource code > span {
+ left: -1em;
+ }
+ pre.numberSource {
+ margin-left: initial;
+ }
+
+ /* Put some space after the section numbers */
+ span.toc-section-number::after {
+ content: "\a0\a0\a0"; /* non-breaking whitespace */
+ }
+
+ /* Hide underlines on code number links */
+ pre > code.sourceCode > span > a:first-child::before {
+ text-decoration: none;
+ }
+
+ /* Color the source blocks */
+ div.sourceCode {
+ background-color: #f0f0f0;
+ }
+
+ /* Fix iOS big text rendering issue */
+ pre > code.sourceCode > span {
+ display: initial;
+ }
+
+
+ /* Color the inline code */
+ code:not(.sourceCode) {
+ background: #f0f0f0;
+ padding-left: 0.2em;
+ padding-right: 0.2em;
+ border-radius: 0.2em;
+ }
+
+ /* Keep code tags from wrapping in tables */
+ tbody code {
+ white-space: nowrap;
+ }
+
+ td {
+ vertical-align: top;
+ }
+
+ body {
+ font-size: 12pt;
+ max-width: 43em;
+ }
+
+ figure {
+ text-align: center;
+ }
+ </style>
+ <!--[if lt IE 9]>
+ <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
+ <![endif]-->
+</head>
+<body>
+<header id="title-block-header">
+<h1 class="title">Beej's Guide to Network Programming</h1>
+<p class="subtitle">Using Internet Sockets</p>
+<p class="author">Brian “Beej Jorgensen” Hall</p>
+<p class="date">v3.1.11, Copyright © April 8, 2023</p>
+</header>
+<nav id="TOC" role="doc-toc">
+<ul>
+<li><a href="#intro" id="toc-intro"><span class="toc-section-number">1</span> Intro</a>
+<ul>
+<li><a href="#audience" id="toc-audience"><span class="toc-section-number">1.1</span> Audience</a></li>
+<li><a href="#platform-and-compiler" id="toc-platform-and-compiler"><span class="toc-section-number">1.2</span> Platform and Compiler</a></li>
+<li><a href="#official-homepage-and-books-for-sale" id="toc-official-homepage-and-books-for-sale"><span class="toc-section-number">1.3</span> Official Homepage and Books For Sale</a></li>
+<li><a href="#solaris" id="toc-solaris"><span class="toc-section-number">1.4</span> Note for Solaris/SunOS Programmers</a></li>
+<li><a href="#windows" id="toc-windows"><span class="toc-section-number">1.5</span> Note for Windows Programmers</a></li>
+<li><a href="#email-policy" id="toc-email-policy"><span class="toc-section-number">1.6</span> Email Policy</a></li>
+<li><a href="#mirroring" id="toc-mirroring"><span class="toc-section-number">1.7</span> Mirroring</a></li>
+<li><a href="#note-for-translators" id="toc-note-for-translators"><span class="toc-section-number">1.8</span> Note for Translators</a></li>
+<li><a href="#legal" id="toc-legal"><span class="toc-section-number">1.9</span> Copyright, Distribution, and Legal</a></li>
+<li><a href="#dedication" id="toc-dedication"><span class="toc-section-number">1.10</span> Dedication</a></li>
+<li><a href="#publishing-information" id="toc-publishing-information"><span class="toc-section-number">1.11</span> Publishing Information</a></li>
+</ul></li>
+<li><a href="#what-is-a-socket" id="toc-what-is-a-socket"><span class="toc-section-number">2</span> What is a socket?</a>
+<ul>
+<li><a href="#two-types-of-internet-sockets" id="toc-two-types-of-internet-sockets"><span class="toc-section-number">2.1</span> Two Types of Internet Sockets</a></li>
+<li><a href="#lowlevel" id="toc-lowlevel"><span class="toc-section-number">2.2</span> Low level Nonsense and Network Theory</a></li>
+</ul></li>
+<li><a href="#ip-addresses-structs-and-data-munging" id="toc-ip-addresses-structs-and-data-munging"><span class="toc-section-number">3</span> IP Addresses, <code>struct</code>s, and Data Munging</a>
+<ul>
+<li><a href="#ip-addresses-versions-4-and-6" id="toc-ip-addresses-versions-4-and-6"><span class="toc-section-number">3.1</span> IP Addresses, versions 4 and 6</a>
+<ul>
+<li><a href="#subnets" id="toc-subnets"><span class="toc-section-number">3.1.1</span> Subnets</a></li>
+<li><a href="#port-numbers" id="toc-port-numbers"><span class="toc-section-number">3.1.2</span> Port Numbers</a></li>
+</ul></li>
+<li><a href="#byte-order" id="toc-byte-order"><span class="toc-section-number">3.2</span> Byte Order</a></li>
+<li><a href="#structs" id="toc-structs"><span class="toc-section-number">3.3</span> <code>struct</code>s</a></li>
+<li><a href="#ip-addresses-part-deux" id="toc-ip-addresses-part-deux"><span class="toc-section-number">3.4</span> IP Addresses, Part Deux</a>
+<ul>
+<li><a href="#private-or-disconnected-networks" id="toc-private-or-disconnected-networks"><span class="toc-section-number">3.4.1</span> Private (Or Disconnected) Networks</a></li>
+</ul></li>
+</ul></li>
+<li><a href="#jumping-from-ipv4-to-ipv6" id="toc-jumping-from-ipv4-to-ipv6"><span class="toc-section-number">4</span> Jumping from IPv4 to IPv6</a></li>
+<li><a href="#system-calls-or-bust" id="toc-system-calls-or-bust"><span class="toc-section-number">5</span> System Calls or Bust</a>
+<ul>
+<li><a href="#getaddrinfoprepare-to-launch" id="toc-getaddrinfoprepare-to-launch"><span class="toc-section-number">5.1</span> <code>getaddrinfo()</code>—Prepare to launch!</a></li>
+<li><a href="#socket" id="toc-socket"><span class="toc-section-number">5.2</span> <code>socket()</code>—Get the File Descriptor!</a></li>
+<li><a href="#bind" id="toc-bind"><span class="toc-section-number">5.3</span> <code>bind()</code>—What port am I on?</a></li>
+<li><a href="#connect" id="toc-connect"><span class="toc-section-number">5.4</span> <code>connect()</code>—Hey, you!</a></li>
+<li><a href="#listen" id="toc-listen"><span class="toc-section-number">5.5</span> <code>listen()</code>—Will somebody please call me?</a></li>
+<li><a href="#acceptthank-you-for-calling-port-3490." id="toc-acceptthank-you-for-calling-port-3490."><span class="toc-section-number">5.6</span> <code>accept()</code>—“Thank you for calling port 3490.”</a></li>
+<li><a href="#sendrecv" id="toc-sendrecv"><span class="toc-section-number">5.7</span> <code>send()</code> and <code>recv()</code>—Talk to me, baby!</a></li>
+<li><a href="#sendtorecv" id="toc-sendtorecv"><span class="toc-section-number">5.8</span> <code>sendto()</code> and <code>recvfrom()</code>—Talk to me, DGRAM-style</a></li>
+<li><a href="#close-and-shutdownget-outta-my-face" id="toc-close-and-shutdownget-outta-my-face"><span class="toc-section-number">5.9</span> <code>close()</code> and <code>shutdown()</code>—Get outta my face!</a></li>
+<li><a href="#getpeernamewho-are-you" id="toc-getpeernamewho-are-you"><span class="toc-section-number">5.10</span> <code>getpeername()</code>—Who are you?</a></li>
+<li><a href="#gethostnamewho-am-i" id="toc-gethostnamewho-am-i"><span class="toc-section-number">5.11</span> <code>gethostname()</code>—Who am I?</a></li>
+</ul></li>
+<li><a href="#client-server-background" id="toc-client-server-background"><span class="toc-section-number">6</span> Client-Server Background</a>
+<ul>
+<li><a href="#a-simple-stream-server" id="toc-a-simple-stream-server"><span class="toc-section-number">6.1</span> A Simple Stream Server</a></li>
+<li><a href="#a-simple-stream-client" id="toc-a-simple-stream-client"><span class="toc-section-number">6.2</span> A Simple Stream Client</a></li>
+<li><a href="#datagram" id="toc-datagram"><span class="toc-section-number">6.3</span> Datagram Sockets</a></li>
+</ul></li>
+<li><a href="#slightly-advanced-techniques" id="toc-slightly-advanced-techniques"><span class="toc-section-number">7</span> Slightly Advanced Techniques</a>
+<ul>
+<li><a href="#blocking" id="toc-blocking"><span class="toc-section-number">7.1</span> Blocking</a></li>
+<li><a href="#poll" id="toc-poll"><span class="toc-section-number">7.2</span> <code>poll()</code>—Synchronous I/O Multiplexing</a></li>
+<li><a href="#select" id="toc-select"><span class="toc-section-number">7.3</span> <code>select()</code>—Synchronous I/O Multiplexing, Old School</a></li>
+<li><a href="#sendall" id="toc-sendall"><span class="toc-section-number">7.4</span> Handling Partial <code>send()</code>s</a></li>
+<li><a href="#serialization" id="toc-serialization"><span class="toc-section-number">7.5</span> Serialization—How to Pack Data</a></li>
+<li><a href="#sonofdataencap" id="toc-sonofdataencap"><span class="toc-section-number">7.6</span> Son of Data Encapsulation</a></li>
+<li><a href="#broadcast-packetshello-world" id="toc-broadcast-packetshello-world"><span class="toc-section-number">7.7</span> Broadcast Packets—Hello, World!</a></li>
+</ul></li>
+<li><a href="#common-questions" id="toc-common-questions"><span class="toc-section-number">8</span> Common Questions</a></li>
+<li><a href="#man-pages" id="toc-man-pages"><span class="toc-section-number">9</span> Man Pages</a>
+<ul>
+<li><a href="#acceptman" id="toc-acceptman"><span class="toc-section-number">9.1</span> <code>accept()</code></a></li>
+<li><a href="#bindman" id="toc-bindman"><span class="toc-section-number">9.2</span> <code>bind()</code></a></li>
+<li><a href="#connectman" id="toc-connectman"><span class="toc-section-number">9.3</span> <code>connect()</code></a></li>
+<li><a href="#closeman" id="toc-closeman"><span class="toc-section-number">9.4</span> <code>close()</code></a></li>
+<li><a href="#getaddrinfoman" id="toc-getaddrinfoman"><span class="toc-section-number">9.5</span> <code>getaddrinfo()</code>, <code>freeaddrinfo()</code>, <code>gai_strerror()</code></a></li>
+<li><a href="#gethostnameman" id="toc-gethostnameman"><span class="toc-section-number">9.6</span> <code>gethostname()</code></a></li>
+<li><a href="#gethostbynameman" id="toc-gethostbynameman"><span class="toc-section-number">9.7</span> <code>gethostbyname()</code>, <code>gethostbyaddr()</code></a></li>
+<li><a href="#getnameinfoman" id="toc-getnameinfoman"><span class="toc-section-number">9.8</span> <code>getnameinfo()</code></a></li>
+<li><a href="#getpeernameman" id="toc-getpeernameman"><span class="toc-section-number">9.9</span> <code>getpeername()</code></a></li>
+<li><a href="#errnoman" id="toc-errnoman"><span class="toc-section-number">9.10</span> <code>errno</code></a></li>
+<li><a href="#fcntlman" id="toc-fcntlman"><span class="toc-section-number">9.11</span> <code>fcntl()</code></a></li>
+<li><a href="#htonsman" id="toc-htonsman"><span class="toc-section-number">9.12</span> <code>htons()</code>, <code>htonl()</code>, <code>ntohs()</code>, <code>ntohl()</code></a></li>
+<li><a href="#inet_ntoaman" id="toc-inet_ntoaman"><span class="toc-section-number">9.13</span> <code>inet_ntoa()</code>, <code>inet_aton()</code>, <code>inet_addr</code></a></li>
+<li><a href="#inet_ntopman" id="toc-inet_ntopman"><span class="toc-section-number">9.14</span> <code>inet_ntop()</code>, <code>inet_pton()</code></a></li>
+<li><a href="#listenman" id="toc-listenman"><span class="toc-section-number">9.15</span> <code>listen()</code></a></li>
+<li><a href="#perrorman" id="toc-perrorman"><span class="toc-section-number">9.16</span> <code>perror()</code>, <code>strerror()</code></a></li>
+<li><a href="#pollman" id="toc-pollman"><span class="toc-section-number">9.17</span> <code>poll()</code></a></li>
+<li><a href="#recvman" id="toc-recvman"><span class="toc-section-number">9.18</span> <code>recv()</code>, <code>recvfrom()</code></a></li>
+<li><a href="#selectman" id="toc-selectman"><span class="toc-section-number">9.19</span> <code>select()</code></a></li>
+<li><a href="#setsockoptman" id="toc-setsockoptman"><span class="toc-section-number">9.20</span> <code>setsockopt()</code>, <code>getsockopt()</code></a></li>
+<li><a href="#sendman" id="toc-sendman"><span class="toc-section-number">9.21</span> <code>send()</code>, <code>sendto()</code></a></li>
+<li><a href="#shutdownman" id="toc-shutdownman"><span class="toc-section-number">9.22</span> <code>shutdown()</code></a></li>
+<li><a href="#socketman" id="toc-socketman"><span class="toc-section-number">9.23</span> <code>socket()</code></a></li>
+<li><a href="#structsockaddrman" id="toc-structsockaddrman"><span class="toc-section-number">9.24</span> <code>struct sockaddr</code> and pals</a></li>
+</ul></li>
+<li><a href="#more-references" id="toc-more-references"><span class="toc-section-number">10</span> More References</a>
+<ul>
+<li><a href="#books" id="toc-books"><span class="toc-section-number">10.1</span> Books</a></li>
+<li><a href="#web-references" id="toc-web-references"><span class="toc-section-number">10.2</span> Web References</a></li>
+<li><a href="#rfcs" id="toc-rfcs"><span class="toc-section-number">10.3</span> RFCs</a></li>
+</ul></li>
+</ul>
+</nav>
+<!--
+Beej's Guide to Network Programming book source
+
+# vim: ts=4:sw=4:nosi:et:tw=72
+-->
+<!--
+ History:
+
+ 2.3.2: socket man page
+ 2.3.3: sockaddr_in man page
+ 2.3.4: bind, listen man page
+ 2.3.5: connect man page
+ 2.3.6: listen, perror man page
+ 2.3.7: errno man page
+ 2.3.8: htonl etc man page
+ 2.3.9: close man page, expanded man page leader
+ 2.3.10: inet_ntoa, setsockopt man pages
+ 2.3.11: getpeername man page
+ 2.3.12: send/sendto man pages
+ 2.3.13: shutdown man pages
+ 2.3.14: gethostname man pages, fix inet_aton links
+ 2.3.15: fcntl man page
+ 2.3.16: recv/recvfrom man page
+ 2.3.17: gethostbyname/gethostbyaddr man page
+ 2.3.18: changed GET / to GET / HTTP/1.0
+ 2.3.19: added select() man page
+ 2.3.20: added poll() man page
+ 2.3.21: section on NAT and reserved networks
+ 2.3.22: typo fixes in sects "man" and "privnet"
+ 2.3.23: added broadcast packets section
+ 2.3.24: manpage prototype changed to code, subtitle moved out of title
+ 2.4.0: big overhaul, serialization stuff
+ 2.4.1: minor text changes in intro
+ 2.4.2: changed all sizeofs to use variable names instead of types
+ 2.4.3: fix myaddr->my_addr in listener.c, sockaddr_inman example
+ 2.4.4: fix myaddr->my_addr in server.c
+ 2.4.5: fix 14->18 in son of data encap
+ 3.0.0: IPv6 overhaul
+ 3.0.1: sa-to-sa6 typo fix
+ 3.0.2: typo fixes
+ 3.0.3: typo fixes
+ 3.0.4: cut-n-paste errors, selectserver hints fix
+ 3.0.5: typo fixes
+ 3.0.6: typo fixes
+ 3.0.7: typo fixes, added front matter
+ 3.0.8: getpeername() code fixes
+ 3.0.9: getpeername() code fixes, this time fer sure
+ 3.0.10: bind() man page code fix, comment changes
+ 3.0.11: socket syscall section code fix, comment changes
+ 3.0.12: typos in "IP Addresses, structs, and Data Munging"
+ 3.0.13: amp removals, note about errno and multithreading
+ 3.0.14: type changes to listener.c, pack2.c
+ 3.0.15: fix inet_pton example
+ 3.0.16: fix simple server output, optlen in getsockopt man page
+ 3.0.17: fix small typo
+ 3.0.18: reverse perror and close calls in getaddrinfo
+ 3.0.19: add notes about O_NONBLOCK with select() under Linux
+ 3.0.20: fix missing .fd in poll() example
+ 3.0.21: change sizeof(int) to sizeof yes
+ 3.0.22: C99 updates, bug fixes, markdown
+ 3.0.23: Book reference and URL updates
+ 3.1.0: Section on poll()
+ 3.1.1: Add WSL note, telnot
+ 3.1.2: pollserver.c bugfix
+ 3.1.3: Fix freeaddrinfo memleak
+ 3.1.4: Fix accept example header files
+ 3.1.5: Fix dgram AF_UNSPEC
+-->
+<!-- prevent hyphenation of the following words: -->
+<!--
+Don't know how to make this work with underscores. I love
+you, Knuth, but... daaahm.
+
+\hyphenation{gai_strerr}
+-->
+<!--
+\hyphenation{inet_ntoa}
+\hyphenation{inet_aton}
+\hyphenation{inet_addr}
+\hyphenation{inet_ntop}
+\hyphenation{inet_pton}
+-->
+<!--
+\hyphenation{sockaddr_in}
+\hyphenation{in_addr}
+\hyphenation{sockaddr_in6}
+\hyphenation{in6_addr}
+-->
+<h1 data-number="1" id="intro"><span class="header-section-number">1</span> Intro</h1>
+<p>Hey! Socket programming got you down? Is this stuff just a little too difficult to figure out from the <code>man</code> pages? You want to do cool Internet programming, but you don’t have time to wade through a gob of <code>struct</code>s trying to figure out if you have to call <code>bind()</code> before you <code>connect()</code>, etc., etc.</p>
+<p>Well, guess what! I’ve already done this nasty business, and I’m dying to share the information with everyone! You’ve come to the right place. This document should give the average competent C programmer the edge s/he needs to get a grip on this networking noise.</p>
+<p>And check it out: I’ve finally caught up with the future (just in the nick of time, too!) and have updated the Guide for IPv6! Enjoy!</p>
+<h2 data-number="1.1" id="audience"><span class="header-section-number">1.1</span> Audience</h2>
+<p>This document has been written as a tutorial, not a complete reference. It is probably at its best when read by individuals who are just starting out with socket programming and are looking for a foothold. It is certainly not the <em>complete and total</em> guide to sockets programming, by any means.</p>
+<p>Hopefully, though, it’ll be just enough for those man pages to start making sense… <code>:-)</code></p>
+<h2 data-number="1.2" id="platform-and-compiler"><span class="header-section-number">1.2</span> Platform and Compiler</h2>
+<p>The code contained within this document was compiled on a Linux PC using Gnu’s <code>gcc</code> compiler. It should, however, build on just about any platform that uses <code>gcc</code>. Naturally, this doesn’t apply if you’re programming for Windows—see the <a href="#windows">section on Windows programming</a>, below.</p>
+<h2 data-number="1.3" id="official-homepage-and-books-for-sale"><span class="header-section-number">1.3</span> Official Homepage and Books For Sale</h2>
+<p>This official location of this document is:</p>
+<ul>
+<li><a href="https://beej.us/guide/bgnet/"><code>https://beej.us/guide/bgnet/</code></a></li>
+</ul>
+<p>There you will also find example code and translations of the guide into various languages.</p>
+<p>To buy nicely bound print copies (some call them “books”), visit:</p>
+<ul>
+<li><a href="https://beej.us/guide/url/bgbuy"><code>https://beej.us/guide/url/bgbuy</code></a></li>
+</ul>
+<p>I’ll appreciate the purchase because it helps sustain my document-writing lifestyle!</p>
+<h2 data-number="1.4" id="solaris"><span class="header-section-number">1.4</span> Note for Solaris/SunOS Programmers</h2>
+<p>When compiling for Solaris or SunOS, you need to specify some extra command-line switches for linking in the proper libraries. In order to do this, simply add “<code>-lnsl -lsocket -lresolv</code>” to the end of the compile command, like so:</p>
+<pre><code>$ cc -o server server.c -lnsl -lsocket -lresolv</code></pre>
+<p>If you still get errors, you could try further adding a <code>-lxnet</code> to the end of that command line. I don’t know what that does, exactly, but some people seem to need it.</p>
+<p>Another place that you might find problems is in the call to <code>setsockopt()</code>. The prototype differs from that on my Linux box, so instead of:</p>
+<div class="sourceCode" id="cb2"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="dt">int</span> yes<span class="op">=</span><span class="dv">1</span><span class="op">;</span></span></code></pre></div>
+<p>enter this:</p>
+<div class="sourceCode" id="cb3"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="dt">char</span> yes<span class="op">=</span><span class="ch">'1'</span><span class="op">;</span></span></code></pre></div>
+<p>As I don’t have a Sun box, I haven’t tested any of the above information—it’s just what people have told me through email.</p>
+<h2 data-number="1.5" id="windows"><span class="header-section-number">1.5</span> Note for Windows Programmers</h2>
+<p>At this point in the guide, historically, I’ve done a bit of bagging on Windows, simply due to the fact that I don’t like it very much. But I should really be fair and tell you that Windows has a huge install base and is obviously a perfectly fine operating system.</p>
+<p>They say absence makes the heart grow fonder, and in this case, I believe it to be true. (Or maybe it’s age.) But what I can say is that after a decade-plus of not using Microsoft OSes for my personal work, I’m much happier! As such, I can sit back and safely say, “Sure, feel free to use Windows!” …OK yes, it does make me grit my teeth to say that.</p>
+<p>So I still encourage you to try <a href="https://www.linux.com/">Linux</a><a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"><sup>1</sup></a>, <a href="https://bsd.org/">BSD</a><a href="#fn2" class="footnote-ref" id="fnref2" role="doc-noteref"><sup>2</sup></a>, or some flavor of Unix, instead.</p>
+<p>But people like what they like, and you Windows folk will be pleased to know that this information is generally applicable to you guys, with a few minor changes, if any.</p>
+<p>Another thing that you should strongly consider is the <a href="https://learn.microsoft.com/en-us/windows/wsl/">Windows Subsystem for Linux</a><a href="#fn3" class="footnote-ref" id="fnref3" role="doc-noteref"><sup>3</sup></a>. This basically allows you to install a Linux VM-ish thing on Windows 10. That will also definitely get you situated, and you’ll be able to build and run these programs as is.</p>
+<p>One cool thing you can do is install <a href="https://cygwin.com/">Cygwin</a><a href="#fn4" class="footnote-ref" id="fnref4" role="doc-noteref"><sup>4</sup></a>, which is a collection of Unix tools for Windows. I’ve heard on the grapevine that doing so allows all these programs to compile unmodified, but I’ve never tried it.</p>
+<p>But some of you might want to do things the Pure Windows Way. That’s very gutsy of you, and this is what you have to do: run out and get Unix immediately! No, no—I’m kidding. I’m supposed to be Windows-friendly(er) these days…</p>
+<p></p>
+<p>This is what you’ll have to do: first, ignore pretty much all of the system header files I mention in here. Instead, include:</p>
+<div class="sourceCode" id="cb4"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im"><winsock2.h></span></span>
+<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im"><ws2tcpip.h></span></span></code></pre></div>
+<p><code>winsock2</code> is the “new” (circa 1994) version of the Windows socket library.</p>
+<p>Unfortunately, if you include <code>windows.h</code>, it automatically pulls in the older <code>winsock.h</code> (version 1) header file which conflicts with <code>winsock2.h</code>! Fun times.</p>
+<p>So if you have to include <code>windows.h</code>, you need to define a macro to get it to <em>not</em> include the older header:</p>
+<div class="sourceCode" id="cb5"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="pp">#define WIN32_LEAN_AND_MEAN </span><span class="co">// Say this...</span></span>
+<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a></span>
+<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im"><windows.h></span><span class="pp"> </span><span class="co">// And now we can include that.</span></span>
+<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im"><winsock2.h></span><span class="pp"> </span><span class="co">// And this.</span></span></code></pre></div>
+<p>Wait! You also have to make a call to <code>WSAStartup()</code> before doing anything else with the sockets library. You pass in the Winsock version you desire to this function (e.g. version 2.2). And then you can check the result to make sure that version is available.</p>
+<p>The code to do that looks something like this:</p>
+<div class="sourceCode" id="cb6"><pre class="sourceCode numberSource c numberLines"><code class="sourceCode c"><span id="cb6-1"><a href="#cb6-1"></a><span class="pp">#include </span><span class="im"><winsock2.h></span></span>
+<span id="cb6-2"><a href="#cb6-2"></a></span>
+<span id="cb6-3"><a href="#cb6-3"></a><span class="op">{</span></span>
+<span id="cb6-4"><a href="#cb6-4"></a> WSADATA wsaData<span class="op">;</span></span>
+<span id="cb6-5"><a href="#cb6-5"></a></span>
+<span id="cb6-6"><a href="#cb6-6"></a> <span class="cf">if</span> <span class="op">(</span>WSAStartup<span class="op">(</span>MAKEWORD<span class="op">(</span><span class="dv">2</span><span class="op">,</span> <span class="dv">2</span><span class="op">),</span> <span class="op">&</span>wsaData<span class="op">)</span> <span class="op">!=</span> <span class="dv">0</span><span class="op">)</span> <span class="op">{</span></span>
+<span id="cb6-7"><a href="#cb6-7"></a> fprintf<span class="op">(</span>stderr<span class="op">,</span> <span class="st">"WSAStartup failed.</span><span class="sc">\n</span><span class="st">"</span><span class="op">);</span></span>
+<span id="cb6-8"><a href="#cb6-8"></a> exit<span class="op">(</span><span class="dv">1</span><span class="op">);</span></span>
+<span id="cb6-9"><a href="#cb6-9"></a> <span class="op">}</span></span>
+<span id="cb6-10"><a href="#cb6-10"></a></span>
+<span id="cb6-11"><a href="#cb6-11"></a> <span class="cf">if</span> <span class="op">(</span>LOBYTE<span class="op">(</span>wsaData<span class="op">.</span>wVersion<span class="op">)</span> <span class="op">!=</span> <span class="dv">2</span> <span class="op">||</span></span>
+<span id="cb6-12"><a href="#cb6-12"></a> HIBYTE<span class="op">(</span>wsaData<span class="op">.</span>wVersion<span class="op">)</span> <span class="op">!=</span> <span class="dv">2</span><span class="op">)</span></span>
+<span id="cb6-13"><a href="#cb6-13"></a> <span class="op">{</span></span>
+<span id="cb6-14"><a href="#cb6-14"></a> fprintf<span class="op">(</span>stderr<span class="op">,</span><span class="st">"Versiion 2.2 of Winsock is not available.</span><span class="sc">\n</span><span class="st">"</span><span class="op">);</span></span>
+<span id="cb6-15"><a href="#cb6-15"></a> WSACleanup<span class="op">();</span></span>
+<span id="cb6-16"><a href="#cb6-16"></a> exit<span class="op">(</span><span class="dv">2</span><span class="op">);</span></span>
+<span id="cb6-17"><a href="#cb6-17"></a> <span class="op">}</span></span></code></pre></div>
+<p>Note that call to <code>WSACleanup()</code> in there. That’s what you want to call when you’re done with the Winsock library.</p>
+<p>You also have to tell your compiler to link in the Winsock library, called <code>ws2_32.lib</code> for Winsock 2. Under VC++, this can be done through the <code>Project</code> menu, under <code>Settings...</code>. Click the <code>Link</code> tab, and look for the box titled “Object/library modules”. Add “ws2_32.lib” (or whichever lib is your preference) to that list.</p>
+<p>Or so I hear.</p>
+<p>Once you do that, the rest of the examples in this tutorial should generally apply, with a few exceptions. For one thing, you can’t use <code>close()</code> to close a socket—you need to use <code>closesocket()</code>, instead. Also, <code>select()</code> only works with socket descriptors, not file descriptors (like <code>0</code> for <code>stdin</code>).</p>
+<p>There is also a socket class that you can use, <a href="https://learn.microsoft.com/en-us/cpp/mfc/reference/csocket-class?view=msvc-170"><code>CSocket</code></a> Check your compiler’s help pages for more information.</p>
+<p>To get more information about Winsock, <a href="https://learn.microsoft.com/en-us/windows/win32/winsock/windows-sockets-start-page-2">check out the official page at Microsoft</a>.</p>
+<p>Finally, I hear that Windows has no <code>fork()</code> system call which is, unfortunately, used in some of my examples. Maybe you have to link in a POSIX library or something to get it to work, or you can use <code>CreateProcess()</code> instead. <code>fork()</code> takes no arguments, and <code>CreateProcess()</code> takes about 48 billion arguments. If you’re not up to that, the <code>CreateThread()</code> is a little easier to digest…unfortunately a discussion about multithreading is beyond the scope of this document. I can only talk about so much, you know!</p>
+<p>Extra finally, Steven Mitchell has <a href="https://www.tallyhawk.net/WinsockExamples/">ported a number of the examples</a><a href="#fn5" class="footnote-ref" id="fnref5" role="doc-noteref"><sup>5</sup></a> to Winsock. Check that stuff out.</p>
+<h2 data-number="1.6" id="email-policy"><span class="header-section-number">1.6</span> Email Policy</h2>
+<p>I’m generally available to help out with email questions so feel free to write in, but I can’t guarantee a response. I lead a pretty busy life and there are times when I just can’t answer a question you have. When that’s the case, I usually just delete the message. It’s nothing personal; I just won’t ever have the time to give the detailed answer you require.</p>
+<p>As a rule, the more complex the question, the less likely I am to respond. If you can narrow down your question before mailing it and be sure to include any pertinent information (like platform, compiler, error messages you’re getting, and anything else you think might help me troubleshoot), you’re much more likely to get a response. For more pointers, read ESR’s document, <a href="http://www.catb.org/~esr/faqs/smart-questions.html">How To Ask Questions The Smart Way</a><a href="#fn6" class="footnote-ref" id="fnref6" role="doc-noteref"><sup>6</sup></a>.</p>
+<p>If you don’t get a response, hack on it some more, try to find the answer, and if it’s still elusive, then write me again with the information you’ve found and hopefully it will be enough for me to help out.</p>
+<p>Now that I’ve badgered you about how to write and not write me, I’d just like to let you know that I <em>fully</em> appreciate all the praise the guide has received over the years. It’s a real morale boost, and it gladdens me to hear that it is being used for good! <code>:-)</code> Thank you!</p>
+<h2 data-number="1.7" id="mirroring"><span class="header-section-number">1.7</span> Mirroring</h2>
+<p> You are more than welcome to mirror this site, whether publicly or privately. If you publicly mirror the site and want me to link to it from the main page, drop me a line at <a href="beej@beej.us"><code>beej@beej.us</code></a>.</p>
+<h2 data-number="1.8" id="note-for-translators"><span class="header-section-number">1.8</span> Note for Translators</h2>
+<p> If you want to translate the guide into another language, write me at <a href="beej@beej.us"><code>beej@beej.us</code></a> and I’ll link to your translation from the main page. Feel free to add your name and contact info to the translation.</p>
+<p>This source markdown document uses UTF-8 encoding.</p>
+<p>Please note the license restrictions in the <a href="#legal">Copyright, Distribution, and Legal</a> section, below.</p>
+<p>If you want me to host the translation, just ask. I’ll also link to it if you want to host it; either way is fine.</p>
+<h2 data-number="1.9" id="legal"><span class="header-section-number">1.9</span> Copyright, Distribution, and Legal</h2>
+<p>Beej’s Guide to Network Programming is Copyright © 2019 Brian “Beej Jorgensen” Hall.</p>
+<p>With specific exceptions for source code and translations, below, this work is licensed under the Creative Commons Attribution- Noncommercial- No Derivative Works 3.0 License. To view a copy of this license, visit</p>
+<p><a href="https://creativecommons.org/licenses/by-nc-nd/3.0/"><code>https://creativecommons.org/licenses/by-nc-nd/3.0/</code></a></p>
+<p>or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.</p>
+<p>One specific exception to the “No Derivative Works” portion of the license is as follows: this guide may be freely translated into any language, provided the translation is accurate, and the guide is reprinted in its entirety. The same license restrictions apply to the translation as to the original guide. The translation may also include the name and contact information for the translator.</p>
+<p>The C source code presented in this document is hereby granted to the public domain, and is completely free of any license restriction.</p>
+<p>Educators are freely encouraged to recommend or supply copies of this guide to their students.</p>
+<p>Unless otherwise mutually agreed by the parties in writing, the author offers the work as-is and makes no representations or warranties of any kind concerning the work, express, implied, statutory or otherwise, including, without limitation, warranties of title, merchantability, fitness for a particular purpose, noninfringement, or the absence of latent or other defects, accuracy, or the presence of absence of errors, whether or not discoverable.</p>
+<p>Except to the extent required by applicable law, in no event will the author be liable to you on any legal theory for any special, incidental, consequential, punitive or exemplary damages arising out of the use of the work, even if the author has been advised of the possibility of such damages.</p>
+<p>Contact <a href="mailto:beej@beej.us"><code>beej@beej.us</code></a> for more information.</p>
+<h2 data-number="1.10" id="dedication"><span class="header-section-number">1.10</span> Dedication</h2>
+<p>Thanks to everyone who has helped in the past and future with me getting this guide written. And thank you to all the people who produce the Free software and packages that I use to make the Guide: GNU, Linux, Slackware, vim, Python, Inkscape, pandoc, many others. And finally a big thank-you to the literally thousands of you who have written in with suggestions for improvements and words of encouragement.</p>
+<p>I dedicate this guide to some of my biggest heroes and inpirators in the world of computers: Donald Knuth, Bruce Schneier, W. Richard Stevens, and The Woz, my Readership, and the entire Free and Open Source Software Community.</p>
+<h2 data-number="1.11" id="publishing-information"><span class="header-section-number">1.11</span> Publishing Information</h2>
+<p>This book is written in Markdown using the vim editor on an Arch Linux box loaded with GNU tools. The cover “art” and diagrams are produced with Inkscape. The Markdown is converted to HTML and LaTex/PDF by Python, Pandoc and XeLaTeX, using Liberation fonts. The toolchain is composed of 100% Free and Open Source Software.</p>
+<h1 data-number="2" id="what-is-a-socket"><span class="header-section-number">2</span> What is a socket?</h1>
+<p>You hear talk of “sockets” all the time, and perhaps you are wondering just what they are exactly. Well, they’re this: a way to speak to other programs using standard Unix file descriptors.</p>
+<p>What?</p>
+<p>Ok—you may have heard some Unix hacker state, “Jeez, <em>everything</em> in Unix is a file!” What that person may have been talking about is the fact that when Unix programs do any sort of I/O, they do it by reading or writing to a file descriptor. A file descriptor is simply an integer associated with an open file. But (and here’s the catch), that file can be a network connection, a FIFO, a pipe, a terminal, a real on-the-disk file, or just about anything else. Everything in Unix <em>is</em> a file! So when you want to communicate with another program over the Internet you’re gonna do it through a file descriptor, you’d better believe it.</p>
+<p>“Where do I get this file descriptor for network communication, Mr. Smarty-Pants?” is probably the last question on your mind right now, but I’m going to answer it anyway: You make a call to the <code>socket()</code> system routine. It returns the socket descriptor, and you communicate through it using the specialized <code>send()</code> and <code>recv()</code> (<a href="#sendman"><code>man send</code></a>, <a href="#recvman"><code>man recv</code></a>) socket calls.</p>
+<p>“But, hey!” you might be exclaiming right about now. “If it’s a file descriptor, why in the name of Neptune can’t I just use the normal <code>read()</code> and <code>write()</code> calls to communicate through the socket?” The short answer is, “You can!” The longer answer is, “You can, but <code>send()</code> and <code>recv()</code> offer much greater control over your data transmission.”</p>
+<p>What next? How about this: there are all kinds of sockets. There are DARPA Internet addresses (Internet Sockets), path names on a local node (Unix Sockets), CCITT X.25 addresses (X.25 Sockets that you can safely ignore), and probably many others depending on which Unix flavor you run. This document deals only with the first: Internet Sockets.</p>
+<h2 data-number="2.1" id="two-types-of-internet-sockets"><span class="header-section-number">2.1</span> Two Types of Internet Sockets</h2>
+<p>What’s this? There are two types of Internet sockets? Yes. Well, no. I’m lying. There are more, but I didn’t want to scare you. I’m only going to talk about two types here. Except for this sentence, where I’m going to tell you that “Raw Sockets” are also very powerful and you should look them up.</p>
+<p>All right, already. What are the two types? One is “Stream Sockets”; the other is “Datagram Sockets”, which may hereafter be referred to as “<code>SOCK_STREAM</code>” and “<code>SOCK_DGRAM</code>”, respectively. Datagram sockets are sometimes called “connectionless sockets”. (Though they can be <code>connect()</code>’d if you really want. See <a href="#connect"><code>connect()</code></a>, below.)</p>
+<p>Stream sockets are reliable two-way connected communication streams. If you output two items into the socket in the order “1, 2”, they will arrive in the order “1, 2” at the opposite end. They will also be error-free. I’m so certain, in fact, they will be error-free, that I’m just going to put my fingers in my ears and chant <em>la la la la</em> if anyone tries to claim otherwise.</p>
+<p>What uses stream sockets? Well, you may have heard of the <code>telnet</code> or <code>ssh</code> applications, yes? They use stream sockets. All the characters you type need to arrive in the same order you type them, right? Also, web browsers use the Hypertext Transfer Protocol (HTTP) which uses stream sockets to get pages. Indeed, if you telnet to a web site on port 80, and type “<code>GET / HTTP/1.0</code>” and hit RETURN twice, it’ll dump the HTML back at you!</p>
+<blockquote>
+<p>If you don’t have <code>telnet</code> installed and don’t want to install it, or your <code>telnet</code> is being picky about connecting to clients, the guide comes with a <code>telnet</code>-like program called <a href="https://beej.us/guide/bgnet/examples/telnot.c"><code>telnot</code></a><a href="#fn7" class="footnote-ref" id="fnref7" role="doc-noteref"><sup>7</sup></a>. This should work well for all the needs of the guide. (Note that telnet is actually a <a href="https://tools.ietf.org/html/rfc854">spec’d networking protocol</a><a href="#fn8" class="footnote-ref" id="fnref8" role="doc-noteref"><sup>8</sup></a>, and <code>telnot</code> doesn’t implement this protocol at all.)</p>
+</blockquote>
+<p>How do stream sockets achieve this high level of data transmission quality? They use a protocol called “The Transmission Control Protocol”, otherwise known as “TCP” (see <a href="https://tools.ietf.org/html/rfc793">RFC 793</a><a href="#fn9" class="footnote-ref" id="fnref9" role="doc-noteref"><sup>9</sup></a> for extremely detailed info on TCP). TCP makes sure your data arrives sequentially and error-free. You may have heard “TCP” before as the better half of “TCP/IP” where “IP” stands for “Internet Protocol” (see <a href="https://tools.ietf.org/html/rfc791">RFC 791</a><a href="#fn10" class="footnote-ref" id="fnref10" role="doc-noteref"><sup>10</sup></a>). IP deals primarily with Internet routing and is not generally responsible for data integrity.</p>
+<p></p>
+<p>Cool. What about Datagram sockets? Why are they called connectionless? What is the deal, here, anyway? Why are they unreliable? Well, here are some facts: if you send a datagram, it may arrive. It may arrive out of order. If it arrives, the data within the packet will be error-free.</p>
+<p>Datagram sockets also use IP for routing, but they don’t use TCP; they use the “User Datagram Protocol”, or “UDP” (see <a href="https://tools.ietf.org/html/rfc768">RFC 768</a><a href="#fn11" class="footnote-ref" id="fnref11" role="doc-noteref"><sup>11</sup></a>).</p>
+<p>Why are they connectionless? Well, basically, it’s because you don’t have to maintain an open connection as you do with stream sockets. You just build a packet, slap an IP header on it with destination information, and send it out. No connection needed. They are generally used either when a TCP stack is unavailable or when a few dropped packets here and there don’t mean the end of the Universe. Sample applications: <code>tftp</code> (trivial file transfer protocol, a little brother to FTP), <code>dhcpcd</code> (a DHCP client), multiplayer games, streaming audio, video conferencing, etc.</p>
+<p></p>
+<p>“Wait a minute! <code>tftp</code> and <code>dhcpcd</code> are used to transfer binary applications from one host to another! Data can’t be lost if you expect the application to work when it arrives! What kind of dark magic is this?”</p>
+<p>Well, my human friend, <code>tftp</code> and similar programs have their own protocol on top of UDP. For example, the tftp protocol says that for each packet that gets sent, the recipient has to send back a packet that says, “I got it!” (an “ACK” packet). If the sender of the original packet gets no reply in, say, five seconds, he’ll re-transmit the packet until he finally gets an ACK. This acknowledgment procedure is very important when implementing reliable <code>SOCK_DGRAM</code> applications.</p>
+<p>For unreliable applications like games, audio, or video, you just ignore the dropped packets, or perhaps try to cleverly compensate for them. (Quake players will know the manifestation this effect by the technical term: <em>accursed lag</em>. The word “accursed”, in this case, represents any extremely profane utterance.)</p>
+<p>Why would you use an unreliable underlying protocol? Two reasons: speed and speed. It’s way faster to fire-and-forget than it is to keep track of what has arrived safely and make sure it’s in order and all that. If you’re sending chat messages, TCP is great; if you’re sending 40 positional updates per second of the players in the world, maybe it doesn’t matter so much if one or two get dropped, and UDP is a good choice.</p>
+<h2 data-number="2.2" id="lowlevel"><span class="header-section-number">2.2</span> Low level Nonsense and Network Theory</h2>
+<p>Since I just mentioned layering of protocols, it’s time to talk about how networks really work, and to show some examples of how <code>SOCK_DGRAM</code> packets are built. Practically, you can probably skip this section. It’s good background, however.</p>
+<figure>
+<embed src="dataencap.svg" title="[Encapsulated Protocols Diagram]" />
+<figcaption aria-hidden="true">Data Encapsulation.</figcaption>
+</figure>
+<p>Hey, kids, it’s time to learn about <em>Data Encapsulation</em>! This is very very important. It’s so important that you might just learn about it if you take the networks course here at Chico State <code>;-)</code>. Basically, it says this: a packet is born, the packet is wrapped (“encapsulated”) in a header (and rarely a footer) by the first protocol (say, the TFTP protocol), then the whole thing (TFTP header included) is encapsulated again by the next protocol (say, UDP), then again by the next (IP), then again by the final protocol on the hardware (physical) layer (say, Ethernet).</p>
+<p>When another computer receives the packet, the hardware strips the Ethernet header, the kernel strips the IP and UDP headers, the TFTP program strips the TFTP header, and it finally has the data.</p>
+<p>Now I can finally talk about the infamous <em>Layered Network Model</em> (aka “ISO/OSI”). This Network Model describes a system of network functionality that has many advantages over other models. For instance, you can write sockets programs that are exactly the same without caring how the data is physically transmitted (serial, thin Ethernet, AUI, whatever) because programs on lower levels deal with it for you. The actual network hardware and topology is transparent to the socket programmer.</p>
+<p>Without any further ado, I’ll present the layers of the full-blown model. Remember this for network class exams:</p>
+<ul>
+<li>Application</li>
+<li>Presentation</li>
+<li>Session</li>
+<li>Transport</li>
+<li>Network</li>
+<li>Data Link</li>
+<li>Physical</li>
+</ul>
+<p>The Physical Layer is the hardware (serial, Ethernet, etc.). The Application Layer is just about as far from the physical layer as you can imagine—it’s the place where users interact with the network.</p>
+<p>Now, this model is so general you could probably use it as an automobile repair guide if you really wanted to. A layered model more consistent with Unix might be:</p>
+<ul>
+<li>Application Layer (<em>telnet, ftp, etc.</em>)</li>
+<li>Host-to-Host Transport Layer (<em>TCP, UDP</em>)</li>
+<li>Internet Layer (<em>IP and routing</em>)</li>
+<li>Network Access Layer (<em>Ethernet, wi-fi, or whatever</em>)</li>
+</ul>
+<p>At this point in time, you can probably see how these layers correspond to the encapsulation of the original data.</p>
+<p>See how much work there is in building a simple packet? Jeez! And you have to type in the packet headers yourself using “<code>cat</code>”! Just kidding. All you have to do for stream sockets is <code>send()</code> the data out. All you have to do for datagram sockets is encapsulate the packet in the method of your choosing and <code>sendto()</code> 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.</p>
+<p>So ends our brief foray into network theory. Oh yes, I forgot to tell you everything I wanted to say about routing: nothing! That’s right, I’m not going to talk about it at all. The router strips the packet to the IP header, consults its routing table, <em>blah blah blah</em>. Check out the <a href="https://tools.ietf.org/html/rfc791">IP RFC</a><a href="#fn12" class="footnote-ref" id="fnref12" role="doc-noteref"><sup>12</sup></a> if you really really care. If you never learn about it, well, you’ll live.</p>
+<h1 data-number="3" id="ip-addresses-structs-and-data-munging"><span class="header-section-number">3</span> IP Addresses, <code>struct</code>s, and Data Munging</h1>
+<p>Here’s the part of the game where we get to talk code for a change.</p>
+<p>But first, let’s discuss more non-code! Yay! First I want to talk about IP addresses and ports for just a tad so we have that sorted out. Then we’ll talk about how the sockets API stores and manipulates IP addresses and other data.</p>
+<h2 data-number="3.1" id="ip-addresses-versions-4-and-6"><span class="header-section-number">3.1</span> IP Addresses, versions 4 and 6</h2>
+<p>In the good old days back when Ben Kenobi was still called Obi Wan Kenobi, there was a wonderful network routing system called The Internet Protocol Version 4, also called IPv4. It had addresses made up of four bytes (A.K.A. four “octets”), and was commonly written in “dots and numbers” form, like so: <code>192.0.2.111</code>.</p>
+<p>You’ve probably seen it around.</p>
+<p>In fact, as of this writing, virtually every site on the Internet uses IPv4.</p>
+<p>Everyone, including Obi Wan, was happy. Things were great, until some naysayer by the name of Vint Cerf warned everyone that we were about to run out of IPv4 addresses!</p>
+<p>(Besides warning everyone of the Coming IPv4 Apocalypse Of Doom And Gloom, <a href="https://en.wikipedia.org/wiki/Vint_Cerf">Vint Cerf</a><a href="#fn13" class="footnote-ref" id="fnref13" role="doc-noteref"><sup>13</sup></a> is also well-known for being The Father Of The Internet. So I really am in no position to second-guess his judgment.)</p>
+<p>Run out of addresses? How could this be? I mean, there are like billions of IP addresses in a 32-bit IPv4 address. Do we really have billions of computers out there?</p>
+<p>Yes.</p>
+<p>Also, in the beginning, when there were only a few computers and everyone thought a billion was an impossibly large number, some big organizations were generously allocated millions of IP addresses for their own use. (Such as Xerox, MIT, Ford, HP, IBM, GE, AT&T, and some little company called Apple, to name a few.)</p>
+<p>In fact, if it weren’t for several stopgap measures, we would have run out a long time ago.</p>
+<p>But now we’re living in an era where we’re talking about every human having an IP address, every computer, every calculator, every phone, every parking meter, and (why not) every puppy dog, as well.</p>
+<p>And so, IPv6 was born. Since Vint Cerf is probably immortal (even if his physical form should pass on, heaven forbid, he is probably already existing as some kind of hyper-intelligent <a href="https://en.wikipedia.org/wiki/ELIZA">ELIZA</a><a href="#fn14" class="footnote-ref" id="fnref14" role="doc-noteref"><sup>14</sup></a> program out in the depths of the Internet2), no one wants to have to hear him say again “I told you so” if we don’t have enough addresses in the next version of the Internet Protocol.</p>
+<p>What does this suggest to you?</p>
+<p>That we need a <em>lot</em> more addresses. That we need not just twice as many addresses, not a billion times as many, not a thousand trillion times as many, but <em>79 MILLION BILLION TRILLION times as many possible addresses!</em> That’ll show ’em!</p>
+<p>You’re saying, “Beej, is that true? I have every reason to disbelieve large numbers.” Well, the difference between 32 bits and 128 bits might not sound like a lot; it’s only 96 more bits, right? But remember, we’re talking powers here: 32 bits represents some 4 billion numbers (2<sup>32</sup>), while 128 bits represents about 340 trillion trillion trillion numbers (for real, 2<sup>128</sup>). That’s like a million IPv4 Internets for <em>every single star in the Universe</em>.</p>
+<p>Forget this dots-and-numbers look of IPv4, too; now we’ve got a hexadecimal representation, with each two-byte chunk separated by a colon, like this:</p>
+<pre><code>2001:0db8:c9d2:aee5:73e3:934a:a5ae:9551</code></pre>
+<p>That’s not all! Lots of times, you’ll have an IP address with lots of zeros in it, and you can compress them between two colons. And you can leave off leading zeros for each byte pair. For instance, each of these pairs of addresses are equivalent:</p>
+<pre><code>2001:0db8:c9d2:0012:0000:0000:0000:0051
+2001:db8:c9d2:12::51
+
+2001:0db8:ab00:0000:0000:0000:0000:0000
+2001:db8:ab00::
+
+0000:0000:0000:0000:0000:0000:0000:0001
+::1</code></pre>
+<p>The address <code>::1</code> is the <em>loopback address</em>. It always means “this machine I’m running on now”. In IPv4, the loopback address is <code>127.0.0.1</code>.</p>
+<p>Finally, there’s an IPv4-compatibility mode for IPv6 addresses that you might come across. If you want, for example, to represent the IPv4 address <code>192.0.2.33</code> as an IPv6 address, you use the following notation: “<code>::ffff:192.0.2.33</code>”.</p>
+<p>We’re talking serious fun.</p>
+<p>In fact, it’s such serious fun, that the Creators of IPv6 have quite cavalierly lopped off trillions and trillions of addresses for reserved use, but we have so many, frankly, who’s even counting anymore? There are plenty left over for every man, woman, child, puppy, and parking meter on every planet in the galaxy. And believe me, every planet in the galaxy has parking meters. You know it’s true.</p>
+<h3 data-number="3.1.1" id="subnets"><span class="header-section-number">3.1.1</span> Subnets</h3>
+<p>For organizational reasons, it’s sometimes convenient to declare that “this first part of this IP address up through this bit is the <em>network portion</em> of the IP address, and the remainder is the <em>host portion</em>.</p>
+<p>For instance, with IPv4, you might have <code>192.0.2.12</code>, and we could say that the first three bytes are the network and the last byte was the host. Or, put another way, we’re talking about host <code>12</code> on network <code>192.0.2.0</code> (see how we zero out the byte that was the host).</p>
+<p>And now for more outdated information! Ready? In the Ancient Times, there were “classes” of subnets, where the first one, two, or three bytes of the address was the network part. If you were lucky enough to have one byte for the network and three for the host, you could have 24 bits-worth of hosts on your network (16 million or so). That was a “Class A” network. On the opposite end was a “Class C”, with three bytes of network, and one byte of host (256 hosts, minus a couple that were reserved).</p>
+<p>So as you can see, there were just a few Class As, a huge pile of Class Cs, and some Class Bs in the middle.</p>
+<p>The network portion of the IP address is described by something called the <em>netmask</em>, which you bitwise-AND with the IP address to get the network number out of it. The netmask usually looks something like <code>255.255.255.0</code>. (E.g. with that netmask, if your IP is <code>192.0.2.12</code>, then your network is <code>192.0.2.12</code> AND <code>255.255.255.0</code> which gives <code>192.0.2.0</code>.)</p>
+<p>Unfortunately, it turned out that this wasn’t fine-grained enough for the eventual needs of the Internet; we were running out of Class C networks quite quickly, and we were most definitely out of Class As, so don’t even bother to ask. To remedy this, The Powers That Be allowed for the netmask to be an arbitrary number of bits, not just 8, 16, or 24. So you might have a netmask of, say <code>255.255.255.252</code>, which is 30 bits of network, and 2 bits of host allowing for four hosts on the network. (Note that the netmask is <em>ALWAYS</em> a bunch of 1-bits followed by a bunch of 0-bits.)</p>
+<p>But it’s a bit unwieldy to use a big string of numbers like <code>255.192.0.0</code> as a netmask. First of all, people don’t have an intuitive idea of how many bits that is, and secondly, it’s really not compact. So the New Style came along, and it’s much nicer. You just put a slash after the IP address, and then follow that by the number of network bits in decimal. Like this: <code>192.0.2.12/30</code>.</p>
+<p>Or, for IPv6, something like this: <code>2001:db8::/32</code> or <code>2001:db8:5413:4028::9db9/64</code>.</p>
+<h3 data-number="3.1.2" id="port-numbers"><span class="header-section-number">3.1.2</span> Port Numbers</h3>
+<p>If you’ll kindly remember, I presented you earlier with the <a href="#lowlevel">Layered Network Model</a> which had the Internet Layer (IP) split off from the Host-to-Host Transport Layer (TCP and UDP). Get up to speed on that before the next paragraph.</p>
+<p>Turns out that besides an IP address (used by the IP layer), there is another address that is used by TCP (stream sockets) and, coincidentally, by UDP (datagram sockets). It is the <em>port number</em>. It’s a 16-bit number that’s like the local address for the connection.</p>
+<p>Think of the IP address as the street address of a hotel, and the port number as the room number. That’s a decent analogy; maybe later I’ll come up with one involving the automobile industry.</p>
+<p>Say you want to have a computer that handles incoming mail AND web services—how do you differentiate between the two on a computer with a single IP address?</p>
+<p>Well, different services on the Internet have different well-known port numbers. You can see them all in <a href="https://www.iana.org/assignments/port-numbers">the Big IANA Port List</a><a href="#fn15" class="footnote-ref" id="fnref15" role="doc-noteref"><sup>15</sup></a> or, if you’re on a Unix box, in your <code>/etc/services</code> file. HTTP (the web) is port 80, telnet is port 23, SMTP is port 25, the game <a href="https://en.wikipedia.org/wiki/Doom_(1993_video_game)">DOOM</a><a href="#fn16" class="footnote-ref" id="fnref16" role="doc-noteref"><sup>16</sup></a> used port 666, etc. and so on. Ports under 1024 are often considered special, and usually require special OS privileges to use.</p>
+<p>And that’s about it!</p>
+<h2 data-number="3.2" id="byte-order"><span class="header-section-number">3.2</span> Byte Order</h2>
+<p> By Order of the Realm! There shall be two byte orderings, hereafter to be known as Lame and Magnificent!</p>
+<p>I joke, but one really is better than the other. <code>:-)</code></p>
+<p>There really is no easy way to say this, so I’ll just blurt it out: your computer might have been storing bytes in reverse order behind your back. I know! No one wanted to have to tell you.</p>
+<p>The thing is, everyone in the Internet world has generally agreed that if you want to represent the two-byte hex number, say <code>b34f</code>, you’ll store it in two sequential bytes <code>b3</code> followed by <code>4f</code>. Makes sense, and, as <a href="https://en.wikipedia.org/wiki/Wilford_Brimley">Wilford Brimley</a><a href="#fn17" class="footnote-ref" id="fnref17" role="doc-noteref"><sup>17</sup></a> would tell you, it’s the Right Thing To Do. This number, stored with the big end first, is called <em>Big-Endian</em>.</p>
+<p>Unfortunately, a <em>few</em> computers scattered here and there throughout the world, namely anything with an Intel or Intel-compatible processor, store the bytes reversed, so <code>b34f</code> would be stored in memory as the sequential bytes <code>4f</code> followed by <code>b3</code>. This storage method is called <em>Little-Endian</em>.</p>
+<p>But wait, I’m not done with terminology yet! The more-sane <em>Big-Endian</em> is also called <em>Network Byte Order</em> because that’s the order us network types like.</p>
+<p>Your computer stores numbers in <em>Host Byte Order</em>. If it’s an Intel 80x86, Host Byte Order is Little-Endian. If it’s a Motorola 68k, Host Byte Order is Big-Endian. If it’s a PowerPC, Host Byte Order is… well, it depends!</p>
+<p>A lot of times when you’re building packets or filling out data structures you’ll need to make sure your two- and four-byte numbers are in Network Byte Order. But how can you do this if you don’t know the native Host Byte Order?</p>
+<p>Good news! You just get to assume the Host Byte Order isn’t right, and you always run the value through a function to set it to Network Byte Order. The function will do the magic conversion if it has to, and this way your code is portable to machines of differing endianness.</p>
+<p>All righty. There are two types of numbers that you can convert: <code>short</code> (two bytes) and <code>long</code> (four bytes). These functions work for the <code>unsigned</code> variations as well. Say you want to convert a <code>short</code> from Host Byte Order to Network Byte Order. Start with “h” for “host”, follow it with “to”, then “n” for “network”, and “s” for “short”: h-to-n-s, or <code>htons()</code> (read: “Host to Network Short”).</p>
+<p>It’s almost too easy…</p>
+<p>You can use every combination of “n”, “h”, “s”, and “l” you want, not counting the really stupid ones. For example, there is NOT a <code>stolh()</code> (“Short to Long Host”) function—not at this party, anyway. But there are:</p>
+<table>
+<colgroup>
+<col style="width: 26%" />
+<col style="width: 73%" />
+</colgroup>
+<thead>
+<tr class="header">
+<th>Function</th>
+<th>Description</th>
+</tr>
+</thead>
+<tbody>
+<tr class="odd">
+<td><code>htons()</code></td>
+<td><code>h</code>ost <code>to</code> <code>n</code>etwork <code>s</code>hort</td>
+</tr>
+<tr class="even">
+<td><code>htonl()</code></td>
+<td><code>h</code>ost <code>to</code> <code>n</code>etwork <code>l</code>ong</td>
+</tr>
+<tr class="odd">
+<td><code>ntohs()</code></td>
+<td><code>n</code>etwork <code>to</code> <code>h</code>ost <code>s</code>hort</td>
+</tr>
+<tr class="even">
+<td><code>ntohl()</code></td>
+<td><code>n</code>etwork <code>to</code> <code>h</code>ost <code>l</code>ong</td>
+</tr>
+</tbody>
+</table>
+<p>Basically, you’ll want to convert the numbers to Network Byte Order before they go out on the wire, and convert them to Host Byte Order as they come in off the wire.</p>
+<p>I don’t know of a 64-bit variant, sorry. And if you want to do floating point, check out the section on <a href="#serialization">Serialization</a>, far below.</p>
+<p>Assume the numbers in this document are in Host Byte Order unless I say otherwise.</p>
+<h2 data-number="3.3" id="structs"><span class="header-section-number">3.3</span> <code>struct</code>s</h2>
+<p>Well, we’re finally here. It’s time to talk about programming. In this section, I’ll cover various data types used by the sockets interface, since some of them are a real bear to figure out.</p>
+<p>First the easy one: a socket descriptor. A socket descriptor is the following type:</p>
+<div class="sourceCode" id="cb9"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a><span class="dt">int</span></span></code></pre></div>
+<p>Just a regular <code>int</code>.</p>
+<p>Things get weird from here, so just read through and bear with me.</p>
+<p>My First Struct™—<code>struct addrinfo</code>. This structure is a more recent invention, and is used to prep the socket address structures for subsequent use. It’s also used in host name lookups, and service name lookups. That’ll make more sense later when we get to actual usage, but just know for now that it’s one of the first things you’ll call when making a connection.</p>
+<div class="sourceCode" id="cb10"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="kw">struct</span> addrinfo <span class="op">{</span></span>
+<span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a> <span class="dt">int</span> ai_flags<span class="op">;</span> <span class="co">// AI_PASSIVE, AI_CANONNAME, etc.</span></span>
+<span id="cb10-3"><a href="#cb10-3" aria-hidden="true" tabindex="-1"></a> <span class="dt">int</span> ai_family<span class="op">;</span> <span class="co">// AF_INET, AF_INET6, AF_UNSPEC</span></span>
+<span id="cb10-4"><a href="#cb10-4" aria-hidden="true" tabindex="-1"></a> <span class="dt">int</span> ai_socktype<span class="op">;</span> <span class="co">// SOCK_STREAM, SOCK_DGRAM</span></span>
+<span id="cb10-5"><a href="#cb10-5" aria-hidden="true" tabindex="-1"></a> <span class="dt">int</span> ai_protocol<span class="op">;</span> <span class="co">// use 0 for "any"</span></span>
+<span id="cb10-6"><a href="#cb10-6" aria-hidden="true" tabindex="-1"></a> <span class="dt">size_t</span> ai_addrlen<span class="op">;</span> <span class="co">// size of ai_addr in bytes</span></span>
+<span id="cb10-7"><a href="#cb10-7" aria-hidden="true" tabindex="-1"></a> <span class="kw">struct</span> sockaddr <span class="op">*</span>ai_addr<span class="op">;</span> <span class="co">// struct sockaddr_in or _in6</span></span>
+<span id="cb10-8"><a href="#cb10-8" aria-hidden="true" tabindex="-1"></a> <span class="dt">char</span> <span class="op">*</span>ai_canonname<span class="op">;</span> <span class="co">// full canonical hostname</span></span>
+<span id="cb10-9"><a href="#cb10-9" aria-hidden="true" tabindex="-1"></a></span>
+<span id="cb10-10"><a href="#cb10-10" aria-hidden="true" tabindex="-1"></a> <span class="kw">struct</span> addrinfo <span class="op">*</span>ai_next<span class="op">;</span> <span class="co">// linked list, next node</span></span>
+<span id="cb10-11"><a href="#cb10-11" aria-hidden="true" tabindex="-1"></a><span class="op">};</span></span></code></pre></div>
+<p>You’ll load this struct up a bit, and then call <code>getaddrinfo()</code>. It’ll return a pointer to a new linked list of these structures filled out with all the goodies you need.</p>
+<p>You can force it to use IPv4 or IPv6 in the <code>ai_family</code> field, or leave it as <code>AF_UNSPEC</code> to use whatever. This is cool because your code can be IP version-agnostic.</p>
+<p>Note that this is a linked list: <code>ai_next</code> points at the next element—there could be several results for you to choose from. I’d use the first result that worked, but you might have different business needs; I don’t know everything, man!</p>
+<p>You’ll see that the <code>ai_addr</code> field in the <code>struct addrinfo</code> is a pointer to a <code>struct sockaddr</code>. This is where we start getting into the nitty-gritty details of what’s inside an IP address structure.</p>
+<p>You might not usually need to write to these structures; oftentimes, a call to <code>getaddrinfo()</code> to fill out your <code>struct addrinfo</code> for you is all you’ll need. You <em>will</em>, however, have to peer inside these <code>struct</code>s to get the values out, so I’m presenting them here.</p>
+<p>(Also, all the code written before <code>struct addrinfo</code> was invented we packed all this stuff by hand, so you’ll see a lot of IPv4 code out in the wild that does exactly that. You know, in old versions of this guide and so on.)</p>
+<p>Some <code>struct</code>s are IPv4, some are IPv6, and some are both. I’ll make notes of which are what.</p>
+<p>Anyway, the <code>struct sockaddr</code> holds socket address information for many types of sockets.</p>
+<div class="sourceCode" id="cb11"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a><span class="kw">struct</span> sockaddr <span class="op">{</span></span>
+<span id="cb11-2"><a href="#cb11-2" aria-hidden="true" tabindex="-1"></a> <span class="dt">unsigned</span> <span class="dt">short</span> sa_family<span class="op">;</span> <span class="co">// address family, AF_xxx</span></span>
+<span id="cb11-3"><a href="#cb11-3" aria-hidden="true" tabindex="-1"></a> <span class="dt">char</span> sa_data<span class="op">[</span><span class="dv">14</span><span class="op">];</span> <span class="co">// 14 bytes of protocol address</span></span>
+<span id="cb11-4"><a href="#cb11-4" aria-hidden="true" tabindex="-1"></a><span class="op">};</span> </span></code></pre></div>
+<p><code>sa_family</code> can be a variety of things, but it’ll be <code>AF_INET</code> (IPv4) or <code>AF_INET6</code> (IPv6) for everything we do in this document. <code>sa_data</code> contains a destination address and port number for the socket. This is rather unwieldy since you don’t want to tediously pack the address in the <code>sa_data</code> by hand.</p>
+<p>To deal with <code>struct sockaddr</code>, programmers created a parallel structure: <code>struct sockaddr_in</code> (“in” for “Internet”) to be used with IPv4.</p>
+<p>And <em>this is the important</em> bit: a pointer to a <code>struct sockaddr_in</code> can be cast to a pointer to a <code>struct sockaddr</code> and vice-versa. So even though <code>connect()</code> wants a <code>struct sockaddr*</code>, you can still use a <code>struct sockaddr_in</code> and cast it at the last minute!</p>
+<div class="sourceCode" id="cb12"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="co">// (IPv4 only--see struct sockaddr_in6 for IPv6)</span></span>
+<span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a></span>
+<span id="cb12-3"><a href="#cb12-3" aria-hidden="true" tabindex="-1"></a><span class="kw">struct</span> sockaddr_in <span class="op">{</span></span>
+<span id="cb12-4"><a href="#cb12-4" aria-hidden="true" tabindex="-1"></a> <span class="dt">short</span> <span class="dt">int</span> sin_family<span class="op">;</span> <span class="co">// Address family, AF_INET</span></span>
+<span id="cb12-5"><a href="#cb12-5" aria-hidden="true" tabindex="-1"></a> <span class="dt">unsigned</span> <span class="dt">short</span> <span class="dt">int</span> sin_port<span class="op">;</span> <span class="co">// Port number</span></span>
+<span id="cb12-6"><a href="#cb12-6" aria-hidden="true" tabindex="-1"></a> <span class="kw">struct</span> in_addr sin_addr<span class="op">;</span> <span class="co">// Internet address</span></span>
+<span id="cb12-7"><a href="#cb12-7" aria-hidden="true" tabindex="-1"></a> <span class="dt">unsigned</span> <span class="dt">char</span> sin_zero<span class="op">[</span><span class="dv">8</span><span class="op">];</span> <span class="co">// Same size as struct sockaddr</span></span>
+<span id="cb12-8"><a href="#cb12-8" aria-hidden="true" tabindex="-1"></a><span class="op">};</span></span></code></pre></div>
+<p>This structure makes it easy to reference elements of the socket address. Note that <code>sin_zero</code> (which is included to pad the structure to the length of a <code>struct sockaddr</code>) should be set to all zeros with the function <code>memset()</code>. Also, notice that <code>sin_family</code> corresponds to <code>sa_family</code> in a <code>struct sockaddr</code> and should be set to “<code>AF_INET</code>”. Finally, the <code>sin_port</code> must be in <em>Network Byte Order</em> (by using <code>htons()</code>!)</p>
+<p>Let’s dig deeper! You see the <code>sin_addr</code> field is a <code>struct in_addr</code>. What is that thing? Well, not to be overly dramatic, but it’s one of the scariest unions of all time:</p>
+<div class="sourceCode" id="cb13"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a><span class="co">// (IPv4 only--see struct in6_addr for IPv6)</span></span>
+<span id="cb13-2"><a href="#cb13-2" aria-hidden="true" tabindex="-1"></a></span>
+<span id="cb13-3"><a href="#cb13-3" aria-hidden="true" tabindex="-1"></a><span class="co">// Internet address (a structure for historical reasons)</span></span>
+<span id="cb13-4"><a href="#cb13-4" aria-hidden="true" tabindex="-1"></a><span class="kw">struct</span> in_addr <span class="op">{</span></span>
+<span id="cb13-5"><a href="#cb13-5" aria-hidden="true" tabindex="-1"></a> <span class="dt">uint32_t</span> s_addr<span class="op">;</span> <span class="co">// that's a 32-bit int (4 bytes)</span></span>
+<span id="cb13-6"><a href="#cb13-6" aria-hidden="true" tabindex="-1"></a><span class="op">};</span></span></code></pre></div>
+<p>Whoa! Well, it <em>used</em> to be a union, but now those days seem to be gone. Good riddance. So if you have declared <code>ina</code> to be of type <code>struct sockaddr_in</code>, then <code>ina.sin_addr.s_addr</code> references the 4-byte IP address (in Network Byte Order). Note that even if your system still uses the God-awful union for <code>struct in_addr</code>, you can still reference the 4-byte IP address in exactly the same way as I did above (this due to <code>#define</code>s).</p>
+<p>What about IPv6? Similar <code>struct</code>s exist for it, as well:</p>
+<div class="sourceCode" id="cb14"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true" tabindex="-1"></a><span class="co">// (IPv6 only--see struct sockaddr_in and struct in_addr for IPv4)</span></span>
+<span id="cb14-2"><a href="#cb14-2" aria-hidden="true" tabindex="-1"></a></span>
+<span id="cb14-3"><a href="#cb14-3" aria-hidden="true" tabindex="-1"></a><span class="kw">struct</span> sockaddr_in6 <span class="op">{</span></span>
+<span id="cb14-4"><a href="#cb14-4" aria-hidden="true" tabindex="-1"></a> u_int16_t sin6_family<span class="op">;</span> <span class="co">// address family, AF_INET6</span></span>
+<span id="cb14-5"><a href="#cb14-5" aria-hidden="true" tabindex="-1"></a> u_int16_t sin6_port<span class="op">;</span> <span class="co">// port number, Network Byte Order</span></span>
+<span id="cb14-6"><a href="#cb14-6" aria-hidden="true" tabindex="-1"></a> u_int32_t sin6_flowinfo<span class="op">;</span> <span class="co">// IPv6 flow information</span></span>
+<span id="cb14-7"><a href="#cb14-7" aria-hidden="true" tabindex="-1"></a> <span class="kw">struct</span> in6_addr sin6_addr<span class="op">;</span> <span class="co">// IPv6 address</span></span>
+<span id="cb14-8"><a href="#cb14-8" aria-hidden="true" tabindex="-1"></a> u_int32_t sin6_scope_id<span class="op">;</span> <span class="co">// Scope ID</span></span>
+<span id="cb14-9"><a href="#cb14-9" aria-hidden="true" tabindex="-1"></a><span class="op">};</span></span>
+<span id="cb14-10"><a href="#cb14-10" aria-hidden="true" tabindex="-1"></a></span>
+<span id="cb14-11"><a href="#cb14-11" aria-hidden="true" tabindex="-1"></a><span class="kw">struct</span> in6_addr <span class="op">{</span></span>
+<span id="cb14-12"><a href="#cb14-12" aria-hidden="true" tabindex="-1"></a> <span class="dt">unsigned</span> <span class="dt">char</span> s6_addr<span class="op">[</span><span class="dv">16</span><span class="op">];</span> <span class="co">// IPv6 address</span></span>
+<span id="cb14-13"><a href="#cb14-13" aria-hidden="true" tabindex="-1"></a><span class="op">};</span></span></code></pre></div>
+<p>Note that IPv6 has an IPv6 address and a port number, just like IPv4 has an IPv4 address and a port number.</p>
+<p>Also note that I’m not going to talk about the IPv6 flow information or Scope ID fields for the moment… this is just a starter guide. <code>:-)</code></p>
+<p>Last but not least, here is another simple structure, <code>struct sockaddr_storage</code> that is designed to be large enough to hold both IPv4 and IPv6 structures. See, for some calls, sometimes you don’t know in advance if it’s going to fill out your <code>struct sockaddr</code> with an IPv4 or IPv6 address. So you pass in this parallel structure, very similar to <code>struct sockaddr</code> except larger, and then cast it to the type you need:</p>
+<div class="sourceCode" id="cb15"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a><span class="kw">struct</span> sockaddr_storage <span class="op">{</span></span>
+<span id="cb15-2"><a href="#cb15-2" aria-hidden="true" tabindex="-1"></a> sa_family_t ss_family<span class="op">;</span> <span class="co">// address family</span></span>
+<span id="cb15-3"><a href="#cb15-3" aria-hidden="true" tabindex="-1"></a></span>
+<span id="cb15-4"><a href="#cb15-4" aria-hidden="true" tabindex="-1"></a> <span class="co">// all this is padding, implementation specific, ignore it:</span></span>
+<span id="cb15-5"><a href="#cb15-5" aria-hidden="true" tabindex="-1"></a> <span class="dt">char</span> __ss_pad1<span class="op">[</span>_SS_PAD1SIZE<span class="op">];</span></span>
+<span id="cb15-6"><a href="#cb15-6" aria-hidden="true" tabindex="-1"></a> <span class="dt">int64_t</span> __ss_align<span class="op">;</span></span>
+<span id="cb15-7"><a href="#cb15-7" aria-hidden="true" tabindex="-1"></a> <span class="dt">char</span> __ss_pad2<span class="op">[</span>_SS_PAD2SIZE<span class="op">];</span></span>
+<span id="cb15-8"><a href="#cb15-8" aria-hidden="true" tabindex="-1"></a><span class="op">};</span></span></code></pre></div>
+<p>What’s important is that you can see the address family in the <code>ss_family</code> field—check this to see if it’s <code>AF_INET</code> or <code>AF_INET6</code> (for IPv4 or IPv6). Then you can cast it to a <code>struct sockaddr_in</code> or <code>struct sockaddr_in6</code> if you wanna.</p>
+<h2 data-number="3.4" id="ip-addresses-part-deux"><span class="header-section-number">3.4</span> IP Addresses, Part Deux</h2>
+<p>Fortunately for you, there are a bunch of functions that allow you to manipulate IP addresses. No need to figure them out by hand and stuff them in a <code>long</code> with the <code><<</code> operator.</p>
+<p>First, let’s say you have a <code>struct sockaddr_in ina</code>, and you have an IP address “<code>10.12.110.57</code>” or “<code>2001:db8:63b3:1::3490</code>” that you want to store into it. The function you want to use, <code>inet_pton()</code>, converts an IP address in numbers-and-dots notation into either a <code>struct in_addr</code> or a <code>struct in6_addr</code> depending on whether you specify <code>AF_INET</code> or <code>AF_INET6</code>. (“<code>pton</code>” stands for “presentation to network”—you can call it “printable to network” if that’s easier to remember.) The conversion can be made as follows:</p>
+<div class="sourceCode" id="cb16"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a><span class="kw">struct</span> sockaddr_in sa<span class="op">;</span> <span class="co">// IPv4</span></span>
+<span id="cb16-2"><a href="#cb16-2" aria-hidden="true" tabindex="-1"></a><span class="kw">struct</span> sockaddr_in6 sa6<span class="op">;</span> <span class="co">// IPv6</span></span>
+<span id="cb16-3"><a href="#cb16-3" aria-hidden="true" tabindex="-1"></a></span>
+<span id="cb16-4"><a href="#cb16-4" aria-hidden="true" tabindex="-1"></a>inet_pton<span class="op">(</span>AF_INET<span class="op">,</span> <span class="st">"10.12.110.57"</span><span class="op">,</span> <span class="op">&(</span>sa<span class="op">.</span>sin_addr<span class="op">));</span> <span class="co">// IPv4</span></span>
+<span id="cb16-5"><a href="#cb16-5" aria-hidden="true" tabindex="-1"></a>inet_pton<span class="op">(</span>AF_INET6<span class="op">,</span> <span class="st">"2001:db8:63b3:1::3490"</span><span class="op">,</span> <span class="op">&(</span>sa6<span class="op">.</span>sin6_addr<span class="op">));</span> <span class="co">// IPv6</span></span></code></pre></div>
+<p>(Quick note: the old way of doing things used a function called <code>inet_addr()</code> or another function called <code>inet_aton()</code>; these are now obsolete and don’t work with IPv6.)</p>
+<p>Now, the above code snippet isn’t very robust because there is no error checking. See, <code>inet_pton()</code> returns <code>-1</code> on error, or 0 if the address is messed up. So check to make sure the result is greater than 0 before using!</p>
+<p>All right, now you can convert string IP addresses to their binary representations. What about the other way around? What if you have a <code>struct in_addr</code> and you want to print it in numbers-and-dots notation? (Or a <code>struct in6_addr</code> that you want in, uh, “hex-and-colons” notation.) In this case, you’ll want to use the function <code>inet_ntop()</code> (“ntop” means “network to presentation”—you can call it “network to printable” if that’s easier to remember), like this:</p>
+<div class="sourceCode" id="cb17"><pre class="sourceCode numberSource c numberLines"><code class="sourceCode c"><span id="cb17-1"><a href="#cb17-1"></a><span class="co">// IPv4:</span></span>
+<span id="cb17-2"><a href="#cb17-2"></a></span>
+<span id="cb17-3"><a href="#cb17-3"></a><span class="dt">char</span> ip4<span class="op">[</span>INET_ADDRSTRLEN<span class="op">];</span> <span class="co">// space to hold the IPv4 string</span></span>
+<span id="cb17-4"><a href="#cb17-4"></a><span class="kw">struct</span> sockaddr_in sa<span class="op">;</span> <span class="co">// pretend this is loaded with something</span></span>
+<span id="cb17-5"><a href="#cb17-5"></a></span>
+<span id="cb17-6"><a href="#cb17-6"></a>inet_ntop<span class="op">(</span>AF_INET<span class="op">,</span> <span class="op">&(</span>sa<span class="op">.</span>sin_addr<span class="op">),</span> ip4<span class="op">,</span> INET_ADDRSTRLEN<span class="op">);</span></span>
+<span id="cb17-7"><a href="#cb17-7"></a></span>
+<span id="cb17-8"><a href="#cb17-8"></a>printf<span class="op">(</span><span class="st">"The IPv4 address is: </span><span class="sc">%s\n</span><span class="st">"</span><span class="op">,</span> ip4<span class="op">);</span></span>
+<span id="cb17-9"><a href="#cb17-9"></a></span>
+<span id="cb17-10"><a href="#cb17-10"></a></span>
+<span id="cb17-11"><a href="#cb17-11"></a><span class="co">// IPv6:</span></span>
+<span id="cb17-12"><a href="#cb17-12"></a></span>
+<span id="cb17-13"><a href="#cb17-13"></a><span class="dt">char</span> ip6<span class="op">[</span>INET6_ADDRSTRLEN<span class="op">];</span> <span class="co">// space to hold the IPv6 string</span></span>
+<span id="cb17-14"><a href="#cb17-14"></a><span class="kw">struct</span> sockaddr_in6 sa6<span class="op">;</span> <span class="co">// pretend this is loaded with something</span></span>
+<span id="cb17-15"><a href="#cb17-15"></a></span>
+<span id="cb17-16"><a href="#cb17-16"></a>inet_ntop<span class="op">(</span>AF_INET6<span class="op">,</span> <span class="op">&(</span>sa6<span class="op">.</span>sin6_addr<span class="op">),</span> ip6<span class="op">,</span> INET6_ADDRSTRLEN<span class="op">);</span></span>
+<span id="cb17-17"><a href="#cb17-17"></a></span>
+<span id="cb17-18"><a href="#cb17-18"></a>printf<span class="op">(</span><span class="st">"The address is: </span><span class="sc">%s\n</span><span class="st">"</span><span class="op">,</span> ip6<span class="op">);</span></span></code></pre></div>
+<p>When you call it, you’ll pass the address type (IPv4 or IPv6), the address, a pointer to a string to hold the result, and the maximum length of that string. (Two macros conveniently hold the size of the string you’ll need to hold the largest IPv4 or IPv6 address: <code>INET_ADDRSTRLEN</code> and <code>INET6_ADDRSTRLEN</code>.)</p>
+<p>(Another quick note to mention once again the old way of doing things: the historical function to do this conversion was called <code>inet_ntoa()</code>. It’s also obsolete and won’t work with IPv6.)</p>
+<p>Lastly, these functions only work with numeric IP addresses—they won’t do any nameserver DNS lookup on a hostname, like “<code>www.example.com</code>”. You will use <code>getaddrinfo()</code> to do that, as you’ll see later on.</p>
+<h3 data-number="3.4.1" id="private-or-disconnected-networks"><span class="header-section-number">3.4.1</span> Private (Or Disconnected) Networks</h3>
+<p> Lots of places have a firewall that hides the network from the rest of the world for their own protection. And often times, the firewall translates “internal” IP addresses to “external” (that everyone else in the world knows) IP addresses using a process called <em>Network Address Translation</em>, or NAT.</p>
+<p>Are you getting nervous yet? “Where’s he going with all this weird stuff?”</p>
+<p>Well, relax and buy yourself a non-alcoholic (or alcoholic) drink, because as a beginner, you don’t even have to worry about NAT, since it’s done for you transparently. But I wanted to talk about the network behind the firewall in case you started getting confused by the network numbers you were seeing.</p>
+<p>For instance, I have a firewall at home. I have two static IPv4 addresses allocated to me by the DSL company, and yet I have seven computers on the network. How is this possible? Two computers can’t share the same IP address, or else the data wouldn’t know which one to go to!</p>
+<p>The answer is: they don’t share the same IP addresses. They are on a private network with 24 million IP addresses allocated to it. They are all just for me. Well, all for me as far as anyone else is concerned. Here’s what’s happening:</p>
+<p>If I log into a remote computer, it tells me I’m logged in from 192.0.2.33 which is the public IP address my ISP has provided to me. But if I ask my local computer what its IP address is, it says 10.0.0.5. Who is translating the IP address from one to the other? That’s right, the firewall! It’s doing NAT!</p>
+<p><code>10.x.x.x</code> is one of a few reserved networks that are only to be used either on fully disconnected networks, or on networks that are behind firewalls. The details of which private network numbers are available for you to use are outlined in <a href="https://tools.ietf.org/html/rfc1918">RFC 1918</a><a href="#fn18" class="footnote-ref" id="fnref18" role="doc-noteref"><sup>18</sup></a>, but some common ones you’ll see are <code>10.x.x.x</code> and <code>192.168.x.x</code>, where <code>x</code> is 0-255, generally. Less common is <code>172.y.x.x</code>, where <code>y</code> goes between 16 and 31.</p>
+<p>Networks behind a NATing firewall don’t <em>need</em> to be on one of these reserved networks, but they commonly are.</p>
+<p>(Fun fact! My external IP address isn’t really <code>192.0.2.33</code>. The <code>192.0.2.x</code> network is reserved for make-believe “real” IP addresses to be used in documentation, just like this guide! Wowzers!)</p>
+<p> IPv6 has private networks, too, in a sense. They’ll start with <code>fdXX:</code> (or maybe in the future <code>fcXX:</code>), as per <a href="https://tools.ietf.org/html/rfc4193">RFC 4193</a><a href="#fn19" class="footnote-ref" id="fnref19" role="doc-noteref"><sup>19</sup></a>. NAT and IPv6 don’t generally mix, however (unless you’re doing the IPv6 to IPv4 gateway thing which is beyond the scope of this document)—in theory you’ll have so many addresses at your disposal that you won’t need to use NAT any longer. But if you want to allocate addresses for yourself on a network that won’t route outside, this is how to do it.</p>
+<h1 data-number="4" id="jumping-from-ipv4-to-ipv6"><span class="header-section-number">4</span> Jumping from IPv4 to IPv6</h1>
+<p></p>
+<p>But I just want to know what to change in my code to get it going with IPv6! Tell me now!</p>
+<p>Ok! Ok!</p>
+<p>Almost everything in here is something I’ve gone over, above, but it’s the short version for the impatient. (Of course, there is more than this, but this is what applies to the guide.)</p>
+<ol type="1">
+<li><p>First of all, try to use <a href="#structs"><code>getaddrinfo()</code></a> to get all the <code>struct sockaddr</code> info, instead of packing the structures by hand. This will keep you IP version-agnostic, and will eliminate many of the subsequent steps.</p></li>
+<li><p>Any place that you find you’re hard-coding anything related to the IP version, try to wrap up in a helper function.</p></li>
+<li><p>Change <code>AF_INET</code> to <code>AF_INET6</code>.</p></li>
+<li><p>Change <code>PF_INET</code> to <code>PF_INET6</code>.</p></li>
+<li><p>Change <code>INADDR_ANY</code> assignments to <code>in6addr_any</code> assignments, which are slightly different:</p>
+<div class="sourceCode" id="cb18"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a><span class="kw">struct</span> sockaddr_in sa<span class="op">;</span></span>
+<span id="cb18-2"><a href="#cb18-2" aria-hidden="true" tabindex="-1"></a><span class="kw">struct</span> sockaddr_in6 sa6<span class="op">;</span></span>
+<span id="cb18-3"><a href="#cb18-3" aria-hidden="true" tabindex="-1"></a></span>
+<span id="cb18-4"><a href="#cb18-4" aria-hidden="true" tabindex="-1"></a>sa<span class="op">.</span>sin_addr<span class="op">.</span>s_addr <span class="op">=</span> INADDR_ANY<span class="op">;</span> <span class="co">// use my IPv4 address</span></span>
+<span id="cb18-5"><a href="#cb18-5" aria-hidden="true" tabindex="-1"></a>sa6<span class="op">.</span>sin6_addr <span class="op">=</span> in6addr_any<span class="op">;</span> <span class="co">// use my IPv6 address</span></span></code></pre></div>
+<p>Also, the value <code>IN6ADDR_ANY_INIT</code> can be used as an initializer when the <code>struct in6_addr</code> is declared, like so:</p>
+<div class="sourceCode" id="cb19"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb19-1"><a href="#cb19-1" aria-hidden="true" tabindex="-1"></a><span class="kw">struct</span> in6_addr ia6 <span class="op">=</span> IN6ADDR_ANY_INIT<span class="op">;</span></span></code></pre></div></li>
+<li><p>Instead of <code>struct sockaddr_in</code> use <code>struct sockaddr_in6</code>, being sure to add “6” to the fields as appropriate (see <a href="#structs"><code>struct</code>s</a>, above). There is no <code>sin6_zero</code> field.</p></li>
+<li><p>Instead of <code>struct in_addr</code> use <code>struct in6_addr</code>, being sure to add “6” to the fields as appropriate (see <a href="#structs"><code>struct</code>s</a>, above).</p></li>
+<li><p>Instead of <code>inet_aton()</code> or <code>inet_addr()</code>, use <code>inet_pton()</code>.</p></li>
+<li><p>Instead of <code>inet_ntoa()</code>, use <code>inet_ntop()</code>.</p></li>
+<li><p>Instead of <code>gethostbyname()</code>, use the superior <code>getaddrinfo()</code>.</p></li>
+<li><p>Instead of <code>gethostbyaddr()</code>, use the superior <code>getnameinfo()</code> (although <code>gethostbyaddr()</code> can still work with IPv6).</p></li>
+<li><p><code>INADDR_BROADCAST</code> no longer works. Use IPv6 multicast instead.</p></li>
+</ol>
+<p><em>Et voila</em>!</p>
+<h1 data-number="5" id="system-calls-or-bust"><span class="header-section-number">5</span> System Calls or Bust</h1>
+<p>This is the section where we get into the system calls (and other library calls) that allow you to access the network functionality of a Unix box, or any box that supports the sockets API for that matter (BSD, Windows, Linux, Mac, what-have-you.) When you call one of these functions, the kernel takes over and does all the work for you automagically.</p>
+<p>The place most people get stuck around here is what order to call these things in. In that, the <code>man</code> pages are no use, as you’ve probably discovered. Well, to help with that dreadful situation, I’ve tried to lay out the system calls in the following sections in <em>exactly</em> (approximately) the same order that you’ll need to call them in your programs.</p>
+<p>That, coupled with a few pieces of sample code here and there, some milk and cookies (which I fear you will have to supply yourself), and some raw guts and courage, and you’ll be beaming data around the Internet like the Son of Jon Postel!</p>
+<p><em>(Please note that for brevity, many code snippets below do not include necessary error checking. And they very commonly assume that the result from calls to <code>getaddrinfo()</code> succeed and return a valid entry in the linked list. Both of these situations are properly addressed in the stand-alone programs, though, so use those as a model.)</em></p>
+<h2 data-number="5.1" id="getaddrinfoprepare-to-launch"><span class="header-section-number">5.1</span> <code>getaddrinfo()</code>—Prepare to launch!</h2>
+<p> This is a real workhorse of a function with a lot of options, but usage is actually pretty simple. It helps set up the <code>struct</code>s you need later on.</p>
+<p>A tiny bit of history: it used to be that you would use a function called <code>gethostbyname()</code> to do DNS lookups. Then you’d load that information by hand into a <code>struct sockaddr_in</code>, and use that in your calls.</p>
+<p>This is no longer necessary, thankfully. (Nor is it desirable, if you want to write code that works for both IPv4 and IPv6!) In these modern times, you now have the function <code>getaddrinfo()</code> that does all kinds of good stuff for you, including DNS and service name lookups, and fills out the <code>struct</code>s you need, besides!</p>
+<p>Let’s take a look!</p>
+<div class="sourceCode" id="cb20"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im"><sys/types.h></span></span>
+<span id="cb20-2"><a href="#cb20-2" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im"><sys/socket.h></span></span>
+<span id="cb20-3"><a href="#cb20-3" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im"><netdb.h></span></span>
+<span id="cb20-4"><a href="#cb20-4" aria-hidden="true" tabindex="-1"></a></span>
+<span id="cb20-5"><a href="#cb20-5" aria-hidden="true" tabindex="-1"></a><span class="dt">int</span> getaddrinfo<span class="op">(</span><span class="dt">const</span> <span class="dt">char</span> <span class="op">*</span>node<span class="op">,</span> <span class="co">// e.g. "www.example.com" or IP</span></span>
+<span id="cb20-6"><a href="#cb20-6" aria-hidden="true" tabindex="-1"></a> <span class="dt">const</span> <span class="dt">char</span> <span class="op">*</span>service<span class="op">,</span> <span class="co">// e.g. "http" or port number</span></span>
+<span id="cb20-7"><a href="#cb20-7" aria-hidden="true" tabindex="-1"></a> <span class="dt">const</span> <span class="kw">struct</span> addrinfo <span class="op">*</span>hints<span class="op">,</span></span>
+<span id="cb20-8"><a href="#cb20-8" aria-hidden="true" tabindex="-1"></a> <span class="kw">struct</span> addrinfo <span class="op">**</span>res<span class="op">);</span></span></code></pre></div>
+<p>You give this function three input parameters, and it gives you a pointer to a linked-list, <code>res</code>, of results.</p>
+<p>The <code>node</code> parameter is the host name to connect to, or an IP address.</p>
+<p>Next is the parameter <code>service</code>, which can be a port number, like “80”, or the name of a particular service (found in <a href="https://www.iana.org/assignments/port-numbers">The IANA Port List</a><a href="#fn20" class="footnote-ref" id="fnref20" role="doc-noteref"><sup>20</sup></a> or the <code>/etc/services</code> file on your Unix machine) like “http” or “ftp” or “telnet” or “smtp” or whatever.</p>
+<p>Finally, the <code>hints</code> parameter points to a <code>struct addrinfo</code> that you’ve already filled out with relevant information.</p>
+<p>Here’s a sample call if you’re a server who wants to listen on your host’s IP address, port 3490. Note that this doesn’t actually do any listening or network setup; it merely sets up structures we’ll use later:</p>
+<div class="sourceCode" id="cb21"><pre class="sourceCode numberSource c numberLines"><code class="sourceCode c"><span id="cb21-1"><a href="#cb21-1"></a><span class="dt">int</span> status<span class="op">;</span></span>
+<span id="cb21-2"><a href="#cb21-2"></a><span class="kw">struct</span> addrinfo hints<span class="op">;</span></span>
+<span id="cb21-3"><a href="#cb21-3"></a><span class="kw">struct</span> addrinfo <span class="op">*</span>servinfo<span class="op">;</span> <span class="co">// will point to the results</span></span>
+<span id="cb21-4"><a href="#cb21-4"></a></span>
+<span id="cb21-5"><a href="#cb21-5"></a>memset<span class="op">(&</span>hints<span class="op">,</span> <span class="dv">0</span><span class="op">,</span> <span class="kw">sizeof</span> hints<span class="op">);</span> <span class="co">// make sure the struct is empty</span></span>
+<span id="cb21-6"><a href="#cb21-6"></a>hints<span class="op">.</span>ai_family <span class="op">=</span> AF_UNSPEC<span class="op">;</span> <span class="co">// don't care IPv4 or IPv6</span></span>
+<span id="cb21-7"><a href="#cb21-7"></a>hints<span class="op">.</span>ai_socktype <span class="op">=</span> SOCK_STREAM<span class="op">;</span> <span class="co">// TCP stream sockets</span></span>
+<span id="cb21-8"><a href="#cb21-8"></a>hints<span class="op">.</span>ai_flags <span class="op">=</span> AI_PASSIVE<span class="op">;</span> <span class="co">// fill in my IP for me</span></span>
+<span id="cb21-9"><a href="#cb21-9"></a></span>
+<span id="cb21-10"><a href="#cb21-10"></a><span class="cf">if</span> <span class="op">((</span>status <span class="op">=</span> getaddrinfo<span class="op">(</span>NULL<span class="op">,</span> <span class="st">"3490"</span><span class="op">,</span> <span class="op">&</span>hints<span class="op">,</span> <span class="op">&</span>servinfo<span class="op">))</span> <span class="op">!=</span> <span class="dv">0</span><span class="op">)</span> <span class="op">{</span></span>
+<span id="cb21-11"><a href="#cb21-11"></a> fprintf<span class="op">(</span>stderr<span class="op">,</span> <span class="st">"getaddrinfo error: </span><span class="sc">%s\n</span><span class="st">"</span><span class="op">,</span> gai_strerror<span class="op">(</span>status<span class="op">));</span></span>
+<span id="cb21-12"><a href="#cb21-12"></a> exit<span class="op">(</span><span class="dv">1</span><span class="op">);</span></span>
+<span id="cb21-13"><a href="#cb21-13"></a><span class="op">}</span></span>
+<span id="cb21-14"><a href="#cb21-14"></a></span>
+<span id="cb21-15"><a href="#cb21-15"></a><span class="co">// servinfo now points to a linked list of 1 or more struct addrinfos</span></span>
+<span id="cb21-16"><a href="#cb21-16"></a></span>
+<span id="cb21-17"><a href="#cb21-17"></a><span class="co">// ... do everything until you don't need servinfo anymore ....</span></span>
+<span id="cb21-18"><a href="#cb21-18"></a></span>
+<span id="cb21-19"><a href="#cb21-19"></a>freeaddrinfo<span class="op">(</span>servinfo<span class="op">);</span> <span class="co">// free the linked-list</span></span></code></pre></div>
+<p>Notice that I set the <code>ai_family</code> to <code>AF_UNSPEC</code>, thereby saying that I don’t care if we use IPv4 or IPv6. You can set it to <code>AF_INET</code> or <code>AF_INET6</code> if you want one or the other specifically.</p>
+<p>Also, you’ll see the <code>AI_PASSIVE</code> flag in there; this tells <code>getaddrinfo()</code> to assign the address of my local host to the socket structures. This is nice because then you don’t have to hardcode it. (Or you can put a specific address in as the first parameter to <code>getaddrinfo()</code> where I currently have <code>NULL</code>, up there.)</p>
+<p>Then we make the call. If there’s an error (<code>getaddrinfo()</code> returns non-zero), we can print it out using the function <code>gai_strerror()</code>, as you see. If everything works properly, though, <code>servinfo</code> will point to a linked list of <code>struct addrinfo</code>s, each of which contains a <code>struct sockaddr</code> of some kind that we can use later! Nifty!</p>
+<p>Finally, when we’re eventually all done with the linked list that <code>getaddrinfo()</code> so graciously allocated for us, we can (and should) free it all up with a call to <code>freeaddrinfo()</code>.</p>
+<p>Here’s a sample call if you’re a client who wants to connect to a particular server, say “www.example.net” port 3490. Again, this doesn’t actually connect, but it sets up the structures we’ll use later:</p>
+<div class="sourceCode" id="cb22"><pre class="sourceCode numberSource c numberLines"><code class="sourceCode c"><span id="cb22-1"><a href="#cb22-1"></a><span class="dt">int</span> status<span class="op">;</span></span>
+<span id="cb22-2"><a href="#cb22-2"></a><span class="kw">struct</span> addrinfo hints<span class="op">;</span></span>
+<span id="cb22-3"><a href="#cb22-3"></a><span class="kw">struct</span> addrinfo <span class="op">*</span>servinfo<span class="op">;</span> <span class="co">// will point to the results</span></span>
+<span id="cb22-4"><a href="#cb22-4"></a></span>
+<span id="cb22-5"><a href="#cb22-5"></a>memset<span class="op">(&</span>hints<span class="op">,</span> <span class="dv">0</span><span class="op">,</span> <span class="kw">sizeof</span> hints<span class="op">);</span> <span class="co">// make sure the struct is empty</span></span>
+<span id="cb22-6"><a href="#cb22-6"></a>hints<span class="op">.</span>ai_family <span class="op">=</span> AF_UNSPEC<span class="op">;</span> <span class="co">// don't care IPv4 or IPv6</span></span>
+<span id="cb22-7"><a href="#cb22-7"></a>hints<span class="op">.</span>ai_socktype <span class="op">=</span> SOCK_STREAM<span class="op">;</span> <span class="co">// TCP stream sockets</span></span>
+<span id="cb22-8"><a href="#cb22-8"></a></span>
+<span id="cb22-9"><a href="#cb22-9"></a><span class="co">// get ready to connect</span></span>
+<span id="cb22-10"><a href="#cb22-10"></a>status <span class="op">=</span> getaddrinfo<span class="op">(</span><span class="st">"www.example.net"</span><span class="op">,</span> <span class="st">"3490"</span><span class="op">,</span> <span class="op">&</span>hints<span class="op">,</span> <span class="op">&</span>servinfo<span class="op">);</span></span>
+<span id="cb22-11"><a href="#cb22-11"></a></span>
+<span id="cb22-12"><a href="#cb22-12"></a><span class="co">// servinfo now points to a linked list of 1 or more struct addrinfos</span></span>
+<span id="cb22-13"><a href="#cb22-13"></a></span>
+<span id="cb22-14"><a href="#cb22-14"></a><span class="co">// etc.</span></span></code></pre></div>
+<p>I keep saying that <code>servinfo</code> is a linked list with all kinds of address information. Let’s write a quick demo program to show off this information. <a href="https://beej.us/guide/bgnet/examples/showip.c">This short program</a><a href="#fn21" class="footnote-ref" id="fnref21" role="doc-noteref"><sup>21</sup></a> will print the IP addresses for whatever host you specify on the command line:</p>
+<div class="sourceCode" id="cb23"><pre class="sourceCode numberSource c numberLines"><code class="sourceCode c"><span id="cb23-1"><a href="#cb23-1"></a><span class="co">/*</span></span>
+<span id="cb23-2"><a href="#cb23-2"></a><span class="co">** showip.c -- show IP addresses for a host given on the command line</span></span>
+<span id="cb23-3"><a href="#cb23-3"></a><span class="co">*/</span></span>
+<span id="cb23-4"><a href="#cb23-4"></a></span>
+<span id="cb23-5"><a href="#cb23-5"></a><span class="pp">#include </span><span class="im"><stdio.h></span></span>
+<span id="cb23-6"><a href="#cb23-6"></a><span class="pp">#include </span><span class="im"><string.h></span></span>
+<span id="cb23-7"><a href="#cb23-7"></a><span class="pp">#include </span><span class="im"><sys/types.h></span></span>
+<span id="cb23-8"><a href="#cb23-8"></a><span class="pp">#include </span><span class="im"><sys/socket.h></span></span>
+<span id="cb23-9"><a href="#cb23-9"></a><span class="pp">#include </span><span class="im"><netdb.h></span></span>
+<span id="cb23-10"><a href="#cb23-10"></a><span class="pp">#include </span><span class="im"><arpa/inet.h></span></span>
+<span id="cb23-11"><a href="#cb23-11"></a><span class="pp">#include </span><span class="im"><netinet/in.h></span></span>
+<span id="cb23-12"><a href="#cb23-12"></a></span>
+<span id="cb23-13"><a href="#cb23-13"></a><span class="dt">int</span> main<span class="op">(</span><span class="dt">int</span> argc<span class="op">,</span> <span class="dt">char</span> <span class="op">*</span>argv<span class="op">[])</span></span>
+<span id="cb23-14"><a href="#cb23-14"></a><span class="op">{</span></span>
+<span id="cb23-15"><a href="#cb23-15"></a> <span class="kw">struct</span> addrinfo hints<span class="op">,</span> <span class="op">*</span>res<span class="op">,</span> <span class="op">*</span>p<span class="op">;</span></span>
+<span id="cb23-16"><a href="#cb23-16"></a> <span class="dt">int</span> status<span class="op">;</span></span>
+<span id="cb23-17"><a href="#cb23-17"></a> <span class="dt">char</span> ipstr<span class="op">[</span>INET6_ADDRSTRLEN<span class="op">];</span></span>
+<span id="cb23-18"><a href="#cb23-18"></a></span>
+<span id="cb23-19"><a href="#cb23-19"></a> <span class="cf">if</span> <span class="op">(</span>argc <span class="op">!=</span> <span class="dv">2</span><span class="op">)</span> <span class="op">{</span></span>
+<span id="cb23-20"><a href="#cb23-20"></a> fprintf<span class="op">(</span>stderr<span class="op">,</span><span class="st">"usage: showip hostname</span><span class="sc">\n</span><span class="st">"</span><span class="op">);</span></span>
+<span id="cb23-21"><a href="#cb23-21"></a> <span class="cf">return</span> <span class="dv">1</span><span class="op">;</span></span>
+<span id="cb23-22"><a href="#cb23-22"></a> <span class="op">}</span></span>
+<span id="cb23-23"><a href="#cb23-23"></a></span>
+<span id="cb23-24"><a href="#cb23-24"></a> memset<span class="op">(&</span>hints<span class="op">,</span> <span class="dv">0</span><span class="op">,</span> <span class="kw">sizeof</span> hints<span class="op">);</span></span>
+<span id="cb23-25"><a href="#cb23-25"></a> hints<span class="op">.</span>ai_family <span class="op">=</span> AF_UNSPEC<span class="op">;</span> <span class="co">// AF_INET or AF_INET6 to force version</span></span>
+<span id="cb23-26"><a href="#cb23-26"></a> hints<span class="op">.</span>ai_socktype <span class="op">=</span> SOCK_STREAM<span class="op">;</span></span>
+<span id="cb23-27"><a href="#cb23-27"></a></span>
+<span id="cb23-28"><a href="#cb23-28"></a> <span class="cf">if</span> <span class="op">((</span>status <span class="op">=</span> getaddrinfo<span class="op">(</span>argv<span class="op">[</span><span class="dv">1</span><span class="op">],</span> NULL<span class="op">,</span> <span class="op">&</span>hints<span class="op">,</span> <span class="op">&</span>res<span class="op">))</span> <span class="op">!=</span> <span class="dv">0</span><span class="op">)</span> <span class="op">{</span></span>
+<span id="cb23-29"><a href="#cb23-29"></a> fprintf<span class="op">(</span>stderr<span class="op">,</span> <span class="st">"getaddrinfo: </span><span class="sc">%s\n</span><span class="st">"</span><span class="op">,</span> gai_strerror<span class="op">(</span>status<span class="op">));</span></span>
+<span id="cb23-30"><a href="#cb23-30"></a> <span class="cf">return</span> <span class="dv">2</span><span class="op">;</span></span>
+<span id="cb23-31"><a href="#cb23-31"></a> <span class="op">}</span></span>
+<span id="cb23-32"><a href="#cb23-32"></a></span>
+<span id="cb23-33"><a href="#cb23-33"></a> printf<span class="op">(</span><span class="st">"IP addresses for </span><span class="sc">%s</span><span class="st">:</span><span class="sc">\n\n</span><span class="st">"</span><span class="op">,</span> argv<span class="op">[</span><span class="dv">1</span><span class="op">]);</span></span>
+<span id="cb23-34"><a href="#cb23-34"></a></span>
+<span id="cb23-35"><a href="#cb23-35"></a> <span class="cf">for</span><span class="op">(</span>p <span class="op">=</span> res<span class="op">;</span>p <span class="op">!=</span> NULL<span class="op">;</span> p <span class="op">=</span> p<span class="op">-></span>ai_next<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb23-36"><a href="#cb23-36"></a> <span class="dt">void</span> <span class="op">*</span>addr<span class="op">;</span></span>
+<span id="cb23-37"><a href="#cb23-37"></a> <span class="dt">char</span> <span class="op">*</span>ipver<span class="op">;</span></span>
+<span id="cb23-38"><a href="#cb23-38"></a></span>
+<span id="cb23-39"><a href="#cb23-39"></a> <span class="co">// get the pointer to the address itself,</span></span>
+<span id="cb23-40"><a href="#cb23-40"></a> <span class="co">// different fields in IPv4 and IPv6:</span></span>
+<span id="cb23-41"><a href="#cb23-41"></a> <span class="cf">if</span> <span class="op">(</span>p<span class="op">-></span>ai_family <span class="op">==</span> AF_INET<span class="op">)</span> <span class="op">{</span> <span class="co">// IPv4</span></span>
+<span id="cb23-42"><a href="#cb23-42"></a> <span class="kw">struct</span> sockaddr_in <span class="op">*</span>ipv4 <span class="op">=</span> <span class="op">(</span><span class="kw">struct</span> sockaddr_in <span class="op">*)</span>p<span class="op">-></span>ai_addr<span class="op">;</span></span>
+<span id="cb23-43"><a href="#cb23-43"></a> addr <span class="op">=</span> <span class="op">&(</span>ipv4<span class="op">-></span>sin_addr<span class="op">);</span></span>
+<span id="cb23-44"><a href="#cb23-44"></a> ipver <span class="op">=</span> <span class="st">"IPv4"</span><span class="op">;</span></span>
+<span id="cb23-45"><a href="#cb23-45"></a> <span class="op">}</span> <span class="cf">else</span> <span class="op">{</span> <span class="co">// IPv6</span></span>
+<span id="cb23-46"><a href="#cb23-46"></a> <span class="kw">struct</span> sockaddr_in6 <span class="op">*</span>ipv6 <span class="op">=</span> <span class="op">(</span><span class="kw">struct</span> sockaddr_in6 <span class="op">*)</span>p<span class="op">-></span>ai_addr<span class="op">;</span></span>
+<span id="cb23-47"><a href="#cb23-47"></a> addr <span class="op">=</span> <span class="op">&(</span>ipv6<span class="op">-></span>sin6_addr<span class="op">);</span></span>
+<span id="cb23-48"><a href="#cb23-48"></a> ipver <span class="op">=</span> <span class="st">"IPv6"</span><span class="op">;</span></span>
+<span id="cb23-49"><a href="#cb23-49"></a> <span class="op">}</span></span>
+<span id="cb23-50"><a href="#cb23-50"></a></span>
+<span id="cb23-51"><a href="#cb23-51"></a> <span class="co">// convert the IP to a string and print it:</span></span>
+<span id="cb23-52"><a href="#cb23-52"></a> inet_ntop<span class="op">(</span>p<span class="op">-></span>ai_family<span class="op">,</span> addr<span class="op">,</span> ipstr<span class="op">,</span> <span class="kw">sizeof</span> ipstr<span class="op">);</span></span>
+<span id="cb23-53"><a href="#cb23-53"></a> printf<span class="op">(</span><span class="st">" </span><span class="sc">%s</span><span class="st">: </span><span class="sc">%s\n</span><span class="st">"</span><span class="op">,</span> ipver<span class="op">,</span> ipstr<span class="op">);</span></span>
+<span id="cb23-54"><a href="#cb23-54"></a> <span class="op">}</span></span>
+<span id="cb23-55"><a href="#cb23-55"></a></span>
+<span id="cb23-56"><a href="#cb23-56"></a> freeaddrinfo<span class="op">(</span>res<span class="op">);</span> <span class="co">// free the linked list</span></span>
+<span id="cb23-57"><a href="#cb23-57"></a></span>
+<span id="cb23-58"><a href="#cb23-58"></a> <span class="cf">return</span> <span class="dv">0</span><span class="op">;</span></span>
+<span id="cb23-59"><a href="#cb23-59"></a><span class="op">}</span></span></code></pre></div>
+<p>As you see, the code calls <code>getaddrinfo()</code> on whatever you pass on the command line, that fills out the linked list pointed to by <code>res</code>, and then we can iterate over the list and print stuff out or do whatever.</p>
+<p>(There’s a little bit of ugliness there where we have to dig into the different types of <code>struct sockaddr</code>s depending on the IP version. Sorry about that! I’m not sure of a better way around it.)</p>
+<p>Sample run! Everyone loves screenshots:</p>
+<pre><code>$ showip www.example.net
+IP addresses for www.example.net:
+
+ IPv4: 192.0.2.88
+
+$ showip ipv6.example.com
+IP addresses for ipv6.example.com:
+
+ IPv4: 192.0.2.101
+ IPv6: 2001:db8:8c00:22::171</code></pre>
+<p>Now that we have that under control, we’ll use the results we get from <code>getaddrinfo()</code> to pass to other socket functions and, at long last, get our network connection established! Keep reading!</p>
+<h2 data-number="5.2" id="socket"><span class="header-section-number">5.2</span> <code>socket()</code>—Get the File Descriptor!</h2>
+<p>I guess I can put it off no longer—I have to talk about the <code>socket()</code> system call. Here’s the breakdown:</p>
+<div class="sourceCode" id="cb25"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb25-1"><a href="#cb25-1" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im"><sys/types.h></span></span>
+<span id="cb25-2"><a href="#cb25-2" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im"><sys/socket.h></span></span>
+<span id="cb25-3"><a href="#cb25-3" aria-hidden="true" tabindex="-1"></a></span>
+<span id="cb25-4"><a href="#cb25-4" aria-hidden="true" tabindex="-1"></a><span class="dt">int</span> socket<span class="op">(</span><span class="dt">int</span> domain<span class="op">,</span> <span class="dt">int</span> type<span class="op">,</span> <span class="dt">int</span> protocol<span class="op">);</span> </span></code></pre></div>
+<p>But what are these arguments? They allow you to say what kind of socket you want (IPv4 or IPv6, stream or datagram, and TCP or UDP).</p>
+<p>It used to be people would hardcode these values, and you can absolutely still do that. (<code>domain</code> is <code>PF_INET</code> or <code>PF_INET6</code>, <code>type</code> is <code>SOCK_STREAM</code> or <code>SOCK_DGRAM</code>, and <code>protocol</code> can be set to <code>0</code> to choose the proper protocol for the given <code>type</code>. Or you can call <code>getprotobyname()</code> to look up the protocol you want, “tcp” or “udp”.)</p>
codemadness.org:70 /git/webdump_tests/commit/837749abc02f28e1584e5f2cf2b274ae1c69d8e6.gph:1051: line too long