-
Notifications
You must be signed in to change notification settings - Fork 158
/
Beej's Guide to Network Programming.html
8542 lines (5701 loc) · 355 KB
/
Beej's Guide to Network Programming.html
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
<!-- saved from url=(0030)http://www.pradnik.net/netman/ -->
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Beej's Guide to Network Programming</title>
<link rel="stylesheet" href="./Beej's Guide to Network Programming_files/pnet.css" type="text/css">
<style type="text/css"></style><style>#sbbjbywfgkxrtcatayjhmiqmksptfvdfiakdcjaifr{border:solid 2px #fff !important;box-sizing:content-box !important;color:#fff !important;display:block !important;height:auto !important;margin:0 !important;opacity:0.9 !important;padding:7px 10px !important;position:fixed !important;visibility:visible !important;width:auto !important;z-index:2147483647 !important;-webkit-border-radius:5px !important;-webkit-box-shadow:0px 0px 20px #000 !important;-webkit-box-sizing:content-box !important;}.sbbjbywfgkxrtcatayjhmiqmksptfvdfiakdcjaifr-blocked{color:#777 !important;display:inline !important;text-decoration:line-through !important;}#sbbjbywfgkxrtcatayjhmiqmksptfvdfiakdcjaifr br{display:block !important;}#sbbjbywfgkxrtcatayjhmiqmksptfvdfiakdcjaifr span{background:transparent !important;}#sbbjbywfgkxrtcatayjhmiqmksptfvdfiakdcjaifr div{border:0 !important;margin:0 !important;padding:0 !important;width:auto !important;letter-spacing:normal !important;font:13px Arial,Helvetica !important;text-align:left !important;text-shadow:none !important;text-transform:none !important;word-spacing:normal !important;}#sbbjbywfgkxrtcatayjhmiqmksptfvdfiakdcjaifr a{font-weight:normal !important;background:none !important;text-decoration:underline !important;color:#fff !important;}@media print{#sbbjbywfgkxrtcatayjhmiqmksptfvdfiakdcjaifr{display:none !important;}}</style><meta name="chromesniffer" id="chromesniffer_meta" content="{"AdSense":-1}"><script type="text/javascript" src="chrome-extension://homgcnaoacgigpkkljjjekpignblkeae/detector.js"></script></head>
<body bgcolor="#ffffff">
<div id="adsense">
<script type="text/javascript"><!--
google_ad_client = "pub-8191228291510015";
google_ad_width = 160;
google_ad_height = 600;
google_ad_format = "160x600_as";
google_ad_type = "text";
//2007-05-05: bgnet
google_ad_channel = "6194029036";
google_color_border = "336699";
google_color_bg = "FFFFFF";
google_color_link = "0000FF";
google_color_text = "000000";
google_color_url = "008000";
//-->
</script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div><br>
<h1 class="guidetitle">Beej's Guide to Network Programming</h1>
<h2 class="guidesubtitle">Using Internet Sockets</h2>
<p><b class="guidetitleauthor">Brian "Beej Jorgensen" Hall</b><br>
<tt class="email"><a href="mailto:[email protected]">[email protected]</a></tt>
</p><p><span class="guideversion">Version 3.0.14</span><br>
<span class="guidedate">September 8, 2009</span><br>
</p><p><small class="guidecopyright">Copyright © 2009 Brian "Beej Jorgensen" Hall</small></p>
<hr class="mainsectbreak">
<h2 class="sect1title">Contents</h2><hr class="mainsecthr">
<dl>
<dt>1. <a href="http://www.pradnik.net/netman/#intro">Intro</a></dt>
<dd>1.1. <a href="http://www.pradnik.net/netman/#audience">Audience</a></dd>
<dd>1.2. <a href="http://www.pradnik.net/netman/#platform">Platform and Compiler</a></dd>
<dd>1.3. <a href="http://www.pradnik.net/netman/#homepage">Official Homepage and Books For Sale</a></dd>
<dd>1.4. <a href="http://www.pradnik.net/netman/#solaris">Note for Solaris/SunOS Programmers</a></dd>
<dd>1.5. <a href="http://www.pradnik.net/netman/#windows">Note for Windows Programmers</a></dd>
<dd>1.6. <a href="http://www.pradnik.net/netman/#emailpolicy">Email Policy</a></dd>
<dd>1.7. <a href="http://www.pradnik.net/netman/#mirroring">Mirroring</a></dd>
<dd>1.8. <a href="http://www.pradnik.net/netman/#xlate">Note for Translators</a></dd>
<dd>1.9. <a href="http://www.pradnik.net/netman/#copyright">Copyright and Distribution</a></dd>
<p></p><dt>2. <a href="http://www.pradnik.net/netman/#theory">What is a socket?</a></dt>
<dd>2.1. <a href="http://www.pradnik.net/netman/#twotypes">Two Types of Internet Sockets</a></dd>
<dd>2.2. <a href="http://www.pradnik.net/netman/#lowlevel">Low level Nonsense and Network Theory</a></dd>
<p></p><dt>3. <a href="http://www.pradnik.net/netman/#ipstructsdata">IP Addresses, <nobr><tt class="type">struct</tt></nobr>s, and Data Munging</a></dt>
<dd>3.1. <a href="http://www.pradnik.net/netman/#ipaddrs1">IP Addresses, versions 4 and 6</a></dd>
<dd>3.2. <a href="http://www.pradnik.net/netman/#byteorder">Byte Order</a></dd>
<dd>3.3. <a href="http://www.pradnik.net/netman/#structs"><nobr><tt class="type">struct</tt></nobr>s</a></dd>
<dd>3.4. <a href="http://www.pradnik.net/netman/#ipaddrs2">IP Addresses, Part Deux</a></dd>
<p></p><dt>4. <a href="http://www.pradnik.net/netman/#ip4to6">Jumping from IPv4 to IPv6</a></dt>
<p></p><dt>5. <a href="http://www.pradnik.net/netman/#syscalls">System Calls or Bust</a></dt>
<dd>5.1. <a href="http://www.pradnik.net/netman/#getaddrinfo"><b><tt class="func">getaddrinfo()</tt></b>—Prepare to launch!</a></dd>
<dd>5.2. <a href="http://www.pradnik.net/netman/#socket"><b><tt class="func">socket()</tt></b>—Get the File Descriptor!</a></dd>
<dd>5.3. <a href="http://www.pradnik.net/netman/#bind"><b><tt class="func">bind()</tt></b>—What port am I on?</a></dd>
<dd>5.4. <a href="http://www.pradnik.net/netman/#connect"><b><tt class="func">connect()</tt></b>—Hey, you!</a></dd>
<dd>5.5. <a href="http://www.pradnik.net/netman/#listen"><b><tt class="func">listen()</tt></b>—Will somebody please call
me?</a></dd>
<dd>5.6. <a href="http://www.pradnik.net/netman/#accept"><b><tt class="func">accept()</tt></b>—"Thank you for calling port
3490."</a></dd>
<dd>5.7. <a href="http://www.pradnik.net/netman/#sendrecv"><b><tt class="func">send()</tt></b> and <b><tt class="func">recv()</tt></b>—Talk to me,
baby!</a></dd>
<dd>5.8. <a href="http://www.pradnik.net/netman/#sendtorecv"><b><tt class="func">sendto()</tt></b> and
<b><tt class="func">recvfrom()</tt></b>—Talk to me, DGRAM-style</a></dd>
<dd>5.9. <a href="http://www.pradnik.net/netman/#closedown"><b><tt class="func">close()</tt></b> and
<b><tt class="func">shutdown()</tt></b>—Get outta my face!</a></dd>
<dd>5.10. <a href="http://www.pradnik.net/netman/#getpeername"><b><tt class="func">getpeername()</tt></b>—Who are you?</a></dd>
<dd>5.11. <a href="http://www.pradnik.net/netman/#gethostname"><b><tt class="func">gethostname()</tt></b>—Who am I?</a></dd>
<p></p><dt>6. <a href="http://www.pradnik.net/netman/#clientserver">Client-Server Background</a></dt>
<dd>6.1. <a href="http://www.pradnik.net/netman/#simpleserver">A Simple Stream Server</a></dd>
<dd>6.2. <a href="http://www.pradnik.net/netman/#simpleclient">A Simple Stream Client</a></dd>
<dd>6.3. <a href="http://www.pradnik.net/netman/#datagram">Datagram Sockets</a></dd>
<p></p><dt>7. <a href="http://www.pradnik.net/netman/#advanced">Slightly Advanced Techniques</a></dt>
<dd>7.1. <a href="http://www.pradnik.net/netman/#blocking">Blocking</a></dd>
<dd>7.2. <a href="http://www.pradnik.net/netman/#select"><b><tt class="func">select()</tt></b>—Synchronous I/O Multiplexing</a></dd>
<dd>7.3. <a href="http://www.pradnik.net/netman/#sendall">Handling Partial <b><tt class="func">send()</tt></b>s</a></dd>
<dd>7.4. <a href="http://www.pradnik.net/netman/#serialization">Serialization—How to Pack Data</a></dd>
<dd>7.5. <a href="http://www.pradnik.net/netman/#sonofdataencap">Son of Data Encapsulation</a></dd>
<dd>7.6. <a href="http://www.pradnik.net/netman/#broadcast">Broadcast Packets—Hello, World!</a></dd>
<p></p><dt>8. <a href="http://www.pradnik.net/netman/#faq">Common Questions</a></dt>
<p></p><dt>9. <a href="http://www.pradnik.net/netman/#man">Man Pages</a></dt>
<dd>9.1. <a href="http://www.pradnik.net/netman/#acceptman"><b><tt class="func">accept()</tt></b></a></dd>
<dd>9.2. <a href="http://www.pradnik.net/netman/#bindman"><b><tt class="func">bind()</tt></b></a></dd>
<dd>9.3. <a href="http://www.pradnik.net/netman/#connectman"><b><tt class="func">connect()</tt></b></a></dd>
<dd>9.4. <a href="http://www.pradnik.net/netman/#closeman"><b><tt class="func">close()</tt></b></a></dd>
<dd>9.5. <a href="http://www.pradnik.net/netman/#getaddrinfoman"><b><tt class="func">getaddrinfo()</tt></b>, <b><tt class="func">freeaddrinfo()</tt></b>,
<b><tt class="func">gai_strerror()</tt></b></a></dd>
<dd>9.6. <a href="http://www.pradnik.net/netman/#gethostnameman"><b><tt class="func">gethostname()</tt></b></a></dd>
<dd>9.7. <a href="http://www.pradnik.net/netman/#gethostbynameman"><b><tt class="func">gethostbyname()</tt></b>, <b><tt class="func">gethostbyaddr()</tt></b></a></dd>
<dd>9.8. <a href="http://www.pradnik.net/netman/#getnameinfoman"><b><tt class="func">getnameinfo()</tt></b></a></dd>
<dd>9.9. <a href="http://www.pradnik.net/netman/#getpeernameman"><b><tt class="func">getpeername()</tt></b></a></dd>
<dd>9.10. <a href="http://www.pradnik.net/netman/#errnoman"><i><tt class="var">errno</tt></i></a></dd>
<dd>9.11. <a href="http://www.pradnik.net/netman/#fcntlman"><b><tt class="func">fcntl()</tt></b></a></dd>
<dd>9.12. <a href="http://www.pradnik.net/netman/#htonsman"><b><tt class="func">htons()</tt></b>, <b><tt class="func">htonl()</tt></b>,
<b><tt class="func">ntohs()</tt></b>, <b><tt class="func">ntohl()</tt></b></a></dd>
<dd>9.13. <a href="http://www.pradnik.net/netman/#inet_ntoaman"><b><tt class="func">inet_ntoa()</tt></b>, <b><tt class="func">inet_aton()</tt></b>,
<b><tt class="func">inet_addr</tt></b></a></dd>
<dd>9.14. <a href="http://www.pradnik.net/netman/#inet_ntopman"><b><tt class="func">inet_ntop()</tt></b>, <b><tt class="func">inet_pton()</tt></b></a></dd>
<dd>9.15. <a href="http://www.pradnik.net/netman/#listenman"><b><tt class="func">listen()</tt></b></a></dd>
<dd>9.16. <a href="http://www.pradnik.net/netman/#perrorman"><b><tt class="func">perror()</tt></b>, <b><tt class="func">strerror()</tt></b></a></dd>
<dd>9.17. <a href="http://www.pradnik.net/netman/#pollman"><b><tt class="func">poll()</tt></b></a></dd>
<dd>9.18. <a href="http://www.pradnik.net/netman/#recvman"><b><tt class="func">recv()</tt></b>, <b><tt class="func">recvfrom()</tt></b></a></dd>
<dd>9.19. <a href="http://www.pradnik.net/netman/#selectman"><b><tt class="func">select()</tt></b></a></dd>
<dd>9.20. <a href="http://www.pradnik.net/netman/#setsockoptman"><b><tt class="func">setsockopt()</tt></b>, <b><tt class="func">getsockopt()</tt></b></a></dd>
<dd>9.21. <a href="http://www.pradnik.net/netman/#sendman"><b><tt class="func">send()</tt></b>, <b><tt class="func">sendto()</tt></b></a></dd>
<dd>9.22. <a href="http://www.pradnik.net/netman/#shutdownman"><b><tt class="func">shutdown()</tt></b></a></dd>
<dd>9.23. <a href="http://www.pradnik.net/netman/#socketman"><b><tt class="func">socket()</tt></b></a></dd>
<dd>9.24. <a href="http://www.pradnik.net/netman/#sockaddr_inman"><nobr><tt class="type">struct sockaddr</tt></nobr> and pals</a></dd>
<p></p><dt>10. <a href="http://www.pradnik.net/netman/#reference">More References</a></dt>
<dd>10.1. <a href="http://www.pradnik.net/netman/#books">Books</a></dd>
<dd>10.2. <a href="http://www.pradnik.net/netman/#webref">Web References</a></dd>
<dd>10.3. <a href="http://www.pradnik.net/netman/#rfcs">RFCs</a></dd>
<p><a href="http://www.pradnik.net/netman/#zindex">Index</a>
</p></dl><p>
</p><hr class="mainsectbreak"><h2 class="sect1title">1. <a name="intro">Intro</a></h2><hr class="mainsecthr">
<p>Hey! Socket programming got you down? Is this stuff just a little
too difficult to figure out from the <b class="com">man</b> pages? You want to
do cool Internet programming, but you don't have time to wade through a
gob of <nobr><tt class="type">struct</tt></nobr>s trying to figure out if you have to call
<b><tt class="func">bind()</tt></b> before you <b><tt class="func">connect()</tt></b>, 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>
<h3 class="sect2title">1.1. <a name="audience">Audience</a></h3>
<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 <i>complete and total</i> guide
to sockets programming, by any means.</p>
<p>Hopefully, though, it'll be just enough for those man pages to start
making sense... <tt>:-)</tt></p>
<h3 class="sect2title">1.2. <a name="platform">Platform and Compiler</a></h3>
<p>The code contained within this document was compiled on a Linux PC
using Gnu's <a name="indexId434909-2"></a><b class="com">gcc</b> compiler. It
should, however, build on just about any platform that uses
<b class="com">gcc</b>. Naturally, this doesn't apply if you're programming for
Windows—see the <a href="http://www.pradnik.net/netman/#windows">section on Windows
programming</a>, below.</p>
<h3 class="sect2title">1.3. <a name="homepage">Official Homepage and Books For Sale</a></h3>
<p>This official location of this document is <tt class="tt"><a href="http://beej.us/guide/bgnet/" target="_blank">http://beej.us/guide/bgnet/</a></tt>. 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
<tt class="tt"><a href="http://beej.us/guide/url/bgbuy" target="_blank">http://beej.us/guide/url/bgbuy</a></tt>. I'll appreciate the purchase
because it helps sustain my document-writing lifestyle!</p>
<h3 class="sect2title">1.4. <a name="solaris">Note for Solaris/SunOS Programmers</a></h3>
<p>When compiling for <a name="indexId434909-3"></a>Solaris or <a name="indexId434909-4"></a>SunOS, you need to specify some extra command-line switches
for linking in the proper libraries. In order to do this, simply add
"<tt class="tt"><nobr>-lnsl</nobr> <nobr>-lsocket</nobr> <nobr>-lresolv</nobr></tt>" to the end of the compile command,
like so:</p>
<pre class="screen">$ cc -o server server.c -lnsl -lsocket -lresolv</pre>
<p>If you still get errors, you could try further adding a
"<tt class="tt">-lxnet</tt>" 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
<b><tt class="func">setsockopt()</tt></b>. The prototype differs from that on my Linux
box, so instead of:</p>
<pre class="code">int yes=1;</pre>
<p>enter this:</p>
<pre class="code">char yes='1';</pre>
<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>
<h3 class="sect2title">1.5. <a name="windows">Note for Windows Programmers</a></h3>
<p>At this point in the guide, historically, I've done a bit of bagging
on <a name="indexId434909-5"></a>Windows, simply due to the fact that I don't like
it very much. But I should really be fair and tell you that Windows has
a huge install base and is obviously a perfectly fine operating
system.</p>
<p>They say absence makes the heart grow fonder, and in this case, I
believe it to be true. (Or maybe it's age.) But what I can say is that
after a decade-plus of not using Microsoft OSes for my personal work,
I'm much happier! As such, I can sit back and safely say, "Sure, feel
free to use Windows!" ...Ok yes, it does make me grit my teeth to say
that.</p>
<p>So I still encourage you to try <a name="indexId434909-6"></a><a href="http://www.linux.com/" target="_blank">Linux</a>, <a href="http://www.bsd.org/" target="_blank">BSD</a>, or
some flavor of Unix, instead.</p>
<p>But people like what they like, and you Windows folk will be pleased
to know that this information is generally applicable to you guys, with
a few minor changes, if any.</p>
<p>One cool thing you can do is install <a name="indexId434909-7"></a><a href="http://www.cygwin.com/" target="_blank">Cygwin</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.</p>
<p>But some of you might want to do things the Pure Windows Way. That's
very gutsy of you, and this is what you have to do: run out and get Unix
immediately! No, no—I'm kidding. I'm supposed to be
Windows-friendly(er) these days...</p>
<p>This is what you'll have to do (unless you install <a href="http://www.cygwin.com/" target="_blank">Cygwin</a>!): first, ignore pretty
much all of the system header files I mention in here. All you need to
include is:</p>
<pre class="code"><a name="indexId434909-8"></a>#include <winsock.h></pre>
<p>Wait! You also have to make a call to <a name="indexId434909-9"></a><b><tt class="func">WSAStartup()</tt></b> before doing anything else
with the sockets library. The code to do that looks something like
this:</p>
<pre class="code">#include <winsock.h>
{
WSADATA wsaData; // if this doesn't work
//WSAData wsaData; // then try this instead
// MAKEWORD(1,1) for Winsock 1.1, MAKEWORD(2,0) for Winsock 2.0:
if (WSAStartup(MAKEWORD(1,1), &wsaData) != 0) {
fprintf(stderr, "WSAStartup failed.\n");
exit(1);
}</pre>
<p>You also have to tell your compiler to link in the Winsock library,
usually called <i><tt class="var">wsock32.lib</tt></i> or <i><tt class="var">winsock32.lib</tt></i>,
or <i><tt class="var">ws2_32.lib</tt></i> for Winsock 2.0. Under VC++, this can be
done through the <tt class="tt">Project</tt> menu, under <tt class="tt">Settings...</tt>.
Click the <tt class="tt">Link</tt> tab, and look for the box titled "Object/library
modules". Add "wsock32.lib" (or whichever lib is your preference) to
that list.</p>
<p>Or so I hear.</p>
<p>Finally, you need to call <a name="indexId434909-10"></a><b><tt class="func">WSACleanup()</tt></b> when you're all through
with the sockets library. See your online help for details.</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
<b><tt class="func">close()</tt></b> to close a socket—you need to use <a name="indexId434909-11"></a><b><tt class="func">closesocket()</tt></b>, instead. Also, <a name="indexId434909-12"></a><b><tt class="func">select()</tt></b> only works with socket
descriptors, not file descriptors (like <tt class="const">0</tt> for
<tt class="tt">stdin</tt>).</p>
<p>There is also a socket class that you can use, <a name="indexId434909-13"></a><nobr><tt class="type">CSocket</tt></nobr>. Check your compilers help pages
for more information.</p>
<p>To get more information about Winsock, read the <a name="indexId434909-14"></a><a href="http://tangentsoft.net/wskfaq/" target="_blank">Winsock FAQ</a> and go from
there.</p>
<p>Finally, I hear that Windows has no <a name="indexId434909-15"></a><b><tt class="func">fork()</tt></b> 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 <a name="indexId434909-16"></a><b><tt class="func">CreateProcess()</tt></b> instead.
<b><tt class="func">fork()</tt></b> takes no arguments, and <b><tt class="func">CreateProcess()</tt></b>
takes about 48 billion arguments. If you're not up to that, the <a name="indexId434909-17"></a><b><tt class="func">CreateThread()</tt></b> 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>
<h3 class="sect2title">1.6. <a name="emailpolicy">Email Policy</a></h3>
<p>I'm generally available to help out with <a name="indexId434909-18"></a>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" target="_blank">How To Ask
Questions The Smart Way</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 <i>fully</i> 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! <tt>:-)</tt>
Thank you!</p>
<h3 class="sect2title">1.7. <a name="mirroring">Mirroring</a></h3>
<p><a name="indexId434909-19"></a>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
<tt class="email"><a href="mailto:[email protected]">[email protected]</a></tt>.</p>
<h3 class="sect2title">1.8. <a name="xlate">Note for Translators</a></h3>
<p><a name="indexId434909-20"></a>If you want to translate the guide into
another language, write me at <tt class="email"><a href="mailto:[email protected]">[email protected]</a></tt> 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>Please note the license restrictions in the Copyright and
Distribution 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>
<h3 class="sect2title">1.9. <a name="copyright">Copyright and Distribution</a></h3>
<p>Beej's Guide to Network Programming is Copyright © 2009
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 <tt class="tt"><a href="http://creativecommons.org/licenses/by-nc-nd/3.0/" target="_blank">http://creativecommons.org/licenses/by-nc-nd/3.0/</a></tt> 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>Contact <tt class="email"><a href="mailto:[email protected]">[email protected]</a></tt> for more information.</p>
<hr class="mainsectbreak"><h2 class="sect1title">2. <a name="theory">What is a socket?</a></h2><hr class="mainsecthr">
<p>You hear talk of "<a name="indexId434909-21"></a>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 <a name="indexId434909-22"></a>file descriptors.</p>
<p>What?</p>
<p>Ok—you may have heard some Unix hacker state, "Jeez,
<i>everything</i> 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 <i>is</i> 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 <a name="indexId434909-23"></a><b><tt class="func">socket()</tt></b> system routine. It returns the
<a name="indexId434909-24"></a>socket descriptor, and you communicate
through it using the specialized <a name="indexId434909-25"></a><b><tt class="func">send()</tt></b>
and <a name="indexId434909-26"></a><b><tt class="func">recv()</tt></b> (<b class="com"><a href="http://www.pradnik.net/netman/#sendman">man
send</a></b>, <b class="com"><a href="http://www.pradnik.net/netman/#recvman">man recv</a></b>)
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 <a name="indexId434909-27"></a><b><tt class="func">read()</tt></b> and <a name="indexId434909-28"></a><b><tt class="func">write()</tt></b> calls to communicate through the
socket?" The short answer is, "You can!" The longer answer is, "You
can, but <a name="indexId434909-29"></a><b><tt class="func">send()</tt></b> and <a name="indexId434909-30"></a><b><tt class="func">recv()</tt></b> offer much greater control over your
data transmission."</p>
<p>What next? How about this: there are all kinds of sockets. There
are <a name="indexId434909-31"></a>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>
<h3 class="sect2title">2.1. <a name="twotypes">Two Types of Internet Sockets</a></h3>
<p>What's this? <a name="indexId434909-32"></a>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 "<a name="indexId434909-33"></a><a name="indexId434909-34"></a>Raw Sockets" are also very powerful and
you should look them up.</p>
<p>All right, already. What are the two types? One is "<a name="indexId434909-35"></a>Stream Sockets"; the other is
"<a name="indexId434909-36"></a>Datagram Sockets", which
may hereafter be referred to as "<tt class="const">SOCK_STREAM</tt>" and
"<tt class="const">SOCK_DGRAM</tt>", respectively. Datagram sockets are
sometimes called "connectionless sockets". (Though they can be <a name="indexId434909-37"></a><b><tt class="func">connect()</tt></b>'d if you really want. See
<b><tt class="func"><a href="http://www.pradnik.net/netman/#connect">connect()</a></tt></b>, 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 <i>la la la la</i>
if anyone tries to claim otherwise.</p>
<p>What uses <a name="indexId434909-38"></a>stream sockets? Well, you may
have heard of the <a name="indexId434909-39"></a><b class="com">telnet</b> application, yes?
It uses stream sockets. All the characters you type need to arrive in
the same order you type them, right? Also, web browsers use the <a name="indexId434909-40"></a>HTTP protocol which uses stream sockets to get
pages. Indeed, if you telnet to a web site on port 80, and type
"<tt class="tt">GET / HTTP/1.0</tt>" and hit RETURN twice, it'll dump the HTML back
at you!</p>
<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 <a name="indexId434909-41"></a>"TCP" (see <a href="http://tools.ietf.org/html/rfc793" target="_blank">RFC 793</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 <a name="indexId434909-42"></a> "IP" stands for "Internet Protocol" (see <a href="http://tools.ietf.org/html/rfc791" target="_blank">RFC 791</a>.) IP deals primarily with
Internet routing and is not generally responsible for data
integrity.</p>
<p>Cool. <a name="indexId434909-43"></a>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 <a name="indexId434909-44"></a>"UDP" (see
<a href="http://tools.ietf.org/html/rfc768" target="_blank">RFC 768</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: <b class="com">tftp</b> (trivial file transfer protocol, a little
brother to FTP), <b class="com">dhcpcd</b> (a DHCP client), multiplayer games,
streaming audio, video conferencing, etc.</p>
<p>"Wait a minute! <b class="com">tftp</b> and <b class="com">dhcpcd</b> 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, <b class="com">tftp</b> 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 <tt class="const">SOCK_DGRAM</tt>
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: <i>accursed lag</i>. 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>
<h3 class="sect2title">2.2. <a name="lowlevel">Low level Nonsense and Network Theory</a></h3>
<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 <a name="indexId434909-45"></a><tt class="const">SOCK_DGRAM</tt> packets are built.
Practically, you can probably skip this section. It's good background,
however.</p>
<a name="figure1"><center>
<div><img src="./Beej's Guide to Network Programming_files/dataencap-120-4.736.png" alt="[Encapsulated Protocols Diagram]"></div>
<p><b>Data Encapsulation.</b></p>
</center>
</a><p><a name="figure1">Hey, kids, it's time to learn about </a><a name="indexId434909-46"></a><i><a href="http://www.pradnik.net/netman/#figure1">Data
Encapsulation</a></i>! 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 <tt>;-)</tt>. Basically, it says this: a packet
is born, the packet is wrapped ("encapsulated") in a <a name="indexId434909-47"></a>header (and rarely a <a name="indexId434909-48"></a>footer) by the
first protocol (say, the <a name="indexId434909-49"></a>TFTP protocol), then the whole
thing (TFTP header included) is encapsulated again by the next protocol
(say, <a name="indexId434909-50"></a>UDP), then again by the next (<a name="indexId434909-51"></a>IP),
then again by the final protocol on the hardware (physical) layer (say,
<a name="indexId434909-52"></a>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 <a name="indexId434909-53"></a><i>Layered Network Model</i> (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 (<i>telnet, ftp, etc.</i>)</li>
<li>Host-to-Host Transport Layer (<i>TCP, UDP</i>)</li>
<li>Internet Layer (<i>IP and routing</i>)</li>
<li>Network Access Layer (<i>Ethernet, wi-fi, or whatever</i>)</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
"<b class="com">cat</b>"! Just kidding. All you have to do for stream sockets
is <a name="indexId434909-54"></a><b><tt class="func">send()</tt></b> the data out. All you have to
do for datagram sockets is encapsulate the packet in the method of your
choosing and <a name="indexId434909-55"></a><b><tt class="func">sendto()</tt></b> 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, <a name="indexId434909-56"></a>blah blah blah. Check out the <a href="http://tools.ietf.org/html/rfc791" target="_blank">IP RFC</a> if you really really care. If
you never learn about it, well, you'll live.</p>
<hr class="mainsectbreak"><h2 class="sect1title">3. <a name="ipstructsdata">IP Addresses, <nobr><b><tt class="titletype">struct</tt></b></nobr>s, and Data Munging</a></h2><hr class="mainsecthr">
<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 <a name="indexId434909-57"></a>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>
<h3 class="sect2title">3.1. <a name="ipaddrs1">IP Addresses, versions 4 and 6</a></h3>
<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 <a name="indexId434909-58"></a>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: <tt class="tt">192.0.2.111</tt>.</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 name="indexId434909-59"></a><a href="http://en.wikipedia.org/wiki/Vinton_Cerf" target="_blank">Vint Cerf</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, <a name="indexId434909-60"></a>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="http://en.wikipedia.org/wiki/ELIZA" target="_blank">ELIZA</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 <i>lot</i> 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 <i>79 MILLION BILLION TRILLION times as
many possible addresses!</i> 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><small>32</small></sup>), while 128 bits represents about 340
trillion trillion trillion numbers (for real, 2<sup><small>128</small></sup>).
That's like a million IPv4 Internets for <i>every single star in the
Universe</i>.</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: <tt class="tt">2001:0db8:c9d2:aee5:73e3:934a:a5ae:9551</tt>.</p>
<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 class="screen">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
</pre>
<p>The address <tt class="tt">::1</tt> is the <i>loopback address</i>. It
always means "this machine I'm running on now". In IPv4, the loopback
address is 127.0.0.1.</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 192.0.2.33 as an IPv6 address, you use the following notation:
"<tt class="tt">::ffff:192.0.2.33</tt>".</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>
<h4 class="sect3title">3.1.1. <a name="netslash">Subnets</a></h4>
<p>For organizational reasons, it's sometimes convenient to declare that
"this first part of this IP address up through this bit is the
<i>network portion</i> of the IP address, and the remainder is the
<i>host portion</i>.</p>
<p>For instance, with IPv4, you might have <tt class="tt">192.0.2.12</tt>, 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 <tt class="tt">12</tt> on
network <tt class="tt">192.0.2.0</tt> (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 (24 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 <i>netmask</i>, which you bitwise-AND with the IP address
to get the network number out of it. The netmask usually looks
something like <tt class="tt">255.255.255.0</tt>. (E.g. with that netmask, if your
IP is <tt class="tt">192.0.2.12</tt>, then your network is <tt class="tt">192.0.2.12</tt> AND
<tt class="tt">255.255.255.0</tt> which gives <tt class="tt">192.0.2.0</tt>.)</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 <tt class="tt">255.255.255.252</tt>, which
is 30 bits of network, and 2 bits of host allowing for four hosts on the
network. (Note that the netmask is <i>ALWAYS</i> 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
<tt class="tt">255.192.0.0</tt> 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: <tt class="tt">192.0.2.12/30</tt>.</p>
<p>Or, for IPv6, something like this: <tt class="tt">2001:db8::/32</tt> or
<tt class="tt">2001:db8:5413:4028::9db9/64</tt>.</p>
<h4 class="sect3title">3.1.2. <a name="portnums">Port Numbers</a></h4>
<p>If you'll kindly remember, I presented you earlier with the <a href="http://www.pradnik.net/netman/#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 <i>port
number</i>. 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="http://www.iana.org/assignments/port-numbers" target="_blank">the Big
IANA Port List</a> or, if you're on a Unix box, in your
<i><tt class="var">/etc/services</tt></i> file. HTTP (the web) is port 80, telnet is
port 23, SMTP is port 25, the game <a href="http://en.wikipedia.org/wiki/Doom_(video_game)" target="_blank">DOOM</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>
<h3 class="sect2title">3.2. <a name="byteorder">Byte Order</a></h3>
<p><a name="indexId434909-61"></a>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. <tt>:-)</tt></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
<tt class="tt">b34f</tt>, you'll store it in two sequential bytes <tt class="tt">b3</tt>
followed by <tt class="tt">4f</tt>. Makes sense, and, as <a href="http://en.wikipedia.org/wiki/Wilford_Brimley" target="_blank">Wilford Brimley</a> would tell you, it's the Right
Thing To Do. This number, stored with the big end first, is called
<i>Big-Endian</i>.</p>
<p>Unfortunately, a few computers scattered here and there throughout
the world, namely anything with an Intel or Intel-compatible processor,
store the bytes reversed, so <tt class="tt">b34f</tt> would be stored in memory as
the sequential bytes <tt class="tt">4f</tt> followed by <tt class="tt">b3</tt>. This storage
method is called <i>Little-Endian</i>.</p>
<p>But wait, I'm not done with terminology yet! The more-sane
<i>Big-Endian</i> is also called <i>Network Byte Order</i>
because that's the order us network types like.</p>
<p>Your computer stores numbers in <i>Host Byte Order</i>. 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:
<nobr><tt class="type">short</tt></nobr> (two bytes) and <nobr><tt class="type">long</tt></nobr> (four bytes).
These functions work for the <nobr><tt class="type">unsigned</tt></nobr> variations as well.
Say you want to convert a <nobr><tt class="type">short</tt></nobr> 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
<b><tt class="func">htons()</tt></b> (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
<b><tt class="func">stolh()</tt></b> ("Short to Long Host") function—not at this
party, anyway. But there are:</p>
<p>
</p><center><table cellpadding="10" cellspacing="0" border="0" class="joetable">