-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathguide.html
More file actions
5114 lines (5074 loc) · 704 KB
/
guide.html
File metadata and controls
5114 lines (5074 loc) · 704 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!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%;
}
svg {
height: auto;
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;}
/* The extra [class] is a hack that increases specificity enough to
override a similar rule in reveal.js */
ul.task-list[class]{list-style: none;}
ul.task-list li input[type="checkbox"] {
font-size: inherit;
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 { 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 { display: inline-block; 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>
<!-- 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;
}
pre.sourceCode {
border: 1px solid #ccc;
padding: 0.5em;
border-radius: 0.2em;
}
/* Keep code tags from wrapping in tables */
tbody code {
white-space: nowrap;
}
/* Prevent hyphenation and hyphen breaks in code*/
code {
word-break: keep-all;
}
td {
vertical-align: top;
}
body {
font-size: 12pt;
max-width: 43em;
font-family: sans-serif;
}
html {
background: #f9f9f9;
}
figure > embed {
max-width: 100%;
}
figure {
text-align: center;
margin-top: 2em;
margin-bottom: 2em;
}
figcaption {
font-size: 0.9em;
font-style: italic;
margin-top: 0.6em;
}
body {
counter-reset: figure-counter-major;
counter-reset: figure-counter-minor;
}
figure {
counter-increment: figure-counter-minor;
}
figcaption::before {
content: "Figure " counter(figure-counter-major) "." counter(figure-counter-minor) ": ";
}
blockquote {
border-left: 2px solid #bbb;
color: #444;
}
/*
In multipage, we need to reset the figure counter to the chapter
number. Luckily, this is in the <h1 data-number> attribute. Unluckily,
there is no way to get this in a general way.
This doesn't work:
h1[data-number] {
counter-set: figure-counter-major attr(data-number);
}
Nor this:
h1[data-number] {
--figure-counter-major-value: attr(data-number);
counter-set: figure-counter-major var(--figure-counter-major-value);
}
So, dumbly, we have a bunch of rules for all these sections, up to the
maximum possible section.
Here's a program to generate them:
for (let i = 1; i < 100; i++)
console.log(`h1[data-number="${i}"]{counter-set:figure-counter-major ${i};counter-reset:figure-counter-minor;}`);
Note to self: never write a book with more than 99 frickin' chapters.
*/
h1[data-number="1"]{counter-set:figure-counter-major 1;counter-reset:figure-counter-minor;}
h1[data-number="2"]{counter-set:figure-counter-major 2;counter-reset:figure-counter-minor;}
h1[data-number="3"]{counter-set:figure-counter-major 3;counter-reset:figure-counter-minor;}
h1[data-number="4"]{counter-set:figure-counter-major 4;counter-reset:figure-counter-minor;}
h1[data-number="5"]{counter-set:figure-counter-major 5;counter-reset:figure-counter-minor;}
h1[data-number="6"]{counter-set:figure-counter-major 6;counter-reset:figure-counter-minor;}
h1[data-number="7"]{counter-set:figure-counter-major 7;counter-reset:figure-counter-minor;}
h1[data-number="8"]{counter-set:figure-counter-major 8;counter-reset:figure-counter-minor;}
h1[data-number="9"]{counter-set:figure-counter-major 9;counter-reset:figure-counter-minor;}
h1[data-number="10"]{counter-set:figure-counter-major 10;counter-reset:figure-counter-minor;}
h1[data-number="11"]{counter-set:figure-counter-major 11;counter-reset:figure-counter-minor;}
h1[data-number="12"]{counter-set:figure-counter-major 12;counter-reset:figure-counter-minor;}
h1[data-number="13"]{counter-set:figure-counter-major 13;counter-reset:figure-counter-minor;}
h1[data-number="14"]{counter-set:figure-counter-major 14;counter-reset:figure-counter-minor;}
h1[data-number="15"]{counter-set:figure-counter-major 15;counter-reset:figure-counter-minor;}
h1[data-number="16"]{counter-set:figure-counter-major 16;counter-reset:figure-counter-minor;}
h1[data-number="17"]{counter-set:figure-counter-major 17;counter-reset:figure-counter-minor;}
h1[data-number="18"]{counter-set:figure-counter-major 18;counter-reset:figure-counter-minor;}
h1[data-number="19"]{counter-set:figure-counter-major 19;counter-reset:figure-counter-minor;}
h1[data-number="20"]{counter-set:figure-counter-major 20;counter-reset:figure-counter-minor;}
h1[data-number="21"]{counter-set:figure-counter-major 21;counter-reset:figure-counter-minor;}
h1[data-number="22"]{counter-set:figure-counter-major 22;counter-reset:figure-counter-minor;}
h1[data-number="23"]{counter-set:figure-counter-major 23;counter-reset:figure-counter-minor;}
h1[data-number="24"]{counter-set:figure-counter-major 24;counter-reset:figure-counter-minor;}
h1[data-number="25"]{counter-set:figure-counter-major 25;counter-reset:figure-counter-minor;}
h1[data-number="26"]{counter-set:figure-counter-major 26;counter-reset:figure-counter-minor;}
h1[data-number="27"]{counter-set:figure-counter-major 27;counter-reset:figure-counter-minor;}
h1[data-number="28"]{counter-set:figure-counter-major 28;counter-reset:figure-counter-minor;}
h1[data-number="29"]{counter-set:figure-counter-major 29;counter-reset:figure-counter-minor;}
h1[data-number="30"]{counter-set:figure-counter-major 30;counter-reset:figure-counter-minor;}
h1[data-number="31"]{counter-set:figure-counter-major 31;counter-reset:figure-counter-minor;}
h1[data-number="32"]{counter-set:figure-counter-major 32;counter-reset:figure-counter-minor;}
h1[data-number="33"]{counter-set:figure-counter-major 33;counter-reset:figure-counter-minor;}
h1[data-number="34"]{counter-set:figure-counter-major 34;counter-reset:figure-counter-minor;}
h1[data-number="35"]{counter-set:figure-counter-major 35;counter-reset:figure-counter-minor;}
h1[data-number="36"]{counter-set:figure-counter-major 36;counter-reset:figure-counter-minor;}
h1[data-number="37"]{counter-set:figure-counter-major 37;counter-reset:figure-counter-minor;}
h1[data-number="38"]{counter-set:figure-counter-major 38;counter-reset:figure-counter-minor;}
h1[data-number="39"]{counter-set:figure-counter-major 39;counter-reset:figure-counter-minor;}
h1[data-number="40"]{counter-set:figure-counter-major 40;counter-reset:figure-counter-minor;}
h1[data-number="41"]{counter-set:figure-counter-major 41;counter-reset:figure-counter-minor;}
h1[data-number="42"]{counter-set:figure-counter-major 42;counter-reset:figure-counter-minor;}
h1[data-number="43"]{counter-set:figure-counter-major 43;counter-reset:figure-counter-minor;}
h1[data-number="44"]{counter-set:figure-counter-major 44;counter-reset:figure-counter-minor;}
h1[data-number="45"]{counter-set:figure-counter-major 45;counter-reset:figure-counter-minor;}
h1[data-number="46"]{counter-set:figure-counter-major 46;counter-reset:figure-counter-minor;}
h1[data-number="47"]{counter-set:figure-counter-major 47;counter-reset:figure-counter-minor;}
h1[data-number="48"]{counter-set:figure-counter-major 48;counter-reset:figure-counter-minor;}
h1[data-number="49"]{counter-set:figure-counter-major 49;counter-reset:figure-counter-minor;}
h1[data-number="50"]{counter-set:figure-counter-major 50;counter-reset:figure-counter-minor;}
h1[data-number="51"]{counter-set:figure-counter-major 51;counter-reset:figure-counter-minor;}
h1[data-number="52"]{counter-set:figure-counter-major 52;counter-reset:figure-counter-minor;}
h1[data-number="53"]{counter-set:figure-counter-major 53;counter-reset:figure-counter-minor;}
h1[data-number="54"]{counter-set:figure-counter-major 54;counter-reset:figure-counter-minor;}
h1[data-number="55"]{counter-set:figure-counter-major 55;counter-reset:figure-counter-minor;}
h1[data-number="56"]{counter-set:figure-counter-major 56;counter-reset:figure-counter-minor;}
h1[data-number="57"]{counter-set:figure-counter-major 57;counter-reset:figure-counter-minor;}
h1[data-number="58"]{counter-set:figure-counter-major 58;counter-reset:figure-counter-minor;}
h1[data-number="59"]{counter-set:figure-counter-major 59;counter-reset:figure-counter-minor;}
h1[data-number="60"]{counter-set:figure-counter-major 60;counter-reset:figure-counter-minor;}
h1[data-number="61"]{counter-set:figure-counter-major 61;counter-reset:figure-counter-minor;}
h1[data-number="62"]{counter-set:figure-counter-major 62;counter-reset:figure-counter-minor;}
h1[data-number="63"]{counter-set:figure-counter-major 63;counter-reset:figure-counter-minor;}
h1[data-number="64"]{counter-set:figure-counter-major 64;counter-reset:figure-counter-minor;}
h1[data-number="65"]{counter-set:figure-counter-major 65;counter-reset:figure-counter-minor;}
h1[data-number="66"]{counter-set:figure-counter-major 66;counter-reset:figure-counter-minor;}
h1[data-number="67"]{counter-set:figure-counter-major 67;counter-reset:figure-counter-minor;}
h1[data-number="68"]{counter-set:figure-counter-major 68;counter-reset:figure-counter-minor;}
h1[data-number="69"]{counter-set:figure-counter-major 69;counter-reset:figure-counter-minor;}
h1[data-number="70"]{counter-set:figure-counter-major 70;counter-reset:figure-counter-minor;}
h1[data-number="71"]{counter-set:figure-counter-major 71;counter-reset:figure-counter-minor;}
h1[data-number="72"]{counter-set:figure-counter-major 72;counter-reset:figure-counter-minor;}
h1[data-number="73"]{counter-set:figure-counter-major 73;counter-reset:figure-counter-minor;}
h1[data-number="74"]{counter-set:figure-counter-major 74;counter-reset:figure-counter-minor;}
h1[data-number="75"]{counter-set:figure-counter-major 75;counter-reset:figure-counter-minor;}
h1[data-number="76"]{counter-set:figure-counter-major 76;counter-reset:figure-counter-minor;}
h1[data-number="77"]{counter-set:figure-counter-major 77;counter-reset:figure-counter-minor;}
h1[data-number="78"]{counter-set:figure-counter-major 78;counter-reset:figure-counter-minor;}
h1[data-number="79"]{counter-set:figure-counter-major 79;counter-reset:figure-counter-minor;}
h1[data-number="80"]{counter-set:figure-counter-major 80;counter-reset:figure-counter-minor;}
h1[data-number="81"]{counter-set:figure-counter-major 81;counter-reset:figure-counter-minor;}
h1[data-number="82"]{counter-set:figure-counter-major 82;counter-reset:figure-counter-minor;}
h1[data-number="83"]{counter-set:figure-counter-major 83;counter-reset:figure-counter-minor;}
h1[data-number="84"]{counter-set:figure-counter-major 84;counter-reset:figure-counter-minor;}
h1[data-number="85"]{counter-set:figure-counter-major 85;counter-reset:figure-counter-minor;}
h1[data-number="86"]{counter-set:figure-counter-major 86;counter-reset:figure-counter-minor;}
h1[data-number="87"]{counter-set:figure-counter-major 87;counter-reset:figure-counter-minor;}
h1[data-number="88"]{counter-set:figure-counter-major 88;counter-reset:figure-counter-minor;}
h1[data-number="89"]{counter-set:figure-counter-major 89;counter-reset:figure-counter-minor;}
h1[data-number="90"]{counter-set:figure-counter-major 90;counter-reset:figure-counter-minor;}
h1[data-number="91"]{counter-set:figure-counter-major 91;counter-reset:figure-counter-minor;}
h1[data-number="92"]{counter-set:figure-counter-major 92;counter-reset:figure-counter-minor;}
h1[data-number="93"]{counter-set:figure-counter-major 93;counter-reset:figure-counter-minor;}
h1[data-number="94"]{counter-set:figure-counter-major 94;counter-reset:figure-counter-minor;}
h1[data-number="95"]{counter-set:figure-counter-major 95;counter-reset:figure-counter-minor;}
h1[data-number="96"]{counter-set:figure-counter-major 96;counter-reset:figure-counter-minor;}
h1[data-number="97"]{counter-set:figure-counter-major 97;counter-reset:figure-counter-minor;}
h1[data-number="98"]{counter-set:figure-counter-major 98;counter-reset:figure-counter-minor;}
h1[data-number="99"]{counter-set:figure-counter-major 99;counter-reset:figure-counter-minor;}
</style>
</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.2.2, Copyright © January 14, 2025</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/illumos 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>
<!-- BG_NEW_CHAPTER -->
<!--
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}
-->
<!-- BG_NEW_CHAPTER -->
<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/illumos Programmers</h2>
<p>When compiling for a Solaris variant 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 then Windows and Microsoft (as a company) got a lot better. Windows 9 and 10 coupled with WSL (below) actually were decent operating systems. Not really a lot to complain about.</p>
<p>Well, a little—for example, I’m writing this (in 2025) on a 2015 laptop that used to run Windows 10. Eventually it got too slow and I installed Linux on it. And have been using it ever since.</p>
<p>And now the news is out that Windows 11 will require beefier hardware than Windows 10. I’m not a fan of that. The OS should be as unobtrusive as possible and not require you to spend more money. The extra CPU power should be for apps, not the OS!</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>, <a href="https://www.illumos.org/">illumos</a><a href="#fn3" class="footnote-ref" id="fnref3" role="doc-noteref"><sup>3</sup></a> or some other flavor of Unix, instead.</p>
<p>How’d that soapbox get there?</p>
<p>But people like what they like, and you Windows folk will be pleased to know that this information is generally applicable to Windows, with a few minor changes.</p>
<p>Oh, hey, the soapbox is back!</p>
<p>One 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="#fn4" class="footnote-ref" id="fnref4" role="doc-noteref"><sup>4</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>Another thing you can do is install <a href="https://cygwin.com/">Cygwin</a><a href="#fn5" class="footnote-ref" id="fnref5" role="doc-noteref"><sup>5</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>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>Okay, okay. I’ll get on with it.</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">"Version 2.2 of Winsock 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="#fn6" class="footnote-ref" id="fnref6" role="doc-noteref"><sup>6</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="#fn7" class="footnote-ref" id="fnref7" role="doc-noteref"><sup>7</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>
<!-- BG_NEW_CHAPTER -->
<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/source/examples/telnot.c"><code>telnot</code></a><a href="#fn8" class="footnote-ref" id="fnref8" role="doc-noteref"><sup>8</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="#fn9" class="footnote-ref" id="fnref9" role="doc-noteref"><sup>9</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="#fn10" class="footnote-ref" id="fnref10" role="doc-noteref"><sup>10</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="#fn11" class="footnote-ref" id="fnref11" role="doc-noteref"><sup>11</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="#fn12" class="footnote-ref" id="fnref12" role="doc-noteref"><sup>12</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="#fn13" class="footnote-ref" id="fnref13" role="doc-noteref"><sup>13</sup></a> if you really really care. If you never learn about it, well, you’ll live.</p>
<!-- BG_NEW_CHAPTER -->
<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="#fn14" class="footnote-ref" id="fnref14" role="doc-noteref"><sup>14</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="#fn15" class="footnote-ref" id="fnref15" role="doc-noteref"><sup>15</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="#fn16" class="footnote-ref" id="fnref16" role="doc-noteref"><sup>16</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="#fn17" class="footnote-ref" id="fnref17" role="doc-noteref"><sup>17</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="#fn18" class="footnote-ref" id="fnref18" role="doc-noteref"><sup>18</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>