From: Snapshot-Content-Location: http://beej.us/guide/bgnet/html/#what-is-a-socket Subject: Beej's Guide to Network Programming Date: Mon, 28 Mar 2022 11:40:54 -0000 MIME-Version: 1.0 Content-Type: multipart/related; type="text/html"; boundary="----MultipartBoundary--Ed8mr4hq2PkKv7UclxPAzEF7J8M75erKKbPS2p3d0i----" ------MultipartBoundary--Ed8mr4hq2PkKv7UclxPAzEF7J8M75erKKbPS2p3d0i---- Content-Type: text/html Content-ID: Content-Transfer-Encoding: quoted-printable Content-Location: http://beej.us/guide/bgnet/html/#what-is-a-socket =20 Beej's Guide to Network Programming =20 =20 =20

Beej's Guide to Network Programming

Using Internet Sockets

Brian =E2=80=9CBeej Jorgensen=E2=80=9D Hall

v3.1.5, Copyright =C2=A9 November 20, 2020

1<= /span> Intro

Hey! Socket programming got you down? Is this stuff just a little too di= fficult to figure out from the man pages? You want to do cool = Internet programming, but you don=E2=80=99t have time to wade through a gob= of structs trying to figure out if you have to call bin= d() before you connect(), etc., etc.

Well, guess what! I=E2=80=99ve already done this nasty business, and I= =E2=80=99m dying to share the information with everyone! You=E2=80=99ve com= e to the right place. This document should give the average competent C pro= grammer the edge s/he needs to get a grip on this networking noise.

And check it out: I=E2=80=99ve finally caught up with the future (just i= n the nick of time, too!) and have updated the Guide for IPv6! Enjoy!

1.1 Audience

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 o= ut with socket programming and are looking for a foothold. It is certainly = not the complete and total guide to sockets programming, by any me= ans.

Hopefully, though, it=E2=80=99ll be just enough for those man pages to s= tart making sense=E2=80=A6 :-)

1.2 Platform and Compiler

The code contained within this document was compiled on a Linux PC using= Gnu=E2=80=99s gcc compiler. It should, however, build on jus= t about any platform that uses gcc. Naturally, this doesn=E2= =80=99t apply if you=E2=80=99re programming for Windows=E2=80=94see the section on Windows progra= mming, below.

1.3 Official Homepage and Books For S= ale

This official location of this document is:

There you will also find example code and translations of the guide into= various languages.

To buy nicely bound print copies (some call them =E2=80=9Cbooks=E2=80=9D= ), visit:

I=E2=80=99ll appreciate the purchase because it helps sustain my documen= t-writing lifestyle!

1.4 Note for Solaris/SunOS Programmers

When compiling for Solaris or SunOS, you need to specify some extra co= mmand-line switches for linking in the proper libraries. In order to do thi= s, simply add =E2=80=9C-lnsl -lsocket -lresolv=E2=80=9D to the= end of the compile command, like so:

    $ cc -o server server.c -lnsl -lsocket -lresolv

If you still get errors, you could try further adding a -lxnet to the end of that command line. I don=E2=80=99t know what that does, e= xactly, but some people seem to need it.

Another place that you might find problems is in the call to setso= ckopt(). The prototype differs from that on my Linux box, so instead= of:

    int yes=3D1;

enter this:

    char yes=3D'1';

As I don=E2=80=99t have a Sun box, I haven=E2=80=99t tested any of the a= bove information=E2=80=94it=E2=80=99s just what people have told me through= email.

1.5 Note for Windows Programmers

At this point in the guide, historically, I=E2=80=99ve done a bit of bag= ging on Windows, simply due to the fact that I don=E2=80=99t like it very = much. But I should really be fair and tell you that Windows has a huge inst= all base and is obviously a perfectly fine operating system.

They say absence makes the heart grow fonder, and in this case, I believ= e it to be true. (Or maybe it=E2=80=99s age.) But what I can say is that af= ter a decade-plus of not using Microsoft OSes for my personal work, I=E2=80= =99m much happier! As such, I can sit back and safely say, =E2=80=9CSure, f= eel free to use Windows!=E2=80=9D =E2=80=A6Ok yes, it does make me grit my = teeth to say that.

So I still encourage you to try Linu= x1, BSD2, or some f= lavor of Unix, instead.

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.

One cool thing you can do is install Cy= gwin3, which is a collec= tion of Unix tools for Windows. I=E2=80=99ve heard on the grapevine that do= ing so allows all these programs to compile unmodified.

Another thing that you should consider is the Windows Subsystem for Linux4. This basically allows you to i= nstall a Linux VM-ish thing on Windows 10. That will also definitely get yo= u situated.

But some of you might want to do things the Pure Windows Way. That=E2=80= =99s very gutsy of you, and this is what you have to do: run out and get Un= ix immediately! No, no=E2=80=94I=E2=80=99m kidding. I=E2=80=99m supposed to= be Windows-friendly(er) these days=E2=80=A6

This is what you=E2=80=99ll have to do (unless you install Cygwin!): first, ignore pretty much all of the syste= m header files I mention in here. All you need to include is:

    #include <winsock.h>

Wait! You also have to make a call to WSAStartup() before = doing anything else with the sockets library. The code to do that looks som= ething like this:

#include <winsock.h>
<=
/span>
{=

 =
   WSADATA wsaData;   // if this doesn't work
 =
   //WSAData wsaData; // then try this instead
<=
/span>
 =
   // MAKEWORD(1,1) for Winsock 1.1, MAKEWORD(2,0) for W=
insock 2.0:
<=
/span>
 =
   if (WSAStartup(MAKEWORD(1,1), &wsaData) !=3D 0=
) {
        fprintf(stderr, "WSAStartup failed.\n");
        exit(1);
    }

You also have to tell your compiler to link in the Winsock library, usua= lly called wsock32.lib or winsock32.lib, or ws2_32.lib for Winsock 2.0. Under VC++, this can be done through th= e Project menu, under Settings.... Click the Link tab, and look for the box titled =E2=80=9CObject/library modu= les=E2=80=9D. Add =E2=80=9Cwsock32.lib=E2=80=9D (or whichever lib is your p= reference) to that list.

Or so I hear.

Finally, you need to call WSACleanup() when you=E2=80=99re= all through with the sockets library. See your online help for details.

Once you do that, the rest of the examples in this tutorial should gener= ally apply, with a few exceptions. For one thing, you can=E2=80=99t use close() to close a socket=E2=80=94you need to use closesoc= ket(), instead. Also, select() only works with socket = descriptors, not file descriptors (like 0 for stdin).

There is also a socket class that you can use, CSocket. Ch= eck your compilers help pages for more information.

To get more information about Winsock, read the Winsock FAQ5<= /sup> and go from there.

Finally, I hear that Windows has no fork() system call whi= ch is, unfortunately, used in some of my examples. Maybe you have to link i= n a POSIX library or something to get it to work, or you can use Cre= ateProcess() instead. fork() takes no arguments, and CreateProcess() takes about 48 billion arguments. If you=E2=80= =99re not up to that, the CreateThread() is a little easier t= o digest=E2=80=A6unfortunately a discussion about multithreading is beyond = the scope of this document. I can only talk about so much, you know!

1.6 Email Policy

I=E2=80=99m generally available to help out with email questions so fee= l free to write in, but I can=E2=80=99t guarantee a response. I lead a pret= ty busy life and there are times when I just can=E2=80=99t answer a questio= n you have. When that=E2=80=99s the case, I usually just delete the message= . It=E2=80=99s nothing personal; I just won=E2=80=99t ever have the time to= give the detailed answer you require.

As a rule, the more complex the question, the less likely I am to respon= d. If you can narrow down your question before mailing it and be sure to in= clude any pertinent information (like platform, compiler, error messages yo= u=E2=80=99re getting, and anything else you think might help me troubleshoo= t), you=E2=80=99re much more likely to get a response. For more pointers, r= ead ESR=E2=80=99s document, How To Ask Questions The Smart Way6.

If you don=E2=80=99t get a response, hack on it some more, try to find t= he answer, and if it=E2=80=99s still elusive, then write me again with the = information you=E2=80=99ve found and hopefully it will be enough for me to = help out.

Now that I=E2=80=99ve badgered you about how to write and not write me, = I=E2=80=99d just like to let you know that I fully appreciate all = the praise the guide has received over the years. It=E2=80=99s a real moral= e boost, and it gladdens me to hear that it is being used for good! := -) Thank you!

1.7 Mirroring

You are more than welcome to mirror this site, whether publicly or priv= ately. If you publicly mirror the site and want me to link to it from the m= ain page, drop me a line at beej@beej.us.

1.8 Note for Translators

If you want to translate the guide into another language, write me at <= a href=3D"http://beej.us/guide/bgnet/html/beej@beej.us">beej@beej.us<= /code> and I=E2=80=99ll link to your translation from the main page. Fe= el free to add your name and contact info to the translation.

This source markdown document uses UTF-8 encoding.

Please note the license restrictions in the Copyright, Distribution, and Legal section, belo= w.

If you want me to host the translation, just ask. I=E2=80=99ll also link= to it if you want to host it; either way is fine.

= 1.9 Copyright, Distribution, and Legal

Beej=E2=80=99s Guide to Network Programming is Copyright =C2=A9 2019 Bri= an =E2=80=9CBeej Jorgensen=E2=80=9D Hall.

With specific exceptions for source code and translations, below, this w= ork is licensed under the Creative Commons Attribution- Noncommercial- No D= erivative Works 3.0 License. To view a copy of this license, visit

htt= ps://creativecommons.org/licenses/by-nc-nd/3.0/

or send a letter to Creative Commons, 171 Second Street, Suite 300, San = Francisco, California, 94105, USA.

One specific exception to the =E2=80=9CNo Derivative Works=E2=80=9D port= ion of the license is as follows: this guide may be freely translated into = any language, provided the translation is accurate, and the guide is reprin= ted in its entirety. The same license restrictions apply to the translation= as to the original guide. The translation may also include the name and co= ntact information for the translator.

The C source code presented in this document is hereby granted to the pu= blic domain, and is completely free of any license restriction.

Educators are freely encouraged to recommend or supply copies of this gu= ide to their students.

Unless otherwise mutually agreed by the parties in writing, the author o= ffers 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, merchantibility, fitness for a par= ticular purpose, noninfringement, or the absence of latent or other defects= , accuracy, or the presence of absence of errors, whether or not discoverab= le.

Except to the extent required by applicable law, in no event will the au= thor be liable to you on any legal theory for any special, incidental, cons= equential, 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.

Contact beej@beej.us fo= r more information.

1.10 Dedication

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 s= oftware and packages that I use to make the Guide: GNU, Linux, Slackware, v= im, Python, Inkscape, pandoc, many others. And finally a big thank-you to t= he literally thousands of you who have written in with suggestions for impr= ovements and words of encouragement.

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 Commun= ity.

1.11 Publishing Information

This book is written in Markdown using the vim editor on an Arch Linux b= ox loaded with GNU tools. The cover =E2=80=9Cart=E2=80=9D 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 compos= ed of 100% Free and Open Source Software.

2 What is a socket?

You hear talk of =E2=80=9Csockets=E2=80=9D all the time, and perhaps yo= u are wondering just what they are exactly. Well, they=E2=80=99re this: a w= ay to speak to other programs using standard Unix file descriptors.

What?

Ok=E2=80=94you may have heard some Unix hacker state, =E2=80=9CJeez, everything in Unix is a file!=E2=80=9D 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 sim= ply an integer associated with an open file. But (and here=E2=80=99s the ca= tch), 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 = is a file! So when you want to communicate with another program over t= he Internet you=E2=80=99re gonna do it through a file descriptor, you=E2=80= =99d better believe it.

=E2=80=9CWhere do I get this file descriptor for network communication, = Mr. Smarty-Pants?=E2=80=9D is probably the last question on your mind right= now, but I=E2=80=99m going to answer it anyway: You make a call to the socket() system routine. It returns the socket descriptor, and = you communicate through it using the specialized send() and = recv() (<= code>man send, man recv) socket calls.

=E2=80=9CBut, hey!=E2=80=9D you might be exclaiming right about now. =E2= =80=9CIf it=E2=80=99s a file descriptor, why in the name of Neptune can=E2= =80=99t I just use the normal read() and write() calls to communicate through the socket?=E2=80=9D The short answer is, = =E2=80=9CYou can!=E2=80=9D The longer answer is, =E2=80=9CYou can, but send() and recv() offer much greater control over y= our data transmission.=E2=80=9D

What next? How about this: there are all kinds of sockets. There are DA= RPA 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 docum= ent deals only with the first: Internet Sockets.

2.1 Two Types of Internet Sockets

What=E2=80=99s this? There are two types of Internet sockets? Yes. Well= , no. I=E2=80=99m lying. There are more, but I didn=E2=80=99t want to scare= you. I=E2=80=99m only going to talk about two types here. Except for this = sentence, where I=E2=80=99m going to tell you that =E2=80=9CRaw Sockets= =E2=80=9D are also very powerful and you should look them up.

All right, already. What are the two types? One is =E2=80=9CStream Sock= ets=E2=80=9D; the other is =E2=80=9CDatagram Sockets=E2=80=9D, which may h= ereafter be referred to as =E2=80=9CSOCK_STREAM=E2=80=9D and = =E2=80=9CSOCK_DGRAM=E2=80=9D, respectively. Datagram sockets a= re sometimes called =E2=80=9Cconnectionless sockets=E2=80=9D. (Though they = can be connect()=E2=80=99d if you really want. See connect(), belo= w.)

Stream sockets are reliable two-way connected communication streams. If = you output two items into the socket in the order =E2=80=9C1, 2=E2=80=9D, t= hey will arrive in the order =E2=80=9C1, 2=E2=80=9D at the opposite end. Th= ey will also be error-free. I=E2=80=99m so certain, in fact, they will be e= rror-free, that I=E2=80=99m just going to put my fingers in my ears and cha= nt la la la la if anyone tries to claim otherwise.

What uses stream sockets? Well, you may have heard of the telnet= application, yes? It uses stream sockets. All the characters you ty= pe need to arrive in the same order you type them, right? Also, web browser= s 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 =E2=80= =9CGET / HTTP/1.0=E2=80=9D and hit RETURN twice, it=E2=80=99ll= dump the HTML back at you!

If you don=E2=80=99t have telnet installed and don=E2=80=99= t want to install it, or your telnet is being picky about conn= ecting to clients, the guide comes with a telnet-like program = called teln= ot7. This should = work well for all the needs of the guide. (Note that telnet is actually a <= a href=3D"https://tools.ietf.org/html/rfc854">spec=E2=80=99d networking pro= tocol8, and telnot= doesn=E2=80=99t implement this protocol at all.)

How do stream sockets achieve this high level of data transmission quali= ty? They use a protocol called =E2=80=9CThe Transmission Control Protocol= =E2=80=9D, otherwise known as =E2=80=9CTCP=E2=80=9D (see RFC 7939 for extremely detailed info on TCP). TCP makes sure your dat= a arrives sequentially and error-free. You may have heard =E2=80=9CTCP=E2= =80=9D before as the better half of =E2=80=9CTCP/IP=E2=80=9D where =E2=80= =9CIP=E2=80=9D stands for =E2=80=9CInternet Protocol=E2=80=9D (see RFC 79110). IP deals primarily with Internet routing and = is not generally responsible for data integrity.

Cool. What about Datagram sockets? Why are they called connectionless? = What is the deal, here, anyway? Why are they unreliable? Well, here are som= e 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.

Datagram sockets also use IP for routing, but they don=E2=80=99t use TCP= ; they use the =E2=80=9CUser Datagram Protocol=E2=80=9D, or =E2=80=9CUDP= =E2=80=9D (see RFC 76811).

Why are they connectionless? Well, basically, it=E2=80=99s because you d= on=E2=80=99t have to maintain an open connection as you do with stream sock= ets. You just build a packet, slap an IP header on it with destination info= rmation, and send it out. No connection needed. They are generally used eit= her when a TCP stack is unavailable or when a few dropped packets here and = there don=E2=80=99t mean the end of the Universe. Sample applications: tftp (trivial file transfer protocol, a little brother to FTP), dhcpcd (a DHCP client), multiplayer games, streaming audio, vide= o conferencing, etc.

=E2=80=9CWait a minute! tftp and dhcpcd are us= ed to transfer binary applications from one host to another! Data can=E2=80= =99t be lost if you expect the application to work when it arrives! What ki= nd of dark magic is this?=E2=80=9D

Well, my human friend, tftp and similar programs have their= own protocol on top of UDP. For example, the tftp protocol says that for e= ach packet that gets sent, the recipient has to send back a packet that say= s, =E2=80=9CI got it!=E2=80=9D (an =E2=80=9CACK=E2=80=9D packet). If the se= nder of the original packet gets no reply in, say, five seconds, he=E2=80= =99ll re-transmit the packet until he finally gets an ACK. This acknowledgm= ent procedure is very important when implementing reliable SOCK_DGRAM= applications.

For unreliable applications like games, audio, or video, you just ignore= the dropped packets, or perhaps try to cleverly compensate for them. (Quak= e players will know the manifestation this effect by the technical term: accursed lag. The word =E2=80=9Caccursed=E2=80=9D, in this case, rep= resents any extremely profane utterance.)

Why would you use an unreliable underlying protocol? Two reasons: speed = and speed. It=E2=80=99s way faster to fire-and-forget than it is to keep tr= ack of what has arrived safely and make sure it=E2=80=99s in order and all = that. If you=E2=80=99re sending chat messages, TCP is great; if you=E2=80= =99re sending 40 positional updates per second of the players in the world,= maybe it doesn=E2=80=99t matter so much if one or two get dropped, and UDP= is a good choice.

2.2 Low level Nonsense and Network Theory

Since I just mentioned layering of protocols, it=E2=80=99s time to talk = about how networks really work, and to show some examples of how SOC= K_DGRAM packets are built. Practically, you can probably skip this s= ection. It=E2=80=99s good background, however.

Data Encapsul= ation.

Hey, kids, it=E2=80=99s time to learn about Data Encapsulation= ! This is very very important. It=E2=80=99s so important that you might jus= t learn about it if you take the networks course here at Chico State = ;-). Basically, it says this: a packet is born, the packet is wrappe= d (=E2=80=9Cencapsulated=E2=80=9D) in a header (and rarely a footer) by t= he first protocol (say, the TFTP protocol), then the whole thing (TFTP hea= der 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).

When another computer receives the packet, the hardware strips the Ether= net header, the kernel strips the IP and UDP headers, the TFTP program stri= ps the TFTP header, and it finally has the data.

Now I can finally talk about the infamous Layered Network Model (aka =E2=80=9CISO/OSI=E2=80=9D). This Network Model describes a system of= network functionality that has many advantages over other models. For inst= ance, you can write sockets programs that are exactly the same without cari= ng how the data is physically transmitted (serial, thin Ethernet, AUI, what= ever) because programs on lower levels deal with it for you. The actual net= work hardware and topology is transparent to the socket programmer.

Without any further ado, I=E2=80=99ll present the layers of the full-blo= wn model. Remember this for network class exams:

  • Application
  • Presentation
  • Session
  • Transport
  • Network
  • Data Link
  • Physical

The Physical Layer is the hardware (serial, Ethernet, etc.). The Applica= tion Layer is just about as far from the physical layer as you can imagine= =E2=80=94it=E2=80=99s the place where users interact with the network.

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:

  • Application Layer (telnet, ftp, etc.)
  • Host-to-Host Transport Layer (TCP, UDP)
  • Internet Layer (IP and routing)
  • Network Access Layer (Ethernet, wi-fi, or whatever)

At this point in time, you can probably see how these layers correspond = to the encapsulation of the original data.

See how much work there is in building a simple packet? Jeez! And you ha= ve to type in the packet headers yourself using =E2=80=9Ccat= =E2=80=9D! Just kidding. All you have to do for stream sockets is se= nd() the data out. All you have to do for datagram sockets is encaps= ulate the packet in the method of your choosing and sendto() = it out. The kernel builds the Transport Layer and Internet Layer on for you= and the hardware does the Network Access Layer. Ah, modern technology.

So ends our brief foray into network theory. Oh yes, I forgot to tell yo= u everything I wanted to say about routing: nothing! That=E2=80=99s right, = I=E2=80=99m not going to talk about it at all. The router strips the packet= to the IP header, consults its routing table, blah blah blah. Ch= eck out the IP RFC12 if you really really care. If= you never learn about it, well, you=E2=80=99ll live.

3 IP Addresses, structs, = and Data Munging

Here=E2=80=99s the part of the game where we get to talk code for a chan= ge.

But first, let=E2=80=99s discuss more non-code! Yay! First I want to tal= k about IP addresses and ports for just a tad so we have that sorted out. = Then we=E2=80=99ll talk about how the sockets API stores and manipulates IP= addresses and other data.

3.1 IP Addresses, versions 4 and 6

In the good old days back when Ben Kenobi was still called Obi Wan Kenob= i, there was a wonderful network routing system called The Internet Protoco= l Version 4, also called IPv4. It had addresses made up of four bytes (A.K= .A. four =E2=80=9Coctets=E2=80=9D), and was commonly written in =E2=80=9Cdo= ts and numbers=E2=80=9D form, like so: 192.0.2.111.

You=E2=80=99ve probably seen it around.

In fact, as of this writing, virtually every site on the Internet uses I= Pv4.

Everyone, including Obi Wan, was happy. Things were great, until some na= ysayer by the name of Vint Cerf warned everyone that we were about to run o= ut of IPv4 addresses!

(Besides warning everyone of the Coming IPv4 Apocalypse Of Doom And Gloo= m, Vint Cerf13 is also well-known for being = The Father Of The Internet. So I really am in no position to second-guess h= is judgment.)

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 co= mputers out there?

Yes.

Also, in the beginning, when there were only a few computers and everyon= e 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.)

In fact, if it weren=E2=80=99t for several stopgap measures, we would ha= ve run out a long time ago.

But now we=E2=80=99re living in an era where we=E2=80=99re 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.

And so, IPv6 was born. Since Vint Cerf is probably immortal (even if hi= s physical form should pass on, heaven forbid, he is probably already exist= ing as some kind of hyper-intelligent ELIZA14 pro= gram out in the depths of the Internet2), no one wants to have to hear him = say again =E2=80=9CI told you so=E2=80=9D if we don=E2=80=99t have enough a= ddresses in the next version of the Internet Protocol.

What does this suggest to you?

That we need a lot more addresses. That we need not just twice = as many addresses, not a billion times as many, not a thousand trillion tim= es as many, but 79 MILLION BILLION TRILLION times as many possible addr= esses! That=E2=80=99ll show =E2=80=99em!

You=E2=80=99re saying, =E2=80=9CBeej, is that true? I have every reason = to disbelieve large numbers.=E2=80=9D Well, the difference between 32 bits = and 128 bits might not sound like a lot; it=E2=80=99s only 96 more bits, ri= ght? But remember, we=E2=80=99re talking powers here: 32 bits represents so= me 4 billion numbers (232), while 128 bits represents about 340 = trillion trillion trillion numbers (for real, 2128). That=E2=80= =99s like a million IPv4 Internets for every single star in the Univers= e.

Forget this dots-and-numbers look of IPv4, too; now we=E2=80=99ve got a = hexadecimal representation, with each two-byte chunk separated by a colon, = like this:

    2001:0db8:c9d2:aee5:73e3:934a:a5ae:9551

That=E2=80=99s not all! Lots of times, you=E2=80=99ll have an IP address= with lots of zeros in it, and you can compress them between two colons. An= d you can leave off leading zeros for each byte pair. For instance, each of= these pairs of addresses are equivalent:

    2001:0db8:c9d2:0012:0000:0000:0000:0051
    2001:db8:c9d2:12::51
   =20
    2001:0db8:ab00:0000:0000:0000:0000:0000
    2001:db8:ab00::
   =20
    0000:0000:0000:0000:0000:0000:0000:0001
    ::1

The address ::1 is the loopback address. It always= means =E2=80=9Cthis machine I=E2=80=99m running on now=E2=80=9D. In IPv4, = the loopback address is 127.0.0.1.

Finally, there=E2=80=99s an IPv4-compatibility mode for IPv6 addresses t= hat 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 n= otation: =E2=80=9C::ffff:192.0.2.33=E2=80=9D.

We=E2=80=99re talking serious fun.

In fact, it=E2=80=99s such serious fun, that the Creators of IPv6 have q= uite cavalierly lopped off trillions and trillions of addresses for reserve= d use, but we have so many, frankly, who=E2=80=99s even counting anymore? T= here are plenty left over for every man, woman, child, puppy, and parking m= eter on every planet in the galaxy. And believe me, every planet in the gal= axy has parking meters. You know it=E2=80=99s true.

3.1.1 Subnets

For organizational reasons, it=E2=80=99s sometimes convenient to declare= that "this first part of this IP address up through this bit is the ne= twork portion of the IP address, and the remainder is the host por= tion.

For instance, with IPv4, you might have 192.0.2.12, and we = could say that the first three bytes are the network and the last byte was = the host. Or, put another way, we=E2=80=99re talking about host 12 on network 192.0.2.0 (see how we zero out the byte that w= as the host).

And now for more outdated information! Ready? In the Ancient Times, ther= e were =E2=80=9Cclasses=E2=80=9D of subnets, where the first one, two, or t= hree 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 bi= ts-worth of hosts on your network (16 million or so). That was a =E2=80=9CC= lass A=E2=80=9D network. On the opposite end was a =E2=80=9CClass C=E2=80= =9D, with three bytes of network, and one byte of host (256 hosts, minus a = couple that were reserved).

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.

The network portion of the IP address is described by something called t= he netmask, which you bitwise-AND with the IP address to get the n= etwork number out of it. The netmask usually looks something like 255= .255.255.0. (E.g. with that netmask, if your IP is 192.0.2.12<= /code>, then your network is 192.0.2.12 AND 255.255.255.= 0 which gives 192.0.2.0.)

Unfortunately, it turned out that this wasn=E2=80=99t fine-grained enoug= h for the eventual needs of the Internet; we were running out of Class C ne= tworks quite quickly, and we were most definitely out of Class As, so don= =E2=80=99t even bother to ask. To remedy this, The Powers That Be allowed f= or the netmask to be an arbitrary number of bits, not just 8, 16, or 24. So= you might have a netmask of, say 255.255.255.252, which is 30= bits of network, and 2 bits of host allowing for four hosts on the network= . (Note that the netmask is ALWAYS a bunch of 1-bits followed by a= bunch of 0-bits.)

But it=E2=80=99s a bit unwieldy to use a big string of numbers like 255.192.0.0 as a netmask. First of all, people don=E2=80=99t have = an intuitive idea of how many bits that is, and secondly, it=E2=80=99s real= ly not compact. So the New Style came along, and it=E2=80=99s much nicer. Y= ou just put a slash after the IP address, and then follow that by the numbe= r of network bits in decimal. Like this: 192.0.2.12/30.

Or, for IPv6, something like this: 2001:db8::/32 or 2= 001:db8:5413:4028::9db9/64.

3.1.2 Port Numbers

If you=E2=80=99ll kindly remember, I presented you earlier with the Layered Network Model= which had the Internet Layer (IP) split off from the Host-to-Host Transpor= t Layer (TCP and UDP). Get up to speed on that before the next paragraph.

Turns out that besides an IP address (used by the IP layer), there is an= other address that is used by TCP (stream sockets) and, coincidentally, by = UDP (datagram sockets). It is the port number. It=E2=80=99s a 16-b= it number that=E2=80=99s like the local address for the connection.

Think of the IP address as the street address of a hotel, and the port n= umber as the room number. That=E2=80=99s a decent analogy; maybe later I=E2= =80=99ll come up with one involving the automobile industry.

Say you want to have a computer that handles incoming mail AND web servi= ces=E2=80=94how do you differentiate between the two on a computer with a s= ingle IP address?

Well, different services on the Internet have different well-known port = numbers. You can see them all in the Big IANA Port List15 or, if you=E2=80=99re on a Unix box, in your /etc/= services file. HTTP (the web) is port 80, telnet is port 23, SMTP is= port 25, the game DOOM16 used p= ort 666, etc. and so on. Ports under 1024 are often considered special, and= usually require special OS privileges to use.

And that=E2=80=99s about it!

3.2 Byte Order

By Order of the Realm! There shall be two byte orderings, hereafter to = be known as Lame and Magnificent!

I joke, but one really is better than the other. :-)

There really is no easy way to say this, so I=E2=80=99ll just blurt it o= ut: your computer might have been storing bytes in reverse order behind you= r back. I know! No one wanted to have to tell you.

The thing is, everyone in the Internet world has generally agreed that i= f you want to represent the two-byte hex number, say b34f, you= =E2=80=99ll store it in two sequential bytes b3 followed by 4f. Makes sense, and, as Wilford Brimley17 would tell you, it=E2=80=99s the Right Thing To Do. This num= ber, stored with the big end first, is called Big-Endian.

Unfortunately, a few computers scattered here and there through= out the world, namely anything with an Intel or Intel-compatible processor,= store the bytes reversed, so b34f would be stored in memory a= s the sequential bytes 4f followed by b3. This st= orage method is called Little-Endian.

But wait, I=E2=80=99m not done with terminology yet! The more-sane B= ig-Endian is also called Network Byte Order because that=E2= =80=99s the order us network types like.

Your computer stores numbers in Host Byte Order. If it=E2=80=99= s an Intel 80x86, Host Byte Order is Little-Endian. If it=E2=80=99s a Motor= ola 68k, Host Byte Order is Big-Endian. If it=E2=80=99s a PowerPC, Host Byt= e Order is=E2=80=A6 well, it depends!

A lot of times when you=E2=80=99re building packets or filling out data = structures you=E2=80=99ll need to make sure your two- and four-byte numbers= are in Network Byte Order. But how can you do this if you don=E2=80=99t kn= ow the native Host Byte Order?

Good news! You just get to assume the Host Byte Order isn=E2=80=99t righ= t, and you always run the value through a function to set it to Network Byt= e Order. The function will do the magic conversion if it has to, and this w= ay your code is portable to machines of differing endianness.

All righty. There are two types of numbers that you can convert: s= hort (two bytes) and long (four bytes). These functions= work for the unsigned variations as well. Say you want to con= vert a short from Host Byte Order to Network Byte Order. Start= with =E2=80=9Ch=E2=80=9D for =E2=80=9Chost=E2=80=9D, follow it with =E2=80= =9Cto=E2=80=9D, then =E2=80=9Cn=E2=80=9D for =E2=80=9Cnetwork=E2=80=9D, and= =E2=80=9Cs=E2=80=9D for =E2=80=9Cshort=E2=80=9D: h-to-n-s, or htons(= ) (read: =E2=80=9CHost to Network Short=E2=80=9D).

It=E2=80=99s almost too easy=E2=80=A6

You can use every combination of =E2=80=9Cn=E2=80=9D, =E2=80=9Ch=E2=80= =9D, =E2=80=9Cs=E2=80=9D, and =E2=80=9Cl=E2=80=9D you want, not counting th= e really stupid ones. For example, there is NOT a stolh() (=E2= =80=9CShort to Long Host=E2=80=9D) function=E2=80=94not at this party, anyw= ay. But there are:

Function Description
htons() host to network sho= rt
htonl() host to network lon= g
ntohs() network to host sho= rt
ntohl() network to host lon= g

Basically, you=E2=80=99ll want to convert the numbers to Network Byte Or= der before they go out on the wire, and convert them to Host Byte Order as = they come in off the wire.

I don=E2=80=99t know of a 64-bit variant, sorry. And if you want to do f= loating point, check out the section on Serialization, far below.

Assume the numbers in this document are in Host Byte Order unless I say = otherwise.

3.3 structs

Well, we=E2=80=99re finally here. It=E2=80=99s time to talk about progra= mming. In this section, I=E2=80=99ll cover various data types used by the s= ockets interface, since some of them are a real bear to figure out.

First the easy one: a socket descriptor. A socket descriptor is the fol= lowing type:

    int

Just a regular int.

Things get weird from here, so just read through and bear with me.

My First Struct=E2=84=A2=E2=80=94struct addrinfo. This str= ucture is a more recent invention, and is used to prep the socket address s= tructures for subsequent use. It=E2=80=99s also used in host name lookups, = and service name lookups. That=E2=80=99ll make more sense later when we get= to actual usage, but just know for now that it=E2=80=99s one of the first = things you=E2=80=99ll call when making a connection.

    struct addrinfo {
        int  =
            ai_flags;     // AI_PASSIVE, AI_CANONNAME, e=
tc.
        int  =
            ai_family;    // AF_INET, AF_INET6, AF_UNSPE=
C
        int  =
            ai_socktype;  // SOCK_STREAM, SOCK_DGRAM
        int  =
            ai_protocol;  // use 0 for "any"
        size_t           ai_addrlen;   // size of ai_addr in bytes
        struct sockaddr *ai_addr;      // struct sockaddr_in or _in6<=
/span>
        char =
           *ai_canonname; // full canonical hostname
    
        struct addrinfo *ai_next;      // linked list, next node
    };

You=E2=80=99ll load this struct up a bit, and then call getaddrin= fo(). It=E2=80=99ll return a pointer to a new linked list of these s= tructures filled out with all the goodies you need.

You can force it to use IPv4 or IPv6 in the ai_family field= , or leave it as AF_UNSPEC to use whatever. This is cool becau= se your code can be IP version-agnostic.

Note that this is a linked list: ai_next points at the next= element=E2=80=94there could be several results for you to choose from. I= =E2=80=99d use the first result that worked, but you might have different b= usiness needs; I don=E2=80=99t know everything, man!

You=E2=80=99ll see that the ai_addr field in the stru= ct addrinfo is a pointer to a struct sockaddr. This is= where we start getting into the nitty-gritty details of what=E2=80=99s ins= ide an IP address structure.

You might not usually need to write to these structures; oftentimes, a c= all to getaddrinfo() to fill out your struct addrinfo for you is all you=E2=80=99ll need. You will, however, have t= o peer inside these structs to get the values out, so I=E2=80= =99m presenting them here.

(Also, all the code written before struct addrinfo was inve= nted we packed all this stuff by hand, so you=E2=80=99ll see a lot of IPv4 = code out in the wild that does exactly that. You know, in old versions of t= his guide and so on.)

Some structs are IPv4, some are IPv6, and some are both. I= =E2=80=99ll make notes of which are what.

Anyway, the struct sockaddr holds socket address informatio= n for many types of sockets.

    struct sockaddr {
        unsigned short    sa_family;    /=
/ address family, AF_xxx
        char              sa_data[14];  /=
/ 14 bytes of protocol address
    }; 

sa_family can be a variety of things, but it=E2=80=99ll be = AF_INET (IPv4) or AF_INET6 (IPv6) for everythin= g we do in this document. sa_data contains a destination addre= ss and port number for the socket. This is rather unwieldy since you don=E2= =80=99t want to tediously pack the address in the sa_data by h= and.

To deal with struct sockaddr, programmers created a paralle= l structure: struct sockaddr_in (=E2=80=9Cin=E2=80=9D for =E2= =80=9CInternet=E2=80=9D) to be used with IPv4.

And this is the important bit: a pointer to a struct sock= addr_in can be cast to a pointer to a struct sockaddr a= nd vice-versa. So even though connect() wants a struct s= ockaddr*, you can still use a struct sockaddr_in and ca= st it at the last minute!

    // (IPv4 only--see struct sockaddr_in6 for IPv6)
    
    struct =
sockaddr_in {
        short int          sin_family;  /=
/ Address family, AF_INET
        unsigned short int sin_por=
t;    // Port number
        struct in_addr     sin_addr;    // Internet address<=
/span>
        unsigned char      sin_zero[8]; // Same size as struct sockaddr
    };

This structure makes it easy to reference elements of the socket address= . Note that sin_zero (which is included to pad the structure t= o the length of a struct sockaddr) should be set to all zeros = with the function memset(). Also, notice that sin_family= corresponds to sa_family in a struct sockaddr and should be set to =E2=80=9CAF_INET=E2=80=9D. Finally, = the sin_port must be in Network Byte Order (by using= htons()!)

Let=E2=80=99s dig deeper! You see the sin_addr field is a <= code>struct in_addr. What is that thing? Well, not to be overly dram= atic, but it=E2=80=99s one of the scariest unions of all time:

    // (IPv4 only--see struct in6_addr for IPv6)
    
    // Internet ad=
dress (a structure for historical reasons)
    struct =
in_addr {
        uint32_t s_addr; // that's a 32-bit int (4 bytes)
    };

Whoa! Well, it used to be a union, but now those days seem to b= e gone. Good riddance. So if you have declared ina to be of ty= pe struct sockaddr_in, then ina.sin_addr.s_addr r= eferences the 4-byte IP address (in Network Byte Order). Note that even if = your system still uses the God-awful union for struct in_addr,= you can still reference the 4-byte IP address in exactly the same way as I= did above (this due to #defines).

What about IPv6? Similar structs exist for it, as well:

    // (IPv6 only--see struct sockaddr_in and struct in_addr for IPv4)<=
/span>
    
    struct =
sockaddr_in6 {
        u_int16_t       sin6_family; =
  // address family, AF_INET6
        u_int16_t       sin6_port;   =
  // port number, Network Byte Order
        u_int32_t       sin6_flowinfo=
; // IPv6 flow information
        struct in6_addr sin6_addr;     // IPv6 address
        u_int32_t       sin6_scope_id=
; // Scope ID
    };
    
    struct in6_addr {
        unsigned=
 char   s6_addr[16];   // IPv6 address
    };

Note that IPv6 has an IPv6 address and a port number, just like IPv4 has= an IPv4 address and a port number.

Also note that I=E2=80=99m not going to talk about the IPv6 flow informa= tion or Scope ID fields for the moment=E2=80=A6 this is just a starter guid= e. :-)

Last but not least, here is another simple structure, struct socka= ddr_storage that is designed to be large enough to hold both IPv4 an= d IPv6 structures. See, for some calls, sometimes you don=E2=80=99t know in= advance if it=E2=80=99s going to fill out your struct sockaddr with an IPv4 or IPv6 address. So you pass in this parallel structure, ver= y similar to struct sockaddr except larger, and then cast it t= o the type you need:

    struct sockaddr_storage {
        sa_family_t  ss_family;     <=
span class=3D"co">// address family
    
        // all thi=
s is padding, implementation specific, ignore it:
        char      __ss_pad1[_SS_PAD1SIZE];
        int64_t   __ss_align;
        char      __ss_pad2[_SS_PAD2SIZE];
    };

What=E2=80=99s important is that you can see the address family in the <= code>ss_family field=E2=80=94check this to see if it=E2=80=99s AF_INET or AF_INET6 (for IPv4 or IPv6). Then you can c= ast it to a struct sockaddr_in or struct sockaddr_in6 if you wanna.

3.4 IP Addresses, Part Deux

Fortunately for you, there are a bunch of functions that allow you to ma= nipulate IP addresses. No need to figure them out by hand and stuff them i= n a long with the << operator.

First, let=E2=80=99s say you have a struct sockaddr_in ina,= and you have an IP address =E2=80=9C10.12.110.57=E2=80=9D or = =E2=80=9C2001:db8:63b3:1::3490=E2=80=9D that you want to store= into it. The function you want to use, inet_pton(), converts= an IP address in numbers-and-dots notation into either a struct in_a= ddr or a struct in6_addr depending on whether you speci= fy AF_INET or AF_INET6. (=E2=80=9Cpton=E2=80=9D stands for =E2=80=9Cpresentation to network=E2=80=9D=E2=80=94yo= u can call it =E2=80=9Cprintable to network=E2=80=9D if that=E2=80=99s easi= er to remember.) The conversion can be made as follows:

    struct sockaddr_in sa; // IPv4
    struct =
sockaddr_in6 sa6; // IPv6
    
    inet_pton(AF_INET, "10.12.110.57", &(sa.sin_addr)); // IPv4=

    inet_pton(AF_INET6, "2001:db8:63b3:1::3490", &(sa6.sin6_addr)); // IPv6

(Quick note: the old way of doing things used a function called i= net_addr() or another function called inet_aton(); the= se are now obsolete and don=E2=80=99t work with IPv6.)

Now, the above code snippet isn=E2=80=99t very robust because there is n= o error checking. See, inet_pton() returns -1 on = error, or 0 if the address is messed up. So check to make sure the result i= s greater than 0 before using!

All right, now you can convert string IP addresses to their binary repre= sentations. What about the other way around? What if you have a struc= t in_addr and you want to print it in numbers-and-dots notation? (Or= a struct in6_addr that you want in, uh, =E2=80=9Chex-and-colo= ns=E2=80=9D notation.) In this case, you=E2=80=99ll want to use the functio= n inet_ntop() (=E2=80=9Cntop=E2=80=9D means =E2=80=9Cnetwork = to presentation=E2=80=9D=E2=80=94you can call it =E2=80=9Cnetwork to printa= ble=E2=80=9D if that=E2=80=99s easier to remember), like this:

When you call it, you=E2=80=99ll pass the address type (IPv4 or IPv6), t= he address, a pointer to a string to hold the result, and the maximum lengt= h of that string. (Two macros conveniently hold the size of the string you= =E2=80=99ll need to hold the largest IPv4 or IPv6 address: INET_ADDRS= TRLEN and INET6_ADDRSTRLEN.)

(Another quick note to mention once again the old way of doing things: t= he historical function to do this conversion was called inet_ntoa()<= /code>. It=E2=80=99s also obsolete and won=E2=80=99t work with IPv6.)

Lastly, these functions only work with numeric IP addresses=E2=80=94they= won=E2=80=99t do any nameserver DNS lookup on a hostname, like =E2=80=9Cwww.example.com=E2=80=9D. You will use getaddrinfo() to do that, as you=E2=80=99ll see later on.

3.4.1 Private (Or Disconnected) Network= s

Lots of places have a firewall that hides the network from the rest of= the world for their own protection. And often times, the firewall translat= es =E2=80=9Cinternal=E2=80=9D IP addresses to =E2=80=9Cexternal=E2=80=9D (t= hat everyone else in the world knows) IP addresses using a process called <= em>Network Address Translation, or NAT.

Are you getting nervous yet? =E2=80=9CWhere=E2=80=99s he going with all = this weird stuff?=E2=80=9D

Well, relax and buy yourself a non-alcoholic (or alcoholic) drink, becau= se as a beginner, you don=E2=80=99t even have to worry about NAT, since it= =E2=80=99s done for you transparently. But I wanted to talk about the netwo= rk behind the firewall in case you started getting confused by the network = numbers you were seeing.

For instance, I have a firewall at home. I have two static IPv4 addresse= s allocated to me by the DSL company, and yet I have seven computers on the= network. How is this possible? Two computers can=E2=80=99t share the same = IP address, or else the data wouldn=E2=80=99t know which one to go to!

The answer is: they don=E2=80=99t share the same IP addresses. They are = on a private network with 24 million IP addresses allocated to it. They are= all just for me. Well, all for me as far as anyone else is concerned. Here= =E2=80=99s what=E2=80=99s happening:

If I log into a remote computer, it tells me I=E2=80=99m logged in from = 192.0.2.33 which is the public IP address my ISP has provided to me. But if= I ask my local computer what its IP address is, it says 10.0.0.5. Who is t= ranslating the IP address from one to the other? That=E2=80=99s right, the = firewall! It=E2=80=99s doing NAT!

10.x.x.x is one of a few reserved networks that are only to= be used either on fully disconnected networks, or on networks that are beh= ind firewalls. The details of which private network numbers are available f= or you to use are outlined in RFC 191818, but som= e common ones you=E2=80=99ll see are 10.x.x.x and 192.= 168.x.x, where x is 0-255, generally. Less common is 172.y.x.x, where y goes between 16 and 31.

Networks behind a NATing firewall don=E2=80=99t need to be on o= ne of these reserved networks, but they commonly are.

(Fun fact! My external IP address isn=E2=80=99t really 192.0.2.33<= /code>. The 192.0.2.x network is reserved for make-believe =E2= =80=9Creal=E2=80=9D IP addresses to be used in documentation, just like thi= s guide! Wowzers!)

IPv6 has private networks, too, in a sense. They=E2=80=99ll start with = fdXX: (or maybe in the future fcXX:), as per RFC 419319. NAT and IPv6 don=E2=80=99t generally mi= x, however (unless you=E2=80=99re doing the IPv6 to IPv4 gateway thing whic= h is beyond the scope of this document)=E2=80=94in theory you=E2=80=99ll ha= ve so many addresses at your disposal that you won=E2=80=99t need to use NA= T any longer. But if you want to allocate addresses for yourself on a netwo= rk that won=E2=80=99t route outside, this is how to do it.

4 Jumping from IPv4 to IPv6

But I just want to know what to change in my code to get it going with = IPv6! Tell me now!

Ok! Ok!

Almost everything in here is something I=E2=80=99ve gone over, above, bu= t it=E2=80=99s the short version for the impatient. (Of course, there is mo= re than this, but this is what applies to the guide.)

  1. First of all, try to use getaddrinfo() to get all the struct socka= ddr info, instead of packing the structures by hand. This will keep = you IP version-agnostic, and will eliminate many of the subsequent steps.

  2. Any place that you find you=E2=80=99re hard-coding anything related = to the IP version, try to wrap up in a helper function.

  3. Change AF_INET to AF_INET6.

  4. Change PF_INET to PF_INET6.

  5. Change INADDR_ANY assignments to in6addr_any assignments, which are slightly different:

        struct sockaddr_in sa;
        struct =
    sockaddr_in6 sa6;
    
        sa.sin_addr.s_addr =3D INADDR_ANY=
    ;  // use my IPv4 address
        sa6.sin6_addr =3D in6addr_any; // use my IPv6 address

    Also, the value IN6ADDR_ANY_INIT can be used as an initiali= zer when the struct in6_addr is declared, like so:

        struct in6_addr ia6 =3D IN6ADDR_ANY_INIT;
  6. Instead of struct sockaddr_in use struct sockaddr= _in6, being sure to add =E2=80=9C6=E2=80=9D to the fields as appropr= iate (see struct= s, above). There is no sin6_zero field.

  7. Instead of struct in_addr use struct in6_addr, being sure to add =E2=80=9C6=E2=80=9D to the fields as appropriate (se= e structs= , above).

  8. Instead of inet_aton() or inet_addr(), use= inet_pton().

  9. Instead of inet_ntoa(), use inet_ntop().

  10. Instead of gethostbyname(), use the superior geta= ddrinfo().

  11. Instead of gethostbyaddr(), use the superior get= nameinfo() (although gethostbyaddr() can still work wit= h IPv6).

  12. INADDR_BROADCAST no longer works. Use IPv6 multicast in= stead.

Et voila!

5 System Calls or Bust

This is the section where we get into the system calls (and other librar= y calls) that allow you to access the network functionality of a Unix box, = or any box that supports the sockets API for that matter (BSD, Windows, Lin= ux, Mac, what-have-you.) When you call one of these functions, the kernel t= akes over and does all the work for you automagically.

The place most people get stuck around here is what order to call these = things in. In that, the man pages are no use, as you=E2=80=99v= e probably discovered. Well, to help with that dreadful situation, I=E2=80= =99ve tried to lay out the system calls in the following sections in ex= actly (approximately) the same order that you=E2=80=99ll need to call = them in your programs.

That, coupled with a few pieces of sample code here and there, some milk= and cookies (which I fear you will have to supply yourself), and some raw = guts and courage, and you=E2=80=99ll be beaming data around the Internet li= ke the Son of Jon Postel!

(Please note that for brevity, many code snippets below do not inclu= de necessary error checking. And they very commonly assume that the result = from calls to getaddrinfo() succeed and return a valid entry i= n the linked list. Both of these situations are properly addressed in the s= tand-alone programs, though, so use those as a model.)

5.1 getaddrinfo()=E2=80=94Prepar= e to launch!

This is a real workhorse of a function with a lot of options, but usage= is actually pretty simple. It helps set up the structs you ne= ed later on.

A tiny bit of history: it used to be that you would use a function calle= d gethostbyname() to do DNS lookups. Then you=E2=80=99d load t= hat information by hand into a struct sockaddr_in, and use tha= t in your calls.

This is no longer necessary, thankfully. (Nor is it desirable, if you wa= nt to write code that works for both IPv4 and IPv6!) In these modern times,= you now have the function getaddrinfo() that does all kinds o= f good stuff for you, including DNS and service name lookups, and fills out= the structs you need, besides!

Let=E2=80=99s take a look!

    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netdb.h>
    
    int get=
addrinfo(const char *no=
de,     // e.g. "www.example.com" or IP
                    const char *service,  // e.g. "http" or port number
                    const struct addrinfo *hints,
                    struct addrinfo **res);

You give this function three input parameters, and it gives you a pointe= r to a linked-list, res, of results.

The node parameter is the host name to connect to, or an IP= address.

Next is the parameter service, which can be a port number, = like =E2=80=9C80=E2=80=9D, or the name of a particular service (found in The IANA Port List<= /a>20 or the /etc/se= rvices file on your Unix machine) like =E2=80=9Chttp=E2=80=9D or =E2= =80=9Cftp=E2=80=9D or =E2=80=9Ctelnet=E2=80=9D or =E2=80=9Csmtp=E2=80=9D or= whatever.

Finally, the hints parameter points to a struct addri= nfo that you=E2=80=99ve already filled out with relevant information= .

Here=E2=80=99s a sample call if you=E2=80=99re a server who wants to lis= ten on your host=E2=80=99s IP address, port 3490. Note that this doesn=E2= =80=99t actually do any listening or network setup; it merely sets up struc= tures we=E2=80=99ll use later:

Notice that I set the ai_family to AF_UNSPEC, = thereby saying that I don=E2=80=99t care if we use IPv4 or IPv6. You can se= t it to AF_INET or AF_INET6 if you want one or th= e other specifically.

Also, you=E2=80=99ll see the AI_PASSIVE flag in there; this= tells getaddrinfo() to assign the address of my local host to= the socket structures. This is nice because then you don=E2=80=99t have to= hardcode it. (Or you can put a specific address in as the first parameter = to getaddrinfo() where I currently have NULL, up = there.)

Then we make the call. If there=E2=80=99s an error (getaddrinfo()<= /code> returns non-zero), we can print it out using the function gai_= strerror(), as you see. If everything works properly, though, = servinfo will point to a linked list of struct addrinfo= s, each of which contains a struct sockaddr of some kind that = we can use later! Nifty!

Finally, when we=E2=80=99re eventually all done with the linked list tha= t getaddrinfo() so graciously allocated for us, we can (and sh= ould) free it all up with a call to freeaddrinfo().

Here=E2=80=99s a sample call if you=E2=80=99re a client who wants to con= nect to a particular server, say =E2=80=9Cwww.example.net=E2=80=9D port 349= 0. Again, this doesn=E2=80=99t actually connect, but it sets up the structu= res we=E2=80=99ll use later:

I keep saying that servinfo is a linked list with all kinds= of address information. Let=E2=80=99s write a quick demo program to show o= ff this information. This short program21 will print the IP addresses for whatever host you specify on the command= line:

/*<=
/span>
** showip.c -- show IP addresses for a host given on th=
e command line
*/

#include <stdio.h>
#include <string.h>
#include <sys/types.h><=
/span>
#include <sys/socket.h>=

#include <netdb.h>
<=
/a>#include <arpa/inet.h>=
;
<=
/a>#include <netinet/in.h&g=
t;
<=
/a>
<=
/a>int main(int argc, <=
span class=3D"dt">char *argv[])
<=
/a>{
<=
/a>    struct addrinfo hints, *res, *p;
<=
/a>    int status;
<=
/a>    char ipstr[INET6_ADDRSTRLEN];
<=
/a>
<=
/a>    if (argc !=3D 2)=
 {
<=
/a>        fprintf(stderr,"usage: showip hostname=
\n");
<=
/a>        return 1;
<=
/a>    }
<=
/a>
<=
/a>    memset(&hints, 0, s=
izeof hints);
<=
/a>    hints.ai_family =3D AF_UNSPEC; // AF_INET or AF_I=
NET6 to force version
<=
/a>    hints.ai_socktype =3D SOCK_STREAM;
<=
/a>
<=
/a>    if ((status =3D getaddrinfo(argv[1], NULL, &hints, &res)) !=3D 0=
) {
<=
/a>        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
<=
/a>        return 2;
<=
/a>    }
<=
/a>
<=
/a>    printf("IP addresses for %s:\n\n", argv[1]);
<=
/a>
<=
/a>    for(p =3D res;p !=3D NULL; p =3D p->ai_=
next) {
<=
/a>        void *addr;
<=
/a>        char *ipver;
<=
/a>
<=
/a>        // get the pointer to the address itself,
<=
/a>        // different fields in IPv4 and IPv6:<=
/span>
<=
/a>        if (p->ai_family =3D=3D AF_INET) { =
// IPv4
<=
/a>            struct sockaddr_in *ipv4 =3D (struct sockaddr_in *)p->ai_addr;
<=
/a>            addr =3D &(ipv4->sin_addr);
<=
/a>            ipver =3D "IPv4";
<=
/a>        } else { // IPv6
<=
/a>            struct sockaddr_in6 *ipv6 =3D (struct sockaddr_in6 *)p->ai_addr;
<=
/a>            addr =3D &(ipv6->sin6_addr);
<=
/a>            ipver =3D "IPv6";
<=
/a>        }
<=
/a>
<=
/a>        // convert the IP to a string and print it:
<=
/a>        inet_ntop(p->ai_family, addr, ipstr, sizeo=
f ipstr);
<=
/a>        printf("  %s: %s\n<=
/span>", ipver, ipstr);
<=
/a>    }
<=
/a>
<=
/a>    freeaddrinfo(res); // free the linked list=

<=
/a>
<=
/a>    return 0;
<=
/a>}

As you see, the code calls getaddrinfo() on whatever you pa= ss on the command line, that fills out the linked list pointed to by = res, and then we can iterate over the list and print stuff out or do= whatever.

(There=E2=80=99s a little bit of ugliness there where we have to dig int= o the different types of struct sockaddrs depending on the IP = version. Sorry about that! I=E2=80=99m not sure of a better way around it.)=

Sample run! Everyone loves screenshots:

    $ showip www.example.net
    IP addresses for www.example.net:
   =20
      IPv4: 192.0.2.88
   =20
    $ showip ipv6.example.com
    IP addresses for ipv6.example.com:
   =20
      IPv4: 192.0.2.101
      IPv6: 2001:db8:8c00:22::171

Now that we have that under control, we=E2=80=99ll use the results we ge= t from getaddrinfo() to pass to other socket functions and, at= long last, get our network connection established! Keep reading!

5.2 socket()=E2=80=94Get the File Descriptor!

I guess I can put it off no longer=E2=80=94I have to talk about the socket() system call. Here=E2=80=99s the breakdown:

    #include <sys/types.h>
    #include <sys/socket.h>
    
    int soc=
ket(int domain, int typ=
e, int protocol); 

But what are these arguments? They allow you to say what kind of socket = you want (IPv4 or IPv6, stream or datagram, and TCP or UDP).

It used to be people would hardcode these values, and you can absolutely= still do that. (domain is PF_INET or PF_IN= ET6, type is SOCK_STREAM or SOCK_DGR= AM, and protocol can be set to 0 to choose= the proper protocol for the given type. Or you can call getprotobyname() to look up the protocol you want, =E2=80=9Ctcp=E2= =80=9D or =E2=80=9Cudp=E2=80=9D.)

(This PF_INET thing is a close relative of the AF_IN= ET that you can use when initializing the sin_family fi= eld in your struct sockaddr_in. In fact, they=E2=80=99re so cl= osely related that they actually have the same value, and many programmers = will call socket() and pass AF_INET as the first = argument instead of PF_INET. Now, get some milk and cookies, b= ecause it=E2=80=99s time for a story. Once upon a time, a long time ago, it= was thought that maybe an address family (what the =E2=80=9CAF=E2=80=9D in= =E2=80=9CAF_INET=E2=80=9D stands for) might support several p= rotocols that were referred to by their protocol family (what the =E2=80=9C= PF=E2=80=9D in =E2=80=9CPF_INET=E2=80=9D stands for). That did= n=E2=80=99t happen. And they all lived happily ever after, The End. So the = most correct thing to do is to use AF_INET in your struc= t sockaddr_in and PF_INET in your call to socket(= ).)

Anyway, enough of that. What you really want to do is use the values fro= m the results of the call to getaddrinfo(), and feed them into= socket() directly like this:

socket() simply returns to you a socket descriptor= that you can use in later system calls, or -1 on error. The g= lobal variable errno is set to the error=E2=80=99s value (see = the errno man page for more details, and a quick note on using errno in multithreaded programs).

Fine, fine, fine, but what good is this socket? The answer is that it=E2= =80=99s really no good by itself, and you need to read on and make more sys= tem calls for it to make any sense.

5= .3 bind()=E2=80=94What port am I on?

Once you have a socket, you might have to associate that socket with a = port on your local machine. (This is commonly done if you=E2=80=99re going= to listen() for incoming connections on a specific port=E2= =80=94multiplayer network games do this when they tell you to =E2=80=9Cconn= ect to 192.168.5.10 port 3490=E2=80=9D.) The port number is used by the ker= nel to match an incoming packet to a certain process=E2=80=99s socket descr= iptor. If you=E2=80=99re going to only be doing a connect() (= because you=E2=80=99re the client, not the server), this is probably be unn= ecessary. Read it anyway, just for kicks.

Here is the synopsis for the bind() system call:

    #include <sys/types.h>
    #include <sys/socket.h>
    
    int bin=
d(int sockfd, struct so=
ckaddr *my_addr, int addrlen);

sockfd is the socket file descriptor returned by sock= et(). my_addr is a pointer to a struct sockaddr that contains information about your address, namely, port and IP ad= dress. addrlen is the length in bytes of that address.

Whew. That=E2=80=99s a bit to absorb in one chunk. Let=E2=80=99s have an= example that binds the socket to the host the program is running on, port = 3490:

struct addrinfo hints, *res;
int sockfd;

// first, load up address structs with getaddrinfo():

memset(&hints, 0, sizeof<=
/span> hints);
hints.ai_family =3D AF_UNSPEC;  // use IPv4 or IPv6, wh=
ichever
hints.ai_socktype =3D SOCK_STREAM;
hints.ai_flags =3D AI_PASSIVE;     // fill in my IP for=
 me
<=
/a>
<=
/a>getaddrinfo(NULL, "3490", &hints, &res=
);
<=
/a>
<=
/a>// make a socket:
<=
/a>
<=
/a>sockfd =3D socket(res->ai_family, res->ai_socktype, res->ai_pro=
tocol);
<=
/a>
<=
/a>// bind it to the port we passed in to getaddrinfo():=

<=
/a>
<=
/a>bind(sockfd, res->ai_addr, res->ai_addrlen);

By using the AI_PASSIVE flag, I=E2=80=99m telling the progr= am to bind to the IP of the host it=E2=80=99s running on. If you want to bi= nd to a specific local IP address, drop the AI_PASSIVE and put= an IP address in for the first argument to getaddrinfo().

bind() also returns -1 on error and sets errno to the error=E2=80=99s value.

Lots of old code manually packs the struct sockaddr_in befo= re calling bind(). Obviously this is IPv4-specific, but there= =E2=80=99s really nothing stopping you from doing the same thing with IPv6,= except that using getaddrinfo() is going to be easier, genera= lly. Anyway, the old code looks something like this:

In the above code, you could also assign INADDR_ANY to the = s_addr field if you wanted to bind to your local IP address (l= ike the AI_PASSIVE flag, above). The IPv6 version of INA= DDR_ANY is a global variable in6addr_any that is assign= ed into the sin6_addr field of your struct sockaddr_in6<= /code>. (There is also a macro IN6ADDR_ANY_INIT that you can u= se in a variable initializer.)

Another thing to watch out for when calling bind(): don=E2= =80=99t go underboard with your port numbers. All ports below 1024 are RES= ERVED (unless you=E2=80=99re the superuser)! You can have any port number a= bove that, right up to 65535 (provided they aren=E2=80=99t already being us= ed by another program).

Sometimes, you might notice, you try to rerun a server and bind()<= /code> fails, claiming =E2=80=9CAddress already in use.=E2=80=9D What does= that mean? Well, a little bit of a socket that was connected is still hang= ing around in the kernel, and it=E2=80=99s hogging the port. You can either= wait for it to clear (a minute or so), or add code to your program allowin= g it to reuse the port, like this:

One small extra final note about bind(): there are times w= hen you won=E2=80=99t absolutely have to call it. If you are connect= ()ing to a remote machine and you don=E2=80=99t care what your local= port is (as is the case with telnet where you only care about= the remote port), you can simply call connect(), it=E2=80=99l= l check to see if the socket is unbound, and will bind() it to= an unused local port if necessary.

5.4 connect()=E2=80=94Hey, you!

Let=E2=80=99s just pretend for a few minutes that you=E2=80=99re a teln= et application. Your user commands you (just like in the movie TRON) to get a socket file descriptor. You comply and call socket(). Next, the user tells you to connect to =E2=80=9C10.12.110.57=E2=80=9D on port =E2=80=9C23=E2=80=9D (the standard telnet= port). Yow! What do you do now?

Lucky for you, program, you=E2=80=99re now perusing the section on connect()=E2=80=94how to connect to a remote host. So read furiousl= y onward! No time to lose!

The connect() call is as follows:

    #include <sys/types.h>
    #include <sys/socket.h>
    
    int con=
nect(int sockfd, struct=
 sockaddr *serv_addr, int addrlen); 

sockfd is our friendly neighborhood socket file descriptor,= as returned by the socket() call, serv_addr is a= struct sockaddr containing the destination port and IP addres= s, and addrlen is the length in bytes of the server address st= ructure.

All of this information can be gleaned from the results of the get= addrinfo() call, which rocks.

Is this starting to make more sense? I can=E2=80=99t hear you from here,= so I=E2=80=99ll just have to hope that it is. Let=E2=80=99s have an exampl= e where we make a socket connection to =E2=80=9Cwww.example.com=E2=80=9D, port 3490:

Again, old-school programs filled out their own struct sockaddr_in= s to pass to connect(). You can do that if you want to.= See the similar note in the bind() section, above.

Be sure to check the return value from connect()=E2=80=94it= =E2=80=99ll return -1 on error and set the variable errn= o.

Also, notice that we didn=E2=80=99t call bind(). Basically,= we don=E2=80=99t care about our local port number; we only care where we= =E2=80=99re going (the remote port). The kernel will choose a local port fo= r us, and the site we connect to will automatically get this information fr= om us. No worries.

5.5 listen()=E2=80=94Will somebody please call me?

Ok, time for a change of pace. What if you don=E2=80=99t want to connec= t to a remote host. Say, just for kicks, that you want to wait for incoming= connections and handle them in some way. The process is two step: first yo= u listen(), then you accept() (see below).

The listen() call is fairly simple, but requires a bit of e= xplanation:

    int listen(int sockfd, int backlog); 

sockfd is the usual socket file descriptor from the s= ocket() system call. backlog is the number of connecti= ons allowed on the incoming queue. What does that mean? Well, incoming conn= ections are going to wait in this queue until you accept() the= m (see below) and this is the limit on how many can queue up. Most systems = silently limit this number to about 20; you can probably get away with sett= ing it to 5 or 10.

Again, as per usual, listen() returns -1 and s= ets errno on error.

Well, as you can probably imagine, we need to call bind() b= efore we call listen() so that the server is running on a spec= ific port. (You have to be able to tell your buddies which port to connect = to!) So if you=E2=80=99re going to be listening for incoming connections, t= he sequence of system calls you=E2=80=99ll make is:

getaddrinfo();
socket();
bind();
listen();
/* accept() goes here */ 

I=E2=80=99ll just leave that in the place of sample code, since it=E2=80= =99s fairly self-explanatory. (The code in the accept() sectio= n, below, is more complete.) The really tricky part of this whole sha-bang = is the call to accept().

5.6 accept()=E2=80=94= =E2=80=9CThank you for calling port 3490.=E2=80=9D

Get ready=E2=80=94the accept() call is kinda weird! What= =E2=80=99s going to happen is this: someone far far away will try to = connect() to your machine on a port that you are listen()ing on. Their connection will be queued up waiting to be accept()ed. You call accept() and you tell it to get the pen= ding connection. It=E2=80=99ll return to you a brand new socket file de= scriptor to use for this single connection! That=E2=80=99s right, sudd= enly you have two socket file descriptors for the price of one! Th= e original one is still listening for more new connections, and the newly c= reated one is finally ready to send() and recv().= We=E2=80=99re there!

The call is as follows:

    #include <sys/types.h>
    #include <sys/socket.h>
    
    int acc=
ept(int sockfd, struct =
sockaddr *addr, socklen_t *addrlen); 

sockfd is the listen()ing socket descriptor. E= asy enough. addr will usually be a pointer to a local st= ruct sockaddr_storage. This is where the information about the incom= ing connection will go (and with it you can determine which host is calling= you from which port). addrlen is a local integer variable tha= t should be set to sizeof(struct sockaddr_storage) before its = address is passed to accept(). accept() will not = put more than that many bytes into addr. If it puts fewer in, = it=E2=80=99ll change the value of addrlen to reflect that.

Guess what? accept() returns -1 and sets errno if an error occurs. Betcha didn=E2=80=99t figure that.

Like before, this is a bunch to absorb in one chunk, so here=E2=80=99s a= sample code fragment for your perusal:

Again, note that we will use the socket descriptor new_fd f= or all send() and recv() calls. If you=E2=80=99re= only getting one single connection ever, you can close() the = listening sockfd in order to prevent more incoming connections= on the same port, if you so desire.

5.7 send() and recv()=E2=80=94Talk to m= e, baby!

These two functions are for communicating over stream sockets or connect= ed datagram sockets. If you want to use regular unconnected datagram socket= s, you=E2=80=99ll need to see the section on sendto() and recvfrom()= , below.

The send() call:

    int send(int sockfd, const void *msg, int len, int flags); 

sockfd is the socket descriptor you want to send data to (w= hether it=E2=80=99s the one returned by socket() or the one yo= u got with accept()). msg is a pointer to the dat= a you want to send, and len is the length of that data in byte= s. Just set flags to 0. (See the send() man page for more information concerning flags.)

Some sample code might be:

send() returns the number of bytes actually sent out=E2=80= =94this might be less than the number you told it to send! See, so= metimes you tell it to send a whole gob of data and it just can=E2=80=99t h= andle it. It=E2=80=99ll fire off as much of the data as it can, and trust y= ou to send the rest later. Remember, if the value returned by send()<= /code> doesn=E2=80=99t match the value in len, it=E2=80=99s up= to you to send the rest of the string. The good news is this: if the packe= t is small (less than 1K or so) it will probably manage to send th= e whole thing all in one go. Again, -1 is returned on error, a= nd errno is set to the error number.

The recv() call is similar in many respects:

    int recv(int sockfd, void *buf, int len, int flags);

sockfd is the socket descriptor to read from, buf is the buffer to read the information into, len is the max= imum length of the buffer, and flags can again be set to 0. (See the recv() man page for flag information.)

recv() returns the number of bytes actually read into the b= uffer, or -1 on error (with errno set, accordingl= y).

Wait! recv() can return 0. This can mean only = one thing: the remote side has closed the connection on you! A return value= of 0 is recv()=E2=80=99s way of letting you know= this has occurred.

There, that was easy, wasn=E2=80=99t it? You can now pass data back and = forth on stream sockets! Whee! You=E2=80=99re a Unix Network Programmer!

5.8 sendto() and recvfrom()=E2=80=94T= alk to me, DGRAM-style

=E2=80=9CThis is all fine and dandy,=E2=80=9D I hear you saying, =E2=80= =9Cbut where does this leave me with unconnected datagram sockets?=E2=80=9D= No problemo, amigo. We have just the thing.

Since datagram sockets aren=E2=80=99t connected to a remote host, guess = which piece of information we need to give before we send a packet? That=E2= =80=99s right! The destination address! Here=E2=80=99s the scoop:

    int sendto(int sockfd, const void *msg, int len, unsigned int=
 flags,
               con=
st struct sockaddr *to, socklen_t tolen); =

As you can see, this call is basically the same as the call to sen= d() with the addition of two other pieces of information. to is a pointer to a struct sockaddr (which will probably b= e another struct sockaddr_in or struct sockaddr_in6 or struct sockaddr_storage that you cast at the last minute= ) which contains the destination IP address and port. tolen,= an int deep-down, can simply be set to sizeof *to or sizeof(struct sockaddr_storage).

To get your hands on the destination address structure, you=E2=80=99ll p= robably either get it from getaddrinfo(), or from recvfr= om(), below, or you=E2=80=99ll fill it out by hand.

Just like with send(), sendto() returns the nu= mber of bytes actually sent (which, again, might be less than the number of= bytes you told it to send!), or -1 on error.

Equally similar are recv() and recvfrom(). Th= e synopsis of recvfrom() is:

    int recvfrom(int sockfd, void *buf, int len, unsigned int flags,
                 s=
truct sockaddr *from, int *fromlen); 

Again, this is just like recv() with the addition of a coup= le fields. from is a pointer to a local struct sockaddr= _storage that will be filled with the IP address and port of the ori= ginating machine. fromlen is a pointer to a local int that should be initialized to sizeof *from or sizeo= f(struct sockaddr_storage). When the function returns, fromlen= will contain the length of the address actually stored in fro= m.

recvfrom() returns the number of bytes received, or -= 1 on error (with errno set accordingly).

So, here=E2=80=99s a question: why do we use struct sockaddr_stora= ge as the socket type? Why not struct sockaddr_in? Beca= use, you see, we want to not tie ourselves down to IPv4 or IPv6. So we use = the generic struct sockaddr_storage which we know will be big = enough for either.

(So=E2=80=A6 here=E2=80=99s another question: why isn=E2=80=99t st= ruct sockaddr itself big enough for any address? We even cast the ge= neral-purpose struct sockaddr_storage to the general-purpose <= code>struct sockaddr! Seems extraneous and redundant, huh. The answe= r is, it just isn=E2=80=99t big enough, and I=E2=80=99d guess that changing= it at this point would be Problematic. So they made a new one.)

Remember, if you connect() a datagram socket, you can then= simply use send() and recv() for all your transa= ctions. The socket itself is still a datagram socket and the packets still = use UDP, but the socket interface will automatically add the destination an= d source information for you.

5.9 close() and shu= tdown()=E2=80=94Get outta my face!

Whew! You=E2=80=99ve been send()ing and recv()= ing data all day long, and you=E2=80=99ve had it. You=E2=80=99re ready to c= lose the connection on your socket descriptor. This is easy. You can just u= se the regular Unix file descriptor close() function:

    close(sockfd)=
; 

This will prevent any more reads and writes to the socket. Anyone attemp= ting to read or write the socket on the remote end will receive an error.

Just in case you want a little more control over how the socket closes, = you can use the shutdown() function. It allows you to cut off= communication in a certain direction, or both ways (just like close(= ) does). Synopsis:

    int shutdown(int sockfd, int how); 

sockfd is the socket file descriptor you want to shutdown, = and how is one of the following:

how Effect
0 Further receives are disallowed
1 Further sends are disallowed
2 Further sends and receives are disallowed (like close())

shutdown() returns 0 on success, and -1<= /code> on error (with errno set accordingly).

If you deign to use shutdown() on unconnected datagram sock= ets, it will simply make the socket unavailable for further send() and recv() calls (remember that you can use these if you = connect() your datagram socket).

It=E2=80=99s important to note that shutdown() doesn=E2=80= =99t actually close the file descriptor=E2=80=94it just changes its usabili= ty. To free a socket descriptor, you need to use close().

Nothing to it.

(Except to remember that if you=E2=80=99re using Windows and Winsock t= hat you should call closesocket() instead of close().)

5.10 getpeername()=E2=80=94Who are yo= u?

This function is so easy.

It=E2=80=99s so easy, I almost didn=E2=80=99t give it its own section. B= ut here it is anyway.

The function getpeername() will tell you who is at the othe= r end of a connected stream socket. The synopsis:

    #include <sys/socket.h>
    
    int get=
peername(int sockfd, struct sockaddr *addr, int *addrlen); 

sockfd is the descriptor of the connected stream socket, addr is a pointer to a struct sockaddr (or a = struct sockaddr_in) that will hold the information about the other s= ide of the connection, and addrlen is a pointer to an in= t, that should be initialized to sizeof *addr or = sizeof(struct sockaddr).

The function returns -1 on error and sets errno accordingly.

Once you have their address, you can use inet_ntop(), getnameinfo(), or gethostbyaddr() to print or get m= ore information. No, you can=E2=80=99t get their login name. (Ok, ok. If th= e other computer is running an ident daemon, this is possible. This, howeve= r, is beyond the scope of this document. Check out RFC 1413= 22 for more info.)

5.11 gethostname()=E2=80=94Who am I?

Even easier than getpeername() is the function getho= stname(). It returns the name of the computer that your program is r= unning on. The name can then be used by gethostbyname(), belo= w, to determine the IP address of your local machine.

What could be more fun? I could think of a few things, but they don=E2= =80=99t pertain to socket programming. Anyway, here=E2=80=99s the breakdown= :

    #include <unistd.h>
    
    int get=
hostname(char *hostname, size_=
t size); 

The arguments are simple: hostname is a pointer to an array= of chars that will contain the hostname upon the function=E2=80=99s return= , and size is the length in bytes of the hostname= array.

The function returns 0 on successful completion, and = -1 on error, setting errno as usual.

6 Client-Server Background

It=E2=80=99s a client-server world, baby. Just about everything on the = network deals with client processes talking to server processes and vice-ve= rsa. Take telnet, for instance. When you connect to a remote h= ost on port 23 with telnet (the client), a program on that host (called telnetd, the server) springs to life. It handles the incoming tel= net connection, sets you up with a login prompt, etc.

Client-Server Int= eraction.

The exchange of information between client and server is summarized in t= he above diagram.

Note that the client-server pair can speak SOCK_STREAM, SOCK_DGRAM, or anything else (as long as they=E2=80=99re speaking= the same thing). Some good examples of client-server pairs are telne= t/telnetd, ftp/ftpd, or Firefox/Apache. Every time you use ftp, t= here=E2=80=99s a remote program, ftpd, that serves you.

Often, there will only be one server on a machine, and that server will = handle multiple clients using fork(). The basic routine is: s= erver will wait for a connection, accept() it, and fork(= ) a child process to handle it. This is what our sample server does = in the next section.

6.1 A Simple Stream Server

All this server does is send the string =E2=80=9CHello, world!=E2=80=9D out over a stream connection. All you need to do to test this= server is run it in one window, and telnet to it from another with:

    $ telnet remotehostname 3490

where remotehostname is the name of the machine you=E2=80= =99re running it on.

The server cod= e23:

/*<=
/span>
** server.c -- a stream socket server demo
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
<=
/a>#include <sys/types.h>=
;
<=
/a>#include <sys/socket.h&g=
t;
<=
/a>#include <netinet/in.h&g=
t;
<=
/a>#include <netdb.h>
<=
/a>#include <arpa/inet.h>=
;
<=
/a>#include <sys/wait.h>=

<=
/a>#include <signal.h>
<=
/a>
<=
/a>#define PORT "3490"  // the=
 port users will be connecting to
<=
/a>
<=
/a>#define BACKLOG 10   // how=
 many pending connections queue will hold
<=
/a>
<=
/a>void sigchld_handler(int s)
<=
/a>{
<=
/a>    // waitpid() might overwrite errno, so we save an=
d restore it:
<=
/a>    int saved_errno =3D errno;
<=
/a>
<=
/a>    while(waitpid(-1=
, NULL, WNOHANG) > 0);
<=
/a>
<=
/a>    errno =3D saved_errno;
<=
/a>}
<=
/a>
<=
/a>
<=
/a>// get sockaddr, IPv4 or IPv6:
<=
/a>void *get_in_addr(struct sockaddr *sa)
<=
/a>{
<=
/a>    if (sa->sa_family =3D=3D AF_INET) {
<=
/a>        return &(((stru=
ct sockaddr_in*)sa)->sin_addr);
<=
/a>    }
<=
/a>
<=
/a>    return &(((struct sockaddr_in6*)sa)->sin6_addr);
<=
/a>}
<=
/a>
<=
/a>int main(void)
<=
/a>{
<=
/a>    int sockfd, new_fd;  //=
 listen on sock_fd, new connection on new_fd
<=
/a>    struct addrinfo hints, *servinfo, *p;
<=
/a>    struct sockaddr_storage their_addr; // connector's address information
<=
/a>    socklen_t sin_size;
<=
/a>    struct sigaction sa;
<=
/a>    int yes=3D1;
<=
/a>    char s[INET6_ADDRSTRLEN];
<=
/a>    int rv;
<=
/a>
<=
/a>    memset(&hints, 0, s=
izeof hints);
<=
/a>    hints.ai_family =3D AF_UNSPEC;
<=
/a>    hints.ai_socktype =3D SOCK_STREAM;
<=
/a>    hints.ai_flags =3D AI_PASSIVE; // use my IP
<=
/a>
<=
/a>    if ((rv =3D getaddrinfo(NULL, PORT, &h=
ints, &servinfo)) !=3D 0) {
<=
/a>        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
<=
/a>        return 1;
<=
/a>    }
<=
/a>
<=
/a>    // loop through all the results and bind to the f=
irst we can
<=
/a>    for(p =3D servinfo; p !=3D NULL; p =3D p-&=
gt;ai_next) {
<=
/a>        if ((sockfd =3D socket(p->ai_family=
, p->ai_socktype,
<=
/a>                p->ai_protocol)) =3D=3D -1)=
 {
<=
/a>            perror("server: socket");
<=
/a>            continue;
<=
/a>        }
<=
/a>
<=
/a>        if (setsockopt(sockfd, SOL_SOCKET, SO_=
REUSEADDR, &yes,
<=
/a>                sizeof(int<=
/span>)) =3D=3D -1) {
<=
/a>            perror("setsockopt");
<=
/a>            exit(1);
<=
/a>        }
<=
/a>
<=
/a>        if (bind(sockfd, p->ai_addr, p->=
ai_addrlen) =3D=3D -1) {
<=
/a>            close(sockfd);
<=
/a>            perror("server: bind");
<=
/a>            continue;
<=
/a>        }
<=
/a>
<=
/a>        break;
<=
/a>    }
<=
/a>
<=
/a>    freeaddrinfo(servinfo); // all done with this str=
ucture
<=
/a>
<=
/a>    if (p =3D=3D NULL)  {
<=
/a>        fprintf(stderr, "server: failed to bind\n");
<=
/a>        exit(1);
<=
/a>    }
<=
/a>
<=
/a>    if (listen(sockfd, BACKLOG) =3D=3D -1) {
<=
/a>        perror("listen");
<=
/a>        exit(1);
<=
/a>    }
<=
/a>
<=
/a>    sa.sa_handler =3D sigchld_handler; // reap all de=
ad processes
    sigemptyset(&sa.sa_mask);
    sa.sa_flags =3D SA_RESTART;
    if (sigaction(SIGCHLD, &sa, NULL) =
=3D=3D -1) {
        perror("sigaction");
        exit(1);
    }

    printf("server: waiting for connections...\n");

    while(1) {  // main accept() loop
        sin_size =3D sizeof their_addr;
        new_fd =3D accept(sockfd, (struct so=
ckaddr *)&their_addr, &sin_size);
        if (new_fd =3D=3D -1) {
            perror("accept");
            continue;
        }

        inet_ntop(their_addr.ss_family,
            get_in_addr((struct sockaddr *)&=
amp;their_addr),
            s, sizeof s);
        printf("server: got connection from %s\n", s);

        if (!fork()) { //=
 this is the child process
            close(sockfd); // child doesn't need th=
e listener
            if (send(new_fd, "Hello, world!", 13, 0) =3D=3D -1)
                perror("send");
            close(new_fd);
            exit(0);
        }
        close(new_fd);  // parent doesn't need this=

    }

    return 0;
}

In case you=E2=80=99re curious, I have the code in one big main()<= /code> function for (I feel) syntactic clarity. Feel free to split it into = smaller functions if it makes you feel better.

(Also, this whole sigaction() thing might be new to you=E2= =80=94that=E2=80=99s ok. The code that=E2=80=99s there is responsible for r= eaping zombie processes that appear as the fork()ed child pro= cesses exit. If you make lots of zombies and don=E2=80=99t reap them, your = system administrator will become agitated.)

You can get the data from this server by using the client listed in the = next section.

6.2 A Simple Stream Client

This guy=E2=80=99s even easier than the server. All this client does is= connect to the host you specify on the command line, port 3490. It gets th= e string that the server sends.

The client sou= rce24:

/*<=
/span>
** client.c -- a stream socket client demo
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
<=
/a>#include <netdb.h>
<=
/a>#include <sys/types.h>=
;
<=
/a>#include <netinet/in.h&g=
t;
<=
/a>#include <sys/socket.h&g=
t;
<=
/a>
<=
/a>#include <arpa/inet.h>=
;
<=
/a>
<=
/a>#define PORT "3490" // the =
port client will be connecting to 
<=
/a>
<=
/a>#define MAXDATASIZE 100 // =
max number of bytes we can get at once 
<=
/a>
<=
/a>// get sockaddr, IPv4 or IPv6:
<=
/a>void *get_in_addr(struct sockaddr *sa)
<=
/a>{
<=
/a>    if (sa->sa_family =3D=3D AF_INET) {
<=
/a>        return &(((stru=
ct sockaddr_in*)sa)->sin_addr);
<=
/a>    }
<=
/a>
<=
/a>    return &(((struct sockaddr_in6*)sa)->sin6_addr);
<=
/a>}
<=
/a>
<=
/a>int main(int argc, <=
span class=3D"dt">char *argv[])
<=
/a>{
<=
/a>    int sockfd, numbytes;  
<=
/a>    char buf[MAXDATASIZE];
<=
/a>    struct addrinfo hints, *servinfo, *p;
<=
/a>    int rv;
<=
/a>    char s[INET6_ADDRSTRLEN];
<=
/a>
<=
/a>    if (argc !=3D 2)=
 {
<=
/a>        fprintf(stderr,"usage: client hostname=
\n");
<=
/a>        exit(1);
<=
/a>    }
<=
/a>
<=
/a>    memset(&hints, 0, s=
izeof hints);
<=
/a>    hints.ai_family =3D AF_UNSPEC;
<=
/a>    hints.ai_socktype =3D SOCK_STREAM;
<=
/a>
<=
/a>    if ((rv =3D getaddrinfo(argv[1], PORT, &hints, &servinfo)) !=3D 0) {
<=
/a>        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
<=
/a>        return 1;
<=
/a>    }
<=
/a>
<=
/a>    // loop through all the results and connect to th=
e first we can
<=
/a>    for(p =3D servinfo; p !=3D NULL; p =3D p-&=
gt;ai_next) {
<=
/a>        if ((sockfd =3D socket(p->ai_family=
, p->ai_socktype,
<=
/a>                p->ai_protocol)) =3D=3D -1)=
 {
<=
/a>            perror("client: socket");
<=
/a>            continue;
<=
/a>        }
<=
/a>
<=
/a>        if (connect(sockfd, p->ai_addr, p-&=
gt;ai_addrlen) =3D=3D -1) {
<=
/a>            close(sockfd);
<=
/a>            perror("client: connect");
<=
/a>            continue;
<=
/a>        }
<=
/a>
<=
/a>        break;
<=
/a>    }
<=
/a>
<=
/a>    if (p =3D=3D NULL) {
<=
/a>        fprintf(stderr, "client: failed to connect\n");
<=
/a>        return 2;
<=
/a>    }
<=
/a>
<=
/a>    inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),
<=
/a>            s, sizeof s);
<=
/a>    printf("client: connecting to %s\n", s);
<=
/a>
<=
/a>    freeaddrinfo(servinfo); // all done with this str=
ucture
<=
/a>
<=
/a>    if ((numbytes =3D recv(sockfd, buf, MAXDAT=
ASIZE-1, 0)) =3D=3D -1) {
<=
/a>        perror("recv");
<=
/a>        exit(1);
<=
/a>    }
<=
/a>
<=
/a>    buf[numbytes] =3D '\0';
<=
/a>
<=
/a>    printf("client: received '%s'\n",buf);
<=
/a>
<=
/a>    close(sockfd);
<=
/a>
<=
/a>    return 0;
<=
/a>}

Notice that if you don=E2=80=99t run the server before you run the clien= t, connect() returns =E2=80=9CConnection refused=E2=80=9D. Ve= ry useful.

6.3 Datagram Sockets

We=E2=80=99ve already covered the basics of UDP datagram sockets with ou= r discussion of sendto() and recvfrom(), above, s= o I=E2=80=99ll just present a couple of sample programs: talker.c and listener.c.

listener sits on a machine waiting for an incoming packet = on port 4950. talker sends a packet to that port, on the speci= fied machine, that contains whatever the user enters on the command line.

Because datagram sockets are connectionless and just fire packets off in= to the ether with callous disregard for success, we are going to tell the c= lient and server to use specifically IPv6. This way we avoid the situation = where the server is listening on IPv6 and the client sends on IPv4; the dat= a simply would not be received. (In our connected TCP stream sockets world,= we might still have the mismatch, but the error on connect() = for one address family would cause us to retry for the other.)

Here is the = source for listener.c25:

/*<=
/span>
** listener.c -- a datagram sockets "server" demo
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
<=
/a>#include <sys/types.h>=
;
<=
/a>#include <sys/socket.h&g=
t;
<=
/a>#include <netinet/in.h&g=
t;
<=
/a>#include <arpa/inet.h>=
;
<=
/a>#include <netdb.h>
<=
/a>
<=
/a>#define MYPORT "4950"    //=
 the port users will be connecting to
<=
/a>
<=
/a>#define MAXBUFLEN 100
<=
/a>
<=
/a>// get sockaddr, IPv4 or IPv6:
<=
/a>void *get_in_addr(struct sockaddr *sa)
<=
/a>{
<=
/a>    if (sa->sa_family =3D=3D AF_INET) {
<=
/a>        return &(((stru=
ct sockaddr_in*)sa)->sin_addr);
<=
/a>    }
<=
/a>
<=
/a>    return &(((struct sockaddr_in6*)sa)->sin6_addr);
<=
/a>}
<=
/a>
<=
/a>int main(void)
<=
/a>{
<=
/a>    int sockfd;
<=
/a>    struct addrinfo hints, *servinfo, *p;
<=
/a>    int rv;
<=
/a>    int numbytes;
<=
/a>    struct sockaddr_storage their_addr;
<=
/a>    char buf[MAXBUFLEN];
<=
/a>    socklen_t addr_len;
<=
/a>    char s[INET6_ADDRSTRLEN];
<=
/a>
<=
/a>    memset(&hints, 0, s=
izeof hints);
<=
/a>    hints.ai_family =3D AF_INET6; // set to AF_INET t=
o use IPv4
<=
/a>    hints.ai_socktype =3D SOCK_DGRAM;
<=
/a>    hints.ai_flags =3D AI_PASSIVE; // use my IP
<=
/a>
<=
/a>    if ((rv =3D getaddrinfo(NULL, MYPORT, &=
;hints, &servinfo)) !=3D 0) {
<=
/a>        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
<=
/a>        return 1;
<=
/a>    }
<=
/a>
<=
/a>    // loop through all the results and bind to the f=
irst we can
<=
/a>    for(p =3D servinfo; p !=3D NULL; p =3D p-&=
gt;ai_next) {
<=
/a>        if ((sockfd =3D socket(p->ai_family=
, p->ai_socktype,
<=
/a>                p->ai_protocol)) =3D=3D -1)=
 {
<=
/a>            perror("listener: socket");
<=
/a>            continue;
<=
/a>        }
<=
/a>
<=
/a>        if (bind(sockfd, p->ai_addr, p->=
ai_addrlen) =3D=3D -1) {
<=
/a>            close(sockfd);
<=
/a>            perror("listener: bind");
<=
/a>            continue;
<=
/a>        }
<=
/a>
<=
/a>        break;
<=
/a>    }
<=
/a>
<=
/a>    if (p =3D=3D NULL) {
<=
/a>        fprintf(stderr, "listener: failed to bind soc=
ket\n");
<=
/a>        return 2;
<=
/a>    }
<=
/a>
<=
/a>    freeaddrinfo(servinfo);
<=
/a>
<=
/a>    printf("listener: waiting to recvfrom...\n");
<=
/a>
<=
/a>    addr_len =3D sizeof their_addr;
<=
/a>    if ((numbytes =3D recvfrom(sockfd, buf, MA=
XBUFLEN-1 , 0,
<=
/a>        (struct sockaddr *)&their_addr, &a=
mp;addr_len)) =3D=3D -1) {
<=
/a>        perror("recvfrom");
<=
/a>        exit(1);
<=
/a>    }
<=
/a>
<=
/a>    printf("listener: got packet from %s\n",
<=
/a>        inet_ntop(their_addr.ss_family,
<=
/a>            get_in_addr((struct sockaddr *)&am=
p;their_addr),
<=
/a>            s, sizeof s));
<=
/a>    printf("listener: packet is %d bytes long<=
span class=3D"sc">\n", numbytes);
<=
/a>    buf[numbytes] =3D '\0';
<=
/a>    printf("listener: packet contains \"%s\"\n", buf);
<=
/a>
<=
/a>    close(sockfd);
<=
/a>
<=
/a>    return 0;
<=
/a>}

Notice that in our call to getaddrinfo() we=E2=80=99re fina= lly using SOCK_DGRAM. Also, note that there=E2=80=99s no need = to listen() or accept(). This is one of the perks= of using unconnected datagram sockets!

Next comes the source for talker.c26:

/*<=
/span>
** talker.c -- a datagram "client" demo
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
<=
/a>#include <sys/types.h>=
;
<=
/a>#include <sys/socket.h&g=
t;
<=
/a>#include <netinet/in.h&g=
t;
<=
/a>#include <arpa/inet.h>=
;
<=
/a>#include <netdb.h>
<=
/a>
<=
/a>#define SERVERPORT "4950"    // the port users will be connecting to
<=
/a>
<=
/a>int main(int argc, <=
span class=3D"dt">char *argv[])
<=
/a>{
<=
/a>    int sockfd;
<=
/a>    struct addrinfo hints, *servinfo, *p;
<=
/a>    int rv;
<=
/a>    int numbytes;
<=
/a>
<=
/a>    if (argc !=3D 3)=
 {
<=
/a>        fprintf(stderr,"usage: talker hostname messag=
e\n");
<=
/a>        exit(1);
<=
/a>    }
<=
/a>
<=
/a>    memset(&hints, 0, s=
izeof hints);
<=
/a>    hints.ai_family =3D AF_INET6; // set to AF_INET t=
o use IPv4
<=
/a>    hints.ai_socktype =3D SOCK_DGRAM;
<=
/a>
<=
/a>    if ((rv =3D getaddrinfo(argv[1], SERVERPORT, &hints, &servinfo)) !=3D 0) {
<=
/a>        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
<=
/a>        return 1;
<=
/a>    }
<=
/a>
<=
/a>    // loop through all the results and make a socket=

<=
/a>    for(p =3D servinfo; p !=3D NULL; p =3D p-&=
gt;ai_next) {
<=
/a>        if ((sockfd =3D socket(p->ai_family=
, p->ai_socktype,
<=
/a>                p->ai_protocol)) =3D=3D -1)=
 {
<=
/a>            perror("talker: socket");
<=
/a>            continue;
<=
/a>        }
<=
/a>
<=
/a>        break;
<=
/a>    }
<=
/a>
<=
/a>    if (p =3D=3D NULL) {
<=
/a>        fprintf(stderr, "talker: failed to create soc=
ket\n");
<=
/a>        return 2;
<=
/a>    }
<=
/a>
<=
/a>    if ((numbytes =3D sendto(sockfd, argv[2], strlen(argv[2]), 0,
<=
/a>             p->ai_addr, p->ai_addrlen)) =3D=3D -1) {
<=
/a>        perror("talker: sendto");
<=
/a>        exit(1);
<=
/a>    }
<=
/a>
<=
/a>    freeaddrinfo(servinfo);
<=
/a>
<=
/a>    printf("talker: sent %d bytes to %s\n", numbytes, argv[1]);
<=
/a>    close(sockfd);
<=
/a>
<=
/a>    return 0;
<=
/a>}

And that=E2=80=99s all there is to it! Run listener on some= machine, then run talker on another. Watch them communicate! = Fun G-rated excitement for the entire nuclear family!

You don=E2=80=99t even have to run the server this time! You can run talker by itself, and it just happily fires packets off into the = ether where they disappear if no one is ready with a recvfrom() on the other side. Remember: data sent using UDP datagram sockets isn=E2= =80=99t guaranteed to arrive!

Except for one more tiny detail that I=E2=80=99ve mentioned many times i= n the past: connected datagram sockets. I need to talk about this here, si= nce we=E2=80=99re in the datagram section of the document. Let=E2=80=99s sa= y that talker calls connect() and specifies the <= code>listener=E2=80=99s address. From that point on, talker may only sent to and receive from the address specified by conne= ct(). For this reason, you don=E2=80=99t have to use sendto()<= /code> and recvfrom(); you can simply use send() = and recv().

7 Slightly Advanced Techniques

These aren=E2=80=99t really advanced, but they=E2=80=99re getti= ng out of the more basic levels we=E2=80=99ve already covered. In fact, if = you=E2=80=99ve gotten this far, you should consider yourself fairly accompl= ished in the basics of Unix network programming! Congratulations!

So here we go into the brave new world of some of the more esoteric thin= gs you might want to learn about sockets. Have at it!

7.1 Blocking

Blocking. You=E2=80=99ve heard about it=E2=80=94now what the heck is it= ? In a nutshell, =E2=80=9Cblock=E2=80=9D is techie jargon for =E2=80=9Cslee= p=E2=80=9D. You probably noticed that when you run listener, a= bove, it just sits there until a packet arrives. What happened is that it c= alled recvfrom(), there was no data, and so recvfrom() is said to =E2=80=9Cblock=E2=80=9D (that is, sleep there) until some = data arrives.

Lots of functions block. accept() blocks. All the rec= v() functions block. The reason they can do this is because they=E2= =80=99re allowed to. When you first create the socket descriptor with socket(), the kernel sets it to blocking. If you don=E2=80=99t wan= t a socket to be blocking, you have to make a call to fcntl()= :

By setting a socket to non-blocking, you can effectively =E2=80=9Cpoll= =E2=80=9D the socket for information. If you try to read from a non-blockin= g socket and there=E2=80=99s no data there, it=E2=80=99s not allowed to blo= ck=E2=80=94it will return -1 and errno will be se= t to EAGAIN or EWOULDBLOCK.

(Wait=E2=80=94it can return EAGAIN or EWOU= LDBLOCK? Which do you check for? The specification doesn=E2=80=99t a= ctually specify which your system will return, so for portability, check th= em both.)

Generally speaking, however, this type of polling is a bad idea. If you = put your program in a busy-wait looking for data on the socket, you=E2=80= =99ll suck up CPU time like it was going out of style. A more elegant solut= ion for checking to see if there=E2=80=99s data waiting to be read comes in= the following section on poll().

7= .2 poll()=E2=80=94Synchronous I/O Multiplexing

What you really want to be able to do is somehow monitor a bunch of sockets at once and then handle the ones that have data ready. This w= ay you don=E2=80=99t have to continously poll all those sockets to see whic= h are ready to read.

A word of warning: poll() is horribly slow when it come= s to giant numbers of connections. In those circumstances, you=E2=80=99ll g= et better performance out of an event library such as libevent27 that attempts to use the fastest possible method availabile on your syste= m.

So how can you avoid polling? Not slightly ironically, you can avoid pol= ling by using the poll() system call. In a nutshell, we=E2=80= =99re going to ask the operating system to do all the dirty work for us, an= d just let us know when some data is ready to read on which sockets. In the= meantime, our process can go to sleep, saving system resources.

The general gameplan is to keep an array of struct pollfds = with information about which socket descriptors we want to monitor, and wha= t kind of events we want to monitor for. The OS will block on the pol= l() call until one of those events occurs (e.g. =E2=80=9Csocket= ready to read!=E2=80=9D) or until a user-specified timeout occurs.

Usefully, a listen()ing socket will return =E2=80=9Cready t= o read=E2=80=9D when a new incoming connection is ready to be accept(= )ed.

That=E2=80=99s enough banter. How do we use this?

    #include <poll.h>
    
    int pol=
l(struct pollfd fds[], nfds_t nfds, int timeout);

fds is our array of information (which sockets to monitor f= or what), nfds is the count of elements in the array, and timeout is a timeout in milliseconds. It returns the number of ele= ments in the array that have had an event occur.

Let=E2=80=99s have a look at that struct:

    struct pollfd {
        int=
 fd;         // the socket descriptor
        short events;   // bitmap of events we're interested in
        short revents;  // when poll() returns, bitmap of events th=
at occurred
    };

So we=E2=80=99re going to have an array of those, and we=E2=80=99ll see = the fd field for each element to a socket descriptor we=E2=80= =99re interested in monitoring. And then we=E2=80=99ll set the events= field to indicate the type of events we=E2=80=99re interested in.

The events field is the bitwise-OR of the following:

Macro Description
POLLIN Alert me when data is ready to recv() on this socket.
POLLOUT Alert me when I can send() data to this socket without blo= cking.

Once you have your array of struct pollfds in order, then y= ou can pass it to poll(), also passing the size of the array, = as well as a timeout value in milliseconds. (You can specify a negative tim= eout to wait forever.)

After poll() returns, you can check the revents field to see if POLLIN or POLLOUT is set, indic= ating that event occurred.

(There=E2=80=99s actually more that you can do with the poll() call. See the poll() man page, below, for more details.)

Here=E2=80=99s a= n example28 where we= =E2=80=99ll wait 2.5 seconds for data to be ready to read from standard inp= ut, i.e. when you hit RETURN:

Notice again that poll() returns the number of elements in = the pfds array for which events have occurred. It doesn=E2=80= =99t tell you which elements in the array (you still have to scan = for that), but it does tell you how many entries have a non-zero reve= nts field (so you can stop scanning after you find that many).

A couple questions might come up here: how to add new file descriptors t= o the set I pass to poll()? For this, simply make sure you hav= e enough space in the array for all you need, or realloc() mor= e space as needed.

What about deleting items from the set? For this, you can copy the last = element in the array over-top the one you=E2=80=99re deleting. And then pas= s in one fewer as the count to poll(). Another option is that = you can set any fd field to a negative number and poll()= will ignore it.

How can we put it all together into a chat server that you can tel= net to?

What we=E2=80=99ll do is start a listener socket, and add it to the set = of file descriptors to poll(). (It will show ready-to-read whe= n there=E2=80=99s an incoming connection.)

Then we=E2=80=99ll add new connections to our struct pollfd= array. And we=E2=80=99ll grow it dynamically if we run out of space.

When a connection is closed, we=E2=80=99ll remove it from the array.

And when a connection is ready-to-read, we=E2=80=99ll read the data from= it and send that data to all the other connections so they can see what th= e other users typed.

So give th= is poll server29 a t= ry. Run it in one window, then telnet localhost 9034 from a nu= mber of other terminal windows. You should be able to see what you type in = one window in the other ones (after you hit RETURN).

Not only that, but if you hit CTRL-] and type quit to exit telnet, the server should detect the disconnectio= n and remove you from the array of file descriptors.

/*<=
/span>
** pollserver.c -- a cheezy multiperson chat server
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h><=
/span>
<=
/a>#include <sys/socket.h&g=
t;
<=
/a>#include <netinet/in.h&g=
t;
<=
/a>#include <arpa/inet.h>=
;
<=
/a>#include <netdb.h>
<=
/a>#include <poll.h>
<=
/a>
<=
/a>#define PORT "9034"   // Po=
rt we're listening on
<=
/a>
<=
/a>// Get sockaddr, IPv4 or IPv6:
<=
/a>void *get_in_addr(struct sockaddr *sa)
<=
/a>{
<=
/a>    if (sa->sa_family =3D=3D AF_INET) {
<=
/a>        return &(((stru=
ct sockaddr_in*)sa)->sin_addr);
<=
/a>    }
<=
/a>
<=
/a>    return &(((struct sockaddr_in6*)sa)->sin6_addr);
<=
/a>}
<=
/a>
<=
/a>// Return a listening socket
<=
/a>int get_listener_socket(voi=
d)
<=
/a>{
<=
/a>    int listener;     // Li=
stening socket descriptor
<=
/a>    int yes=3D1;    =
    // For setsockopt() SO_REUSEADDR, below
<=
/a>    int rv;
<=
/a>
<=
/a>    struct addrinfo hints, *ai, *p;
<=
/a>
<=
/a>    // Get us a socket and bind it
<=
/a>    memset(&hints, 0, s=
izeof hints);
<=
/a>    hints.ai_family =3D AF_UNSPEC;
<=
/a>    hints.ai_socktype =3D SOCK_STREAM;
<=
/a>    hints.ai_flags =3D AI_PASSIVE;
<=
/a>    if ((rv =3D getaddrinfo(NULL, PORT, &h=
ints, &ai)) !=3D 0) {
<=
/a>        fprintf(stderr, "selectserver: %s\n", gai_strerror(rv));
<=
/a>        exit(1);
<=
/a>    }
<=
/a>    
<=
/a>    for(p =3D ai; p !=3D NULL; p =3D p->ai_=
next) {
<=
/a>        listener =3D socket(p->ai_family, p->ai_socktype, p->ai=
_protocol);
<=
/a>        if (listener < 0=
) { 
<=
/a>            continue;
<=
/a>        }
<=
/a>        
<=
/a>        // Lose the pesky "address already in use" er=
ror message
<=
/a>        setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
<=
/a>
<=
/a>        if (bind(listener, p->ai_addr, p-&g=
t;ai_addrlen) < 0) {
<=
/a>            close(listener);
<=
/a>            continue;
<=
/a>        }
<=
/a>
<=
/a>        break;
<=
/a>    }
<=
/a>
<=
/a>    freeaddrinfo(ai); // All done with this
<=
/a>
<=
/a>    // If we got here, it means we didn't get bound
<=
/a>    if (p =3D=3D NULL) {
<=
/a>        return -1;
<=
/a>    }
<=
/a>
<=
/a>    // Listen
<=
/a>    if (listen(listener, 10=
) =3D=3D -1) {
<=
/a>        return -1;
<=
/a>    }
<=
/a>
<=
/a>    return listener;
<=
/a>}
<=
/a>
<=
/a>// Add a new file descriptor to the set
<=
/a>void add_to_pfds(struct pollfd *pfds[], int newfd, int *fd_count, int *fd_size)
<=
/a>{
<=
/a>    // If we don't have room, add more space in the p=
fds array
<=
/a>    if (*fd_count =3D=3D *fd_size) {
<=
/a>        *fd_size *=3D 2; //=
 Double it
<=
/a>
<=
/a>        *pfds =3D realloc(*pfds, sizeof(**pfds=
) * (*fd_size));
<=
/a>    }
<=
/a>
<=
/a>    (*pfds)[*fd_count].fd =3D newfd;
<=
/a>    (*pfds)[*fd_count].events =3D POLLIN; // Check re=
ady-to-read
<=
/a>
<=
/a>    (*fd_count)++;
<=
/a>}
<=
/a>
<=
/a>// Remove an index from the set
<=
/a>void del_from_pfds(struct pollfd pfds[], int i, in=
t *fd_count)
<=
/a>{
<=
/a>    // Copy the one from the end over this one=

<=
/a>    pfds[i] =3D pfds[*fd_count-1];

    (*fd_count)--;
}

// Main
int main(void)
{
    int listener;     // =
Listening socket descriptor

    int newfd;        // =
Newly accept()ed socket descriptor
    struct sockaddr_storage remoteaddr; // Client address
    socklen_t addrlen;

    char buf[256];=
    // Buffer for client data

    char remoteIP[INET6_ADDRSTRLEN];

    // Start off with room for 5 connections=

    // (We'll realloc as necessary)
    int fd_count =3D 0;
    int fd_size =3D 5;
    struct pollfd *pfds =3D malloc(sizeof *pfds * fd_size);

    // Set up and get a listening socket
    listener =3D get_listener_socket();

    if (listener =3D=3D -=
1) {
        fprintf(stderr, "error getting listening so=
cket\n");
        exit(1);
    }

    // Add the listener to set
    pfds[0].fd =3D listener;
    pfds[0].events =3D POLLIN; // Report ready to read on incoming connection

    fd_count =3D 1; // Fo=
r the listener

    // Main loop
    for(;;) {
        int poll_count =3D poll(pfds, fd_cou=
nt, -1);

        if (poll_count =3D=3D -1) {
            perror("poll");
            exit(1);
        }

        // Run through the existing connections loo=
king for data to read
        for(int i =
=3D 0; i < fd_count; i++) {

            // Check if someone's ready to read
            if (pfds[i].revents & POLLIN=
) { // We got one!!

                if (pfds[i].fd =3D=3D listen=
er) {
                    // If listener is ready to read=
, handle new connection

                    addrlen =3D sizeof remot=
eaddr;
                    newfd =3D accept(listener,
                        (struct sockaddr *)&=
amp;remoteaddr,
                        &addrlen);

                    if (newfd =3D=3D -1) {
                        perror("accept");
                    } else {
                        add_to_pfds(&pfds, newfd, &fd_count, &=
amp;fd_size);

                        printf("pollserver: new con=
nection from %s on "
                            "socket %d\n",
                            inet_ntop(remoteaddr.ss_family,
                                get_in_addr((struct=
 sockaddr*)&remoteaddr),
                                remoteIP, INET6_ADDRSTRLEN),
                            newfd);
                    }
                } else {
                    // If not the listener, we're j=
ust a regular client
                    int nbytes =3D recv(pfds=
[i].fd, buf, sizeof buf, 0);

                    int sender_fd =3D pfds[i=
].fd;

                    if (nbytes <=3D 0) {
                        // Got error or connection =
closed by client
                        if (nbytes =3D=3D 0) {
                            // Connection closed
                            printf("pollserver: soc=
ket %d hung up\n", sender_fd);
                        } else {
                            perror("recv");<=
/span>
                        }

                        close(pfds[i].fd); // Bye!<=
/span>

                        del_from_pfds(pfds, i, &fd_count);

                    } else {
                        // We got some good data fr=
om a client

                        for(int j =3D 0; j < fd_count; j++) {
                            // Send to everyone!
                            int dest_fd =3D =
pfds[j].fd;

                            // Except the listener =
and ourselves
                            if (dest_fd !=3D=
 listener && dest_fd !=3D sender_fd) {
                                if (send(des=
t_fd, buf, nbytes, 0) =3D=3D -=
1) {
                                    perror("send");
                                }
                            }
                        }
                    }
                } // END<=
/span> handle data from client
            } // END got ready-to-read from poll()
        } // END looping through file descriptors
    } // END for(;;)--and you thought it would never end!
    
    return 0;
}

In the next section, we=E2=80=99ll look at a similar, older function cal= led select(). Both select() and poll() offer similar functionality and performance, and only really differ in h= ow they=E2=80=99re used. select() might be slightly more porta= ble, but is perhaps a little clunkier in use. Choose the one you like the b= est, as long as it=E2=80=99s supported on your system.

7.3 select()=E2=80=94Synchronous I/O Multiplexing, Old= School

This function is somewhat strange, but it=E2=80=99s very useful. Take t= he following situation: you are a server and you want to listen for incomin= g connections as well as keep reading from the connections you already have= .

No problem, you say, just an accept() and a couple of recv()s. Not so fast, buster! What if you=E2=80=99re blocking on an= accept() call? How are you going to recv() data = at the same time? =E2=80=9CUse non-blocking sockets!=E2=80=9D No way! You d= on=E2=80=99t want to be a CPU hog. What, then?

select() gives you the power to monitor several sockets at = the same time. It=E2=80=99ll tell you which ones are ready for reading, whi= ch are ready for writing, and which sockets have raised exceptions, if you = really want to know that.

A word of warning: select(), though very portable, is t= erribly slow when it comes to giant numbers of connections. In those circum= stances, you=E2=80=99ll get better performance out of an event library such= as libevent30 that attempts to use the fastest possible method= availabile on your system.

Without any further ado, I=E2=80=99ll offer the synopsis of select= ():

    #include <sys/time.h>
    #include <sys/types.h>
    #include <unistd.h>
    
    int sel=
ect(int numfds, fd_set *readfds, fd_set *writefds=
,
               fd_set *exceptfds, struct timeval *timeout); 

The function monitors =E2=80=9Csets=E2=80=9D of file descriptors; in par= ticular readfds, writefds, and exceptfds. If you want to see if you can read from standard input and some socke= t descriptor, sockfd, just add the file descriptors 0 and sockfd to the set readfds. The parameter= numfds should be set to the values of the highest file descri= ptor plus one. In this example, it should be set to sockfd+1, = since it is assuredly higher than standard input (0).

When select() returns, readfds will be modifie= d to reflect which of the file descriptors you selected which is ready for = reading. You can test them with the macro FD_ISSET(), below.

Before progressing much further, I=E2=80=99ll talk about how to manipula= te these sets. Each set is of the type fd_set. The following m= acros operate on this type:

Function Description
FD_SET(int fd, fd_set *set); Add fd to the set.
FD_CLR(int fd, fd_set *set); Remove fd from the set.
FD_ISSET(int fd, fd_set *set); Return true if fd is in the set.
FD_ZERO(fd_set *set); Clear all entries from the set.

Finally, what is this weirded out struct timeval? Well, so= metimes you don=E2=80=99t want to wait forever for someone to send you some= data. Maybe every 96 seconds you want to print =E2=80=9CStill Going=E2=80= =A6=E2=80=9D to the terminal even though nothing has happened. This time st= ructure allows you to specify a timeout period. If the time is exceeded and= select() still hasn=E2=80=99t found any ready file descriptor= s, it=E2=80=99ll return so you can continue processing.

The struct timeval has the follow fields:

    struct timeval {
        int=
 tv_sec;     // seconds
        int=
 tv_usec;    // microseconds
    }; 

Just set tv_sec to the number of seconds to wait, and set <= code>tv_usec to the number of microseconds to wait. Yes, that=E2=80= =99s _micro_seconds, not milliseconds. There are 1,000 microseconds in a mi= llisecond, and 1,000 milliseconds in a second. Thus, there are 1,000,000 mi= croseconds in a second. Why is it =E2=80=9Cusec=E2=80=9D? The =E2=80=9Cu=E2= =80=9D is supposed to look like the Greek letter =CE=BC (Mu) that we use fo= r =E2=80=9Cmicro=E2=80=9D. Also, when the function returns, timeout might be updated to show the time still remaining. This depe= nds on what flavor of Unix you=E2=80=99re running.

Yay! We have a microsecond resolution timer! Well, don=E2=80=99t count o= n it. You=E2=80=99ll probably have to wait some part of your standard Unix = timeslice no matter how small you set your struct timeval.

Other things of interest: If you set the fields in your struct tim= eval to 0, select() will timeout immediate= ly, effectively polling all the file descriptors in your sets. If you set t= he parameter timeout to NULL, it will never timeout, and will = wait until the first file descriptor is ready. Finally, if you don=E2=80=99= t care about waiting for a certain set, you can just set it to NULL in the = call to select().

The following = code snippet31 waits 2= .5 seconds for something to appear on standard input:

If you=E2=80=99re on a line buffered terminal, the key you hit should be= RETURN or it will time out anyway.

Now, some of you might think this is a great way to wait for data on a d= atagram socket=E2=80=94and you are right: it might be. Some Unices= can use select in this manner, and some can=E2=80=99t. You should see what= your local man page says on the matter if you want to attempt it.

Some Unices update the time in your struct timeval to refle= ct the amount of time still remaining before a timeout. But others do not. = Don=E2=80=99t rely on that occurring if you want to be portable. (Use gettimeofday() if you need to track time elapsed. It=E2=80=99s a b= ummer, I know, but that=E2=80=99s the way it is.)

What happens if a socket in the read set closes the connection? Well, in= that case, select() returns with that socket descriptor set a= s =E2=80=9Cready to read=E2=80=9D. When you actually do recv()= from it, recv() will return 0. That=E2=80=99s ho= w you know the client has closed the connection.

One more note of interest about select(): if you have a soc= ket that is listen()ing, you can check to see if there is a = new connection by putting that socket=E2=80=99s file descriptor in the readfds set.

And that, my friends, is a quick overview of the almighty select()= function.

But, by popular demand, here is an in-depth example. Unfortunately, the = difference between the dirt-simple example, above, and this one here is sig= nificant. But have a look, then read the description that follows it.

This pro= gram32 acts like a sim= ple multi-user chat server. Start it running in one window, then teln= et to it (=E2=80=9Ctelnet hostname 9034=E2=80=9D) from = multiple other windows. When you type something in one telnet = session, it should appear in all the others.

/*<=
/span>
** selectserver.c -- a cheezy multiperson chat server
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h><=
/span>
<=
/a>#include <sys/socket.h&g=
t;
<=
/a>#include <netinet/in.h&g=
t;
<=
/a>#include <arpa/inet.h>=
;
<=
/a>#include <netdb.h>
<=
/a>
<=
/a>#define PORT "9034"   // po=
rt we're listening on
<=
/a>
<=
/a>// get sockaddr, IPv4 or IPv6:
<=
/a>void *get_in_addr(struct sockaddr *sa)
<=
/a>{
<=
/a>    if (sa->sa_family =3D=3D AF_INET) {
<=
/a>        return &(((stru=
ct sockaddr_in*)sa)->sin_addr);
<=
/a>    }
<=
/a>
<=
/a>    return &(((struct sockaddr_in6*)sa)->sin6_addr);
<=
/a>}
<=
/a>
<=
/a>int main(void)
<=
/a>{
<=
/a>    fd_set master;    // master file descriptor list<=
/span>
<=
/a>    fd_set read_fds;  // temp file descriptor list fo=
r select()
<=
/a>    int fdmax;        // ma=
ximum file descriptor number
<=
/a>
<=
/a>    int listener;     // li=
stening socket descriptor
<=
/a>    int newfd;        // ne=
wly accept()ed socket descriptor
<=
/a>    struct sockaddr_storage remoteaddr; // client address
<=
/a>    socklen_t addrlen;
<=
/a>
<=
/a>    char buf[256];  =
  // buffer for client data
<=
/a>    int nbytes;
<=
/a>
<=
/a>    char remoteIP[INET6_ADDRSTRLEN];
<=
/a>
<=
/a>    int yes=3D1;    =
    // for setsockopt() SO_REUSEADDR, below
<=
/a>    int i, j, rv;
<=
/a>
<=
/a>    struct addrinfo hints, *ai, *p;
<=
/a>
<=
/a>    FD_ZERO(&master);    // clear the master and =
temp sets
<=
/a>    FD_ZERO(&read_fds);
<=
/a>
<=
/a>    // get us a socket and bind it
<=
/a>    memset(&hints, 0, s=
izeof hints);
<=
/a>    hints.ai_family =3D AF_UNSPEC;
<=
/a>    hints.ai_socktype =3D SOCK_STREAM;
<=
/a>    hints.ai_flags =3D AI_PASSIVE;
<=
/a>    if ((rv =3D getaddrinfo(NULL, PORT, &h=
ints, &ai)) !=3D 0) {
<=
/a>        fprintf(stderr, "selectserver: %s\n", gai_strerror(rv));
<=
/a>        exit(1);
<=
/a>    }
<=
/a>    
<=
/a>    for(p =3D ai; p !=3D NULL; p =3D p->ai_=
next) {
<=
/a>        listener =3D socket(p->ai_family, p->ai_socktype, p->ai=
_protocol);
<=
/a>        if (listener < 0=
) { 
<=
/a>            continue;
<=
/a>        }
<=
/a>        
<=
/a>        // lose the pesky "address already in use" er=
ror message
<=
/a>        setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
<=
/a>
<=
/a>        if (bind(listener, p->ai_addr, p-&g=
t;ai_addrlen) < 0) {
<=
/a>            close(listener);
<=
/a>            continue;
<=
/a>        }
<=
/a>
<=
/a>        break;
<=
/a>    }
<=
/a>
<=
/a>    // if we got here, it means we didn't get bound
<=
/a>    if (p =3D=3D NULL) {
<=
/a>        fprintf(stderr, "selectserver: failed to bind=
\n");
<=
/a>        exit(2);
<=
/a>    }
<=
/a>
<=
/a>    freeaddrinfo(ai); // all done with this
<=
/a>
<=
/a>    // listen
<=
/a>    if (listen(listener, 10=
) =3D=3D -1) {
<=
/a>        perror("listen");
<=
/a>        exit(3);
<=
/a>    }
<=
/a>
<=
/a>    // add the listener to the master set
<=
/a>    FD_SET(listener, &master);
<=
/a>
<=
/a>    // keep track of the biggest file descriptor
<=
/a>    fdmax =3D listener; // so far, it's this one
<=
/a>
<=
/a>    // main loop
<=
/a>    for(;;) {
        read_fds =3D master; // copy it
        if (select(fdmax+=
1, &read_fds, NULL, NULL, NULL) =3D=3D -1) {
            perror("select");
            exit(4);
        }

        // run through the existing connections loo=
king for data to read
        for(i =3D 0; i <=3D fdmax; i++) {
            if (FD_ISSET(i, &read_fds)) =
{ // we got one!!
                if (i =3D=3D listener) {
                    // handle new connections
                    addrlen =3D sizeof remot=
eaddr;
                    newfd =3D accept(listener,
                        (struct sockaddr *)&=
amp;remoteaddr,
                        &addrlen);

                    if (newfd =3D=3D -1) {
                        perror("accept");
                    } else {
                        FD_SET(newfd, &master); // add to master set
                        if (newfd > fdmax=
) {    // keep track of the max
                            fdmax =3D newfd;
                        }
                        printf("selectserver: new c=
onnection from %s on "
                            "socket %d\n",
                            inet_ntop(remoteaddr.ss_family,
                                get_in_addr((struct=
 sockaddr*)&remoteaddr),
                                remoteIP, INET6_ADDRSTRLEN),
                            newfd);
                    }
                } else {
                    // handle data from a client
                    if ((nbytes =3D recv(i, =
buf, sizeof buf, 0)) &l=
t;=3D 0) {
                        // got error or connection =
closed by client
                        if (nbytes =3D=3D 0) {
                            // connection closed
                            printf("selectserver: s=
ocket %d hung up\n", i);
                        } else {
                            perror("recv");<=
/span>
                        }
                        close(i); // bye!
                        FD_CLR(i, &master); // =
remove from master set
                    } else {
                        // we got some data from a =
client
                        for(j =3D 0; j <=3D fdmax; j++) {
                            // send to everyone!
                            if (FD_ISSET(j, =
&master)) {
                                // except the liste=
ner and ourselves
                                if (j !=3D l=
istener && j !=3D i) {
                                    if (send=
(j, buf, nbytes, 0) =3D=3D -1<=
/span>) {
                                        perror("sen=
d");
                                    }
                                }
                            }
                        }
                    }
                } // END<=
/span> handle data from client
            } // END got new incoming connection
        } // END looping through file descriptors
    } // END for(;;)--and you thought it would never end!
    
    return 0;
}

Notice I have two file descriptor sets in the code: master = and read_fds. The first, master, holds all the so= cket descriptors that are currently connected, as well as the socket descri= ptor that is listening for new connections.

The reason I have the master set is that select() actually changes the set you pass into it to reflect which soc= kets are ready to read. Since I have to keep track of the connections from = one call of select() to the next, I must store these safely aw= ay somewhere. At the last minute, I copy the master into the <= code>read_fds, and then call select().

But doesn=E2=80=99t this mean that every time I get a new connection, I = have to add it to the master set? Yup! And every time a connec= tion closes, I have to remove it from the master set? Yes, it = does.

Notice I check to see when the listener socket is ready to = read. When it is, it means I have a new connection pending, and I acc= ept() it and add it to the master set. Similarly, when = a client connection is ready to read, and recv() returns 0, I know the client has closed the connection, and I must remove i= t from the master set.

If the client recv() returns non-zero, though, I know some = data has been received. So I get it, and then go through the master list and send that data to all the rest of the connected clients.

And that, my friends, is a less-than-simple overview of the almighty select() function.

Quick note to all you Linux fans out there: sometimes, in rare circumsta= nces, Linux=E2=80=99s select() can return =E2=80=9Cready-to-re= ad=E2=80=9D and then not actually be ready to read! This means it will bloc= k on the read() after the select() says it won=E2= =80=99t! Why you little=E2=80=94! Anyway, the workaround solution is to set= the O_NONBLOCK flag on the receiving socket so it errors wit= h EWOULDBLOCK (which you can just safely ignore if it occurs).= See the fcntl(= ) reference page for more info on setting a socket to non-blocki= ng.

In addition, here is a bonus afterthought: there is another function cal= led poll() which behaves much the same way select() does, but with a different system for managing the file descriptor sets= . Check it out!

7.4 Handling Partial send()s

Remember back in the section about send(), above, when I said that sen= d() might not send all the bytes you asked it to? That is, you want = it to send 512 bytes, but it returns 412. What happened to the remaining 10= 0 bytes?

Well, they=E2=80=99re still in your little buffer waiting to be sent out= . Due to circumstances beyond your control, the kernel decided not to send = all the data out in one chunk, and now, my friend, it=E2=80=99s up to you t= o get the data out there.

You could write a function like this to do it, too:

In this example, s is the socket you want to send the data = to, buf is the buffer containing the data, and len is a pointer to an int containing the number of bytes in the= buffer.

The function returns -1 on error (and errno is= still set from the call to send()). Also, the number of bytes= actually sent is returned in len. This will be the same numbe= r of bytes you asked it to send, unless there was an error. sendall()= will do it=E2=80=99s best, huffing and puffing, to send the data ou= t, but if there=E2=80=99s an error, it gets back to you right away.

For completeness, here=E2=80=99s a sample call to the function:

What happens on the receiver=E2=80=99s end when part of a packet arrives= ? If the packets are variable length, how does the receiver know when one p= acket ends and another begins? Yes, real-world scenarios are a royal pain i= n the donkeys. You probably have to encapsulate (remember that f= rom the data encapsul= ation section way back there at the beginning?) Read on for details!

7.5 Serialization=E2=80=94How to Pack Data

It=E2=80=99s easy enough to send text data across the network, you=E2= =80=99re finding, but what happens if you want to send some =E2=80=9Cbinary= =E2=80=9D data like ints or floats? It turns out = you have a few options.

  1. Convert the number into text with a function like sprintf(), then send the text. The receiver will parse the text back into a numb= er using a function like strtol().

  2. Just send the data raw, passing a pointer to the data to send(= ).

  3. Encode the number into a portable binary form. The receiver will dec= ode it.

Sneak preview! Tonight only!

[Curtain raises]

Beej says, =E2=80=9CI prefer Method Three, above!=E2=80=9D

[THE END]

(Before I begin this section in earnest, I should tell you that there ar= e libraries out there for doing this, and rolling your own and remaining po= rtable and error-free is quite a challenge. So hunt around and do your home= work before deciding to implement this stuff yourself. I include the inform= ation here for those curious about how things like this work.)

Actually all the methods, above, have their drawbacks and advantages, bu= t, like I said, in general, I prefer the third method. First, though, let= =E2=80=99s talk about some of the drawbacks and advantages to the other two= .

The first method, encoding the numbers as text before sending, has the a= dvantage that you can easily print and read the data that=E2=80=99s coming = over the wire. Sometimes a human-readable protocol is excellent to use in a= non-bandwidth-intensive situation, such as with Internet Relay Chat (IRC)33. However, it has the disadvant= age that it is slow to convert, and the results almost always take up more = space than the original number!

Method two: passing the raw data. This one is quite easy (but dangerous!= ): just take a pointer to the data to send, and call send with it.

    double d =3D 3490.15926535;
    
    send(s, &d, sizeof d, 0);  /* DANGER--non-portable! */

The receiver gets it like this:

    double d;
    
    recv(s, &d, sizeof d, 0);  /* DANGER--non-portable! */

Fast, simple=E2=80=94what=E2=80=99s not to like? Well, it turns out that= not all architectures represent a double (or int= for that matter) with the same bit representation or even the same byte or= dering! The code is decidedly non-portable. (Hey=E2=80=94maybe you don=E2= =80=99t need portability, in which case this is nice and fast.)

When packing integer types, we=E2=80=99ve already seen how the ht= ons()-class of functions can help keep things portable by transformi= ng the numbers into Network Byte Order, and how that=E2=80=99s the Right T= hing to do. Unfortunately, there are no similar functions for float types. Is all hope lost?

Fear not! (Were you afraid there for a second? No? Not even a little bit= ?) There is something we can do: we can pack (or =E2=80=9Cmarshal=E2=80=9D,= or =E2=80=9Cserialize=E2=80=9D, or one of a thousand million other names) = the data into a known binary format that the receiver can unpack on the rem= ote side.

What do I mean by =E2=80=9Cknown binary format=E2=80=9D? Well, we=E2=80= =99ve already seen the htons() example, right? It changes (or = =E2=80=9Cencodes=E2=80=9D, if you want to think of it that way) a number fr= om whatever the host format is into Network Byte Order. To reverse (unencod= e) the number, the receiver calls ntohs().

But didn=E2=80=99t I just get finished saying there wasn=E2=80=99t any s= uch function for other non-integer types? Yes. I did. And since there=E2=80= =99s no standard way in C to do this, it=E2=80=99s a bit of a pickle (that = a gratuitous pun there for you Python fans).

The thing to do is to pack the data into a known format and send that ov= er the wire for decoding. For example, to pack floats, here=E2= =80=99s something q= uick and dirty with plenty of room for improvement34:

The above code is sort of a naive implementation that stores a flo= at in a 32-bit number. The high bit (31) is used to store the sign o= f the number (=E2=80=9C1=E2=80=9D means negative), and the next seven bits = (30-16) are used to store the whole number portion of the float. Finally, the remaining bits (15-0) are used to store the fractional port= ion of the number.

Usage is fairly straightforward:

On the plus side, it=E2=80=99s small, simple, and fast. On the minus sid= e, it=E2=80=99s not an efficient use of space and the range is severely res= tricted=E2=80=94try storing a number greater-than 32767 in there and it won= =E2=80=99t be very happy! You can also see in the above example that the la= st couple decimal places are not correctly preserved.

What can we do instead? Well, The Standard for storing floating= point numbers is known as IEEE-75435. Most c= omputers use this format internally for doing floating point math, so in th= ose cases, strictly speaking, conversion wouldn=E2=80=99t need to be done. = But if you want your source code to be portable, that=E2=80=99s an assumpti= on you can=E2=80=99t necessarily make. (On the other hand, if you want thin= gs to be fast, you should optimize this out on platforms that don=E2=80=99t= need to do it! That=E2=80=99s what htons() and its ilk do.)

Here=E2=80=99= s some code that encodes floats and doubles into IEEE-754 format36. (Mostly=E2=80=94it doesn=E2= =80=99t encode NaN or Infinity, but it could be modified to do that.)

#define pa=
ck754_32(f) (pack754((f), 32, 8))
#define pack754_64(f) (pack754((f), 64, 11))
#define unpack754_32(i) (unpack754((i), 32, 8))<=
/span>
#define unpack754_64(i) (unpack754((i), 64, 11))=


uint64_t pack754(long =
double f, unsigned bits=
, unsigned expbits)
{
    long double fnorm;=

    int shift;
<=
/a>    long long sign, =
exp, significand;
<=
/a>    unsigned significandbits =3D bits - expbit=
s - 1; // -1 for sign bit
<=
/a>
<=
/a>    if (f =3D=3D 0.0=
) return 0; // get this special case out of the way
<=
/a>
<=
/a>    // check sign and begin normalization
<=
/a>    if (f < 0) { =
sign =3D 1; fnorm =3D -f; }
<=
/a>    else { sign =3D 0; fnorm =3D f; }
<=
/a>
<=
/a>    // get the normalized form of f and track the exp=
onent
<=
/a>    shift =3D 0;
<=
/a>    while(fnorm >=3D 2.0=
) { fnorm /=3D 2.0; shift++; }
<=
/a>    while(fnorm < 1.0) { fnorm *=3D 2.0; shift--; }
<=
/a>    fnorm =3D fnorm - 1.0;
<=
/a>
<=
/a>    // calculate the binary form (non-float) of the s=
ignificand data
<=
/a>    significand =3D fnorm * ((1LL<<significandbits) + 0.5f);
<=
/a>
<=
/a>    // get the biased exponent
<=
/a>    exp =3D shift + ((1<<(expbits-1)) - 1); =
// shift + bias
<=
/a>
<=
/a>    // return the final answer
<=
/a>    return (sign<<(bits-1)) | (exp<<(bits-expbits-1)) | s=
ignificand;
<=
/a>}
<=
/a>
<=
/a>long double unpack75=
4(uint64_t i, unsigned =
bits, unsigned expbits)
<=
/a>{
<=
/a>    long double resu=
lt;
<=
/a>    long long shift;=

<=
/a>    unsigned bias;
<=
/a>    unsigned significandbits =3D bits - expbit=
s - 1; // -1 for sign bit
<=
/a>
<=
/a>    if (i =3D=3D 0) =
return 0.0;
<=
/a>
<=
/a>    // pull the significand
<=
/a>    result =3D (i&((1LL=
<<significandbits)-1)); // mask
<=
/a>    result /=3D (1LL=
<<significandbits); // convert back to float
<=
/a>    result +=3D 1.0f=
; // add the one back on
<=
/a>
<=
/a>    // deal with the exponent
<=
/a>    bias =3D (1<<(expbits-1)) - 1;
<=
/a>    shift =3D ((i>>significandbits)&((1LL<<expbits)-1=
)) - bias;
<=
/a>    while(shift > 0) { result *=3D 2.0; shift--; }
<=
/a>    while(shift < 0) { result /=3D 2.0; shift++; }
<=
/a>
<=
/a>    // sign it
<=
/a>    result *=3D (i>>(bits-1))&1? -1.0: 1=
.0;
<=
/a>
<=
/a>    return result;
<=
/a>}

I put some handy macros up there at the top for packing and unpacking 32= -bit (probably a float) and 64-bit (probably a double) numbers, but the pack754() function could be called dire= ctly and told to encode bits-worth of data (expbits of which are reserved for the normalized number=E2=80=99s exponent).

Here=E2=80=99s sample usage:

The above code produces this output:

    float before : 3.1415925
    float encoded: 0x40490FDA
    float after  : 3.1415925
   =20
    double before : 3.14159265358979311600
    double encoded: 0x400921FB54442D18
    double after  : 3.14159265358979311600

Another question you might have is how do you pack structs?= Unfortunately for you, the compiler is free to put padding all over the pl= ace in a struct, and that means you can=E2=80=99t portably sen= d the whole thing over the wire in one chunk. (Aren=E2=80=99t you getting s= ick of hearing =E2=80=9Ccan=E2=80=99t do this=E2=80=9D, =E2=80=9Ccan=E2=80= =99t do that=E2=80=9D? Sorry! To quote a friend, =E2=80=9CWhenever anything= goes wrong, I always blame Microsoft.=E2=80=9D This one might not be Micro= soft=E2=80=99s fault, admittedly, but my friend=E2=80=99s statement is comp= letely true.)

Back to it: the best way to send the struct over the wire i= s to pack each field independently and then unpack them into the stru= ct when they arrive on the other side.

That=E2=80=99s a lot of work, is what you=E2=80=99re thinking. Yes, it i= s. One thing you can do is write a helper function to help pack the data fo= r you. It=E2=80=99ll be fun! Really!

In the book The Practice = of Programming37 = by Kernighan and Pike, they implement printf()-like functions = called pack() and unpack() that do exactly this. = I=E2=80=99d link to them, but apparently those functions aren=E2=80=99t onl= ine with the rest of the source from the book.

(The Practice of Programming is an excellent read. Zeus saves a kitten e= very time I recommend it.)

At this point, I=E2=80=99m going to drop a pointer to a Protocol Buffers implementation in C38 which I=E2=80=99ve ne= ver used, but looks completely respectable. Python and Perl programmers wil= l want to check out their language=E2=80=99s pack() and = unpack() functions for accomplishing the same thing. And Java has a = big-ol=E2=80=99 Serializable interface that can be used in a similar way.

But if you want to write your own packing utility in C, K&P=E2=80=99= s trick is to use variable argument lists to make printf()-lik= e functions to build the packets. Here=E2=80=99s a version I cooked up39 on my own based on that which hopefully = will be enough to give you an idea of how such a thing can work.

(This code references the pack754() functions, above. The <= code>packi*() functions operate like the familiar htons() family, except they pack into a char array instead of anoth= er integer.)

#include <=
/span><stdio.h>
#include <ctype.h>
#include <stdarg.h>
#include <string.h>

/*
** packi16() -- store a 16-bit int into a char buffer (=
like htons())
*/ 
void packi16(unsigned =
char *buf, unsigned int i)
<=
/a>{
<=
/a>    *buf++ =3D i>>8; *buf++ =3D i;
<=
/a>}
<=
/a>
<=
/a>/*
<=
/a>** packi32() -- store a 32-bit int into a char buffer=
 (like htonl())
<=
/a>*/ 
<=
/a>void packi32(unsigned char *buf, unsigned <=
span class=3D"dt">long int i)
<=
/a>{
<=
/a>    *buf++ =3D i>>24; *buf++ =3D i>&g=
t;16;
<=
/a>    *buf++ =3D i>>8;  *buf++ =3D i;
<=
/a>}
<=
/a>
<=
/a>/*
<=
/a>** packi64() -- store a 64-bit int into a char buffer=
 (like htonl())
<=
/a>*/ 
<=
/a>void packi64(unsigned char *buf, unsigned <=
span class=3D"dt">long long int i)
<=
/a>{
<=
/a>    *buf++ =3D i>>56; *buf++ =3D i>&g=
t;48;
<=
/a>    *buf++ =3D i>>40; *buf++ =3D i>&g=
t;32;
<=
/a>    *buf++ =3D i>>24; *buf++ =3D i>&g=
t;16;
<=
/a>    *buf++ =3D i>>8;  *buf++ =3D i;
<=
/a>}
<=
/a>
<=
/a>/*
<=
/a>** unpacki16() -- unpack a 16-bit int from a char buf=
fer (like ntohs())
<=
/a>*/ 
<=
/a>int unpacki16(unsigned char *buf)
<=
/a>{
<=
/a>    unsigned int i2 =
=3D ((unsigned int)buf[=
0]<<8) | buf[1];
<=
/a>    int i;
<=
/a>
<=
/a>    // change unsigned numbers to signed
<=
/a>    if (i2 <=3D 0x7fffu) { i =3D i2; }
<=
/a>    else { i =3D -1 =
- (unsigned int)(0xffffu - i2); }
<=
/a>
<=
/a>    return i;
<=
/a>}
<=
/a>
<=
/a>/*
<=
/a>** unpacku16() -- unpack a 16-bit unsigned from a cha=
r buffer (like ntohs())
<=
/a>*/ 
<=
/a>unsigned int unpacku=
16(unsigned char *buf)<=
/span>
<=
/a>{
<=
/a>    return ((unsigned int)buf[0]<<8) | buf[1];
<=
/a>}
<=
/a>
<=
/a>/*
<=
/a>** unpacki32() -- unpack a 32-bit int from a char buf=
fer (like ntohl())
<=
/a>*/ 
<=
/a>long int unpacki32(<=
span class=3D"dt">unsigned char *buf)
<=
/a>{
<=
/a>    unsigned long int i2 =3D ((unsigned long int)buf[0]<<24) |
<=
/a>                           ((unsigned long int)buf[1]<<16) |
<=
/a>                           ((unsigned long int)buf[2]<<8)  |
<=
/a>                           buf[3];
<=
/a>    long int i;
<=
/a>
<=
/a>    // change unsigned numbers to signed
<=
/a>    if (i2 <=3D 0x7fffff=
ffu) { i =3D i2; }
<=
/a>    else { i =3D -1 =
- (long int)(0xffffffffu - i2); }
<=
/a>
<=
/a>    return i;
<=
/a>}
<=
/a>
<=
/a>/*
<=
/a>** unpacku32() -- unpack a 32-bit unsigned from a cha=
r buffer (like ntohl())
<=
/a>*/ 
<=
/a>unsigned long int unpacku32(unsigned char *buf)
<=
/a>{
<=
/a>    return ((unsigned long int)buf[0]<<24) |
<=
/a>           ((unsigned long<=
/span> int)buf[1]<&l=
t;16) |
<=
/a>           ((unsigned long<=
/span> int)buf[2]<&l=
t;8)  |
<=
/a>           buf[3];
<=
/a>}
<=
/a>
<=
/a>/*
<=
/a>** unpacki64() -- unpack a 64-bit int from a char buf=
fer (like ntohl())
<=
/a>*/ 
<=
/a>long long int unpacki64(unsigned char *buf)
<=
/a>{
<=
/a>    unsigned long long int i2 =3D ((unsigned long long int)buf[0]<<56) |
<=
/a>                                ((unsigned long long int)buf[1]<<48=
) |
<=
/a>                                ((unsigned long long int)buf[2]<<40=
) |
<=
/a>                                ((unsigned long long int)buf[3]<<32=
) |
<=
/a>                                ((unsigned long long int)buf[4]<<24=
) |
<=
/a>                                ((unsigned long long int)buf[5]<<16=
) |
<=
/a>                                ((unsigned long long int)buf[6]<<8<=
/span>)  |
<=
/a>                                buf[7];
<=
/a>    long long int i;

    // change unsigned numbers to signed
    if (i2 <=3D 0x7fff=
ffffffffffffu) { i =3D i2; }
    else { i =3D -1 -(long long int)(0xffffffffffffffffu - i2); }

    return i;
}

/*
** unpacku64() -- unpack a 64-bit unsigned from a c=
har buffer (like ntohl())
*/ 
unsigned long long int unpacku64(unsigned char *buf)
{
    return ((unsigned long long int)buf[0]<<56) |
           ((unsigned lon=
g long int)buf[<=
span class=3D"dv">1]<<48) |
           ((unsigned lon=
g long int)buf[<=
span class=3D"dv">2]<<40) |
           ((unsigned lon=
g long int)buf[<=
span class=3D"dv">3]<<32) |
           ((unsigned lon=
g long int)buf[<=
span class=3D"dv">4]<<24) |
           ((unsigned lon=
g long int)buf[<=
span class=3D"dv">5]<<16) |
           ((unsigned lon=
g long int)buf[<=
span class=3D"dv">6]<<8)  |
           buf[7];
}

/*
** pack() -- store data dictated by the format stri=
ng in the buffer
**
**   bits |signed   unsigned   float   string
**   -----+----------------------------------
**      8 |   c        C         
**     16 |   h        H         f
**     32 |   l        L         d
**     64 |   q        Q         g
**      - |                               s<=
/span>
**
**  (16-bit unsigned length is automatically prepen=
ded to strings)
*/ 

unsigned int pack(=
unsigned char *buf, char *format, ...)
{
    va_list ap;

    signed char c;=
              // 8-bit
    unsigned char =
C;

    int h;                      // 16-bit
    unsigned int H=
;

    long int l;   =
              // 32-bit
    unsigned long =
int L;

    long long int q;            // 64-bit=

    unsigned long =
long int Q;

    float f;                    // floats
    double d;
    long double g;=

    unsigned long =
long int fhold;

    char *s;                    // strings
    unsigned int l=
en;

    unsigned int s=
ize =3D 0;

    va_start(ap, format);

    for(; *format !=3D '\=
0'; format++) {
        switch(*format) {
        case 'c': =
// 8-bit
            size +=3D 1;
            c =3D (signed char)va_arg(ap, int); =
// promoted
            *buf++ =3D c;
            break;

        case 'C': =
// 8-bit unsigned
            size +=3D 1;
            C =3D (unsigned char)va_arg(ap, unsigned int); // promoted
            *buf++ =3D C;
            break;

        case 'h': =
// 16-bit
            size +=3D 2;
            h =3D va_arg(ap, int);
            packi16(buf, h);
            buf +=3D 2;
            break;

        case 'H': =
// 16-bit unsigned
            size +=3D 2;
            H =3D va_arg(ap, unsigned int);
            packi16(buf, H);
            buf +=3D 2;
            break;

        case 'l': =
// 32-bit
            size +=3D 4;
            l =3D va_arg(ap, long int);
            packi32(buf, l);
            buf +=3D 4;
            break;

        case 'L': =
// 32-bit unsigned
            size +=3D 4;
            L =3D va_arg(ap, unsigned long int);
            packi32(buf, L);
            buf +=3D 4;
            break;

        case 'q': =
// 64-bit
            size +=3D 8;
            q =3D va_arg(ap, long long int);
            packi64(buf, q);
            buf +=3D 8;
            break;

        case 'Q': =
// 64-bit unsigned
            size +=3D 8;
            Q =3D va_arg(ap, unsigned long long =
int);
            packi64(buf, Q);
            buf +=3D 8;
            break;

        case 'f': =
// float-16
            size +=3D 2;
            f =3D (float)va_arg(ap, double); // promoted
            fhold =3D pack754_16(f); // convert to =
IEEE 754
            packi16(buf, fhold);
            buf +=3D 2;
            break;

        case 'd': =
// float-32
            size +=3D 4;
            d =3D va_arg(ap, double);
            fhold =3D pack754_32(d); // convert to =
IEEE 754
            packi32(buf, fhold);
            buf +=3D 4;
            break;

        case 'g': =
// float-64
            size +=3D 8;
            g =3D va_arg(ap, long double);
            fhold =3D pack754_64(g); // convert to =
IEEE 754
            packi64(buf, fhold);
            buf +=3D 8;
            break;

        case 's': =
// string
            s =3D va_arg(ap, char*);
            len =3D strlen(s);
            size +=3D len + 2;
            packi16(buf, len);
            buf +=3D 2;
            memcpy(buf, s, len);
            buf +=3D len;
            break;
        }
    }

    va_end(ap);

    return size;
}

/*
** unpack() -- unpack data dictated by the format s=
tring into the buffer
**
**   bits |signed   unsigned   float   string
**   -----+----------------------------------
**      8 |   c        C         
**     16 |   h        H         f
**     32 |   l        L         d
**     64 |   q        Q         g
**      - |                               s<=
/span>
**
**  (string is extracted based on its stored length=
, but 's' can be
**  prepended with a max length)
*/
void unpack(unsigned char *buf, char *for=
mat, ...)
{
    va_list ap;

    signed char *c=
;              // 8-bit
    unsigned char =
*C;

    int *h;                      // 16-bit
    unsigned int *=
H;

    long int *l;  =
               // 32-bit
    unsigned long =
int *L;

    long long int *q;            // 64-bit
    unsigned long =
long int *Q;

    float *f;                    // floats
    double *d;
    long double *g=
;
    unsigned long =
long int fhold;

    char *s;
    unsigned int l=
en, maxstrlen=3D0, count;

    va_start(ap, format);

    for(; *format !=3D '\=
0'; format++) {
        switch(*format) {
        case 'c': =
// 8-bit
            c =3D va_arg(ap, signed char*);
            if (*buf <=3D 0x7f) { *c =3D *buf;} // re-sign
            else { *c =3D -1 - (unsigned char)(0xffu - *buf); }<=
/span>
            buf++;
            break;

        case 'C': =
// 8-bit unsigned
            C =3D va_arg(ap, unsigned char*);
            *C =3D *buf++;
            break;

        case 'h': =
// 16-bit
            h =3D va_arg(ap, int*);
            *h =3D unpacki16(buf);
            buf +=3D 2;
            break;

        case 'H': =
// 16-bit unsigned
            H =3D va_arg(ap, unsigned int*);
            *H =3D unpacku16(buf);
            buf +=3D 2;
            break;

        case 'l': =
// 32-bit
            l =3D va_arg(ap, long int*);
            *l =3D unpacki32(buf);
            buf +=3D 4;
            break;

        case 'L': =
// 32-bit unsigned
            L =3D va_arg(ap, unsigned long int*);
            *L =3D unpacku32(buf);
            buf +=3D 4;
            break;

        case 'q': =
// 64-bit
            q =3D va_arg(ap, long long int*);
            *q =3D unpacki64(buf);
            buf +=3D 8;
            break;

        case 'Q': =
// 64-bit unsigned
            Q =3D va_arg(ap, unsigned long long =
int*);
            *Q =3D unpacku64(buf);
            buf +=3D 8;
            break;

        case 'f': =
// float
            f =3D va_arg(ap, float*);
            fhold =3D unpacku16(buf);
            *f =3D unpack754_16(fhold);
            buf +=3D 2;
            break;

        case 'd': =
// float-32
            d =3D va_arg(ap, double*);
            fhold =3D unpacku32(buf);
            *d =3D unpack754_32(fhold);
            buf +=3D 4;
            break;

        case 'g': =
// float-64
            g =3D va_arg(ap, long double*);
            fhold =3D unpacku64(buf);
            *g =3D unpack754_64(fhold);
            buf +=3D 8;
            break;

        case 's': =
// string
            s =3D va_arg(ap, char*);
            len =3D unpacku16(buf);
            buf +=3D 2;
            if (maxstrlen > 0 && len >=3D maxstrlen) count =3D maxstrlen - 1;
            else count =3D len;
            memcpy(s, buf, count);
            s[count] =3D '\0';
            buf +=3D len;
            break;

        default:
            if (isdigit(*format)) { // track max str len
                maxstrlen =3D maxstrlen * 10=
 + (*format-'0');
            }
        }

        if (!isdigit(*format)) maxstrlen =3D=
 0;
    }

    va_end(ap);
}

And here is a d= emonstration program40= of the above code that packs some data into buf and then unpa= cks it into variables. Note that when calling unpack() with a = string argument (format specifier =E2=80=9Cs=E2=80=9D), it=E2= =80=99s wise to put a maximum length count in front of it to prevent a buff= er overrun, e.g. =E2=80=9C96s=E2=80=9D. Be wary when unpa= cking data you get over the network=E2=80=94a malicious user might send bad= ly-constructed packets in an effort to attack your system!

Whether you roll your own code or use someone else=E2=80=99s, it=E2=80= =99s a good idea to have a general set of data packing routines for the sak= e of keeping bugs in check, rather than packing each bit by hand each time.=

When packing the data, what=E2=80=99s a good format to use? Excellent qu= estion. Fortunately, RFC 4= 50641, the External Da= ta Representation Standard, already defines binary formats for a bunch of d= ifferent types, like floating point types, integer types, arrays, raw data,= etc. I suggest conforming to that if you=E2=80=99re going to roll the data= yourself. But you=E2=80=99re not obligated to. The Packet Police are not r= ight outside your door. At least, I don=E2=80=99t think they are.<= /p>

In any case, encoding the data somehow or another before you send it is = the right way of doing things!

7.6 Son of Data Encapsulation

What does it really mean to encapsulate data, anyway? In the simplest ca= se, it means you=E2=80=99ll stick a header on there with either some identi= fying information or a packet length, or both.

What should your header look like? Well, it=E2=80=99s just some binary d= ata that represents whatever you feel is necessary to complete your project= .

Wow. That=E2=80=99s vague.

Okay. For instance, let=E2=80=99s say you have a multi-user chat program= that uses SOCK_STREAMs. When a user types (=E2=80=9Csays=E2= =80=9D) something, two pieces of information need to be transmitted to the = server: what was said and who said it.

So far so good? =E2=80=9CWhat=E2=80=99s the problem?=E2=80=9D you=E2=80= =99re asking.

The problem is that the messages can be of varying lengths. One person n= amed =E2=80=9Ctom=E2=80=9D might say, =E2=80=9CHi=E2=80=9D, and another per= son named =E2=80=9CBenjamin=E2=80=9D might say, =E2=80=9CHey guys what is u= p?=E2=80=9D

So you send() all this stuff to the clients as it comes in.= Your outgoing data stream looks like this:

    t o m H i B e n j a m i n H e y g u y s w h a t i s u p ?

And so on. How does the client know when one message starts and another = stops? You could, if you wanted, make all messages the same length and just= call the sendall() we implemented, above. But that wastes bandwidth! We don=E2= =80=99t want to send() 1024 bytes just so =E2=80=9Ctom=E2=80= =9D can say =E2=80=9CHi=E2=80=9D.

So we encapsulate the data in a tiny header and packet structur= e. Both the client and server know how to pack and unpack (sometimes referr= ed to as =E2=80=9Cmarshal=E2=80=9D and =E2=80=9Cunmarshal=E2=80=9D) this da= ta. Don=E2=80=99t look now, but we=E2=80=99re starting to define a prot= ocol that describes how a client and server communicate!

In this case, let=E2=80=99s assume the user name is a fixed length of 8 = characters, padded with '\0'. And then let=E2=80=99s assume th= e data is variable length, up to a maximum of 128 characters. Let=E2=80=99s= have a look a sample packet structure that we might use in this situation:=

  1. len (1 byte, unsigned)=E2=80=94The total length of the = packet, counting the 8-byte user name and chat data.

  2. name (8 bytes)=E2=80=94The user=E2=80=99s name, NUL-pad= ded if necessary.

  3. chatdata (n-bytes)=E2=80=94The data itself, no= more than 128 bytes. The length of the packet should be calculated as the = length of this data plus 8 (the length of the name field, above).

Why did I choose the 8-byte and 128-byte limits for the fields? I pulled= them out of the air, assuming they=E2=80=99d be long enough. Maybe, though= , 8 bytes is too restrictive for your needs, and you can have a 30-byte nam= e field, or whatever. The choice is up to you.

Using the above packet definition, the first packet would consist of the= following information (in hex and ASCII):

       0A     74 6F 6D 00 00 00 00 00      48 69
    (length)  T  o  m    (padding)         H  i

And the second is similar:

       18     42 65 6E 6A 61 6D 69 6E      48 65 79 20 67 75 79 =
73 20 77 ...
    (length)  B  e  n  j  a  m  i  n       H  e  y     g  u  y  s     w  ..=
.

(The length is stored in Network Byte Order, of course. In this case, it= =E2=80=99s only one byte so it doesn=E2=80=99t matter, but generally speaki= ng you=E2=80=99ll want all your binary integers to be stored in Network Byt= e Order in your packets.)

When you=E2=80=99re sending this data, you should be safe and use a comm= and similar to s= endall(), above, so you know all the data is sent, even if it ta= kes multiple calls to send() to get it all out.

Likewise, when you=E2=80=99re receiving this data, you need to do a bit = of extra work. To be safe, you should assume that you might receive a parti= al packet (like maybe we receive =E2=80=9C18 42 65 6E 6A=E2=80= =9D from Benjamin, above, but that=E2=80=99s all we get in this call to recv()). We need to call recv() over and over again = until the packet is completely received.

But how? Well, we know the number of bytes we need to receive in total f= or the packet to be complete, since that number is tacked on the front of t= he packet. We also know the maximum packet size is 1+8+128, or 137 bytes (b= ecause that=E2=80=99s how we defined the packet).

There are actually a couple things you can do here. Since you know every= packet starts off with a length, you can call recv() just to = get the packet length. Then once you have that, you can call it again speci= fying exactly the remaining length of the packet (possibly repeatedly to ge= t all the data) until you have the complete packet. The advantage of this m= ethod is that you only need a buffer large enough for one packet, while the= disadvantage is that you need to call recv() at least twice t= o get all the data.

Another option is just to call recv() and say the amount yo= u=E2=80=99re willing to receive is the maximum number of bytes in a packet.= Then whatever you get, stick it onto the back of a buffer, and finally che= ck to see if the packet is complete. Of course, you might get some of the n= ext packet, so you=E2=80=99ll need to have room for that.

What you can do is declare an array big enough for two packets. This is = your work array where you will reconstruct packets as they arrive.

Every time you recv() data, you=E2=80=99ll append it into t= he work buffer and check to see if the packet is complete. That is, the num= ber of bytes in the buffer is greater than or equal to the length specified= in the header (+1, because the length in the header doesn=E2=80=99t includ= e the byte for the length itself). If the number of bytes in the buffer is = less than 1, the packet is not complete, obviously. You have to make a spec= ial case for this, though, since the first byte is garbage and you can=E2= =80=99t rely on it for the correct packet length.

Once the packet is complete, you can do with it what you will. Use it, a= nd remove it from your work buffer.

Whew! Are you juggling that in your head yet? Well, here=E2=80=99s the s= econd of the one-two punch: you might have read past the end of one packet = and onto the next in a single recv() call. That is, you have a= work buffer with one complete packet, and an incomplete part of the next p= acket! Bloody heck. (But this is why you made your work buffer large enough= to hold two packets=E2=80=94in case this happened!)

Since you know the length of the first packet from the header, and you= =E2=80=99ve been keeping track of the number of bytes in the work buffer, y= ou can subtract and calculate how many of the bytes in the work buffer belo= ng to the second (incomplete) packet. When you=E2=80=99ve handled the first= one, you can clear it out of the work buffer and move the partial second p= acket down the to front of the buffer so it=E2=80=99s all ready to go for t= he next recv().

(Some of you readers will note that actually moving the partial second p= acket to the beginning of the work buffer takes time, and the program can b= e coded to not require this by using a circular buffer. Unfortunately for t= he rest of you, a discussion on circular buffers is beyond the scope of thi= s article. If you=E2=80=99re still curious, grab a data structures book and= go from there.)

I never said it was easy. Ok, I did say it was easy. And it is; you just= need practice and pretty soon it=E2=80=99ll come to you naturally. By Exc= alibur I swear it!

7.7 Broadcast Packets=E2=80=94Hello, World!

So far, this guide has talked about sending data from one host to one ot= her host. But it is possible, I insist, that you can, with the proper autho= rity, send data to multiple hosts at the same time!

With UDP (only UDP, not TCP) and standard IPv4, this is done through a = mechanism called broadcasting. With IPv6, broadcasting isn=E2=80= =99t supported, and you have to resort to the often superior technique of <= em>multicasting, which, sadly I won=E2=80=99t be discussing at this ti= me. But enough of the starry-eyed future=E2=80=94we=E2=80=99re stuck in the= 32-bit present.

But wait! You can=E2=80=99t just run off and start broadcasting willy-ni= lly; You have to set the socket option SO_BROADCAST before y= ou can send a broadcast packet out on the network. It=E2=80=99s like a one = of those little plastic covers they put over the missile launch switch! Tha= t=E2=80=99s just how much power you hold in your hands!

But seriously, though, there is a danger to using broadcast packets, and= that is: every system that receives a broadcast packet must undo all the o= nion-skin layers of data encapsulation until it finds out what port the dat= a is destined to. And then it hands the data over or discards it. In either= case, it=E2=80=99s a lot of work for each machine that receives the broadc= ast packet, and since it is all of them on the local network, that could be= a lot of machines doing a lot of unnecessary work. When the game Doom firs= t came out, this was a complaint about its network code.

Now, there is more than one way to skin a cat=E2=80=A6 wait a minute. Is= there really more than one way to skin a cat? What kind of expression is t= hat? Uh, and likewise, there is more than one way to send a broadcast packe= t. So, to get to the meat and potatoes of the whole thing: how do you speci= fy the destination address for a broadcast message? There are two common wa= ys:

  1. Send the data to a specific subnet=E2=80=99s broadcast address. This= is the subnet=E2=80=99s network number with all one-bits set for the host = portion of the address. For instance, at home my network is 192.168.1= .0, my netmask is 255.255.255.0, so the last byte of th= e address is my host number (because the first three bytes, according to th= e netmask, are the network number). So my broadcast address is 192.16= 8.1.255. Under Unix, the ifconfig command will actually= give you all this data. (If you=E2=80=99re curious, the bitwise logic to g= et your broadcast address is network_number OR (NOT netm= ask).) You can send this type of broadcast packet to remote networks= as well as your local network, but you run the risk of the packet being dr= opped by the destination=E2=80=99s router. (If they didn=E2=80=99t drop it,= then some random smurf could start flooding their LAN with broadcast traff= ic.)

  2. Send the data to the =E2=80=9Cglobal=E2=80=9D broadcast address. Thi= s is 255.255.255.255, aka INADDR_BROADCAST. Man= y machines will automatically bitwise AND this with your network number to = convert it to a network broadcast address, but some won=E2=80=99t. It varie= s. Routers do not forward this type of broadcast packet off your local netw= ork, ironically enough.

So what happens if you try to send data on the broadcast address without= first setting the SO_BROADCAST socket option? Well, let=E2=80= =99s fire up good old talker and listener and see what happens.

    $ talker 192.168.1.2 foo
    sent 3 bytes to 192.168.1.2
    $ talker 192.168.1.255 foo
    sendto: Permission denied
    $ talker 255.255.255.255 foo
    sendto: Permission denied

Yes, it=E2=80=99s not happy at all=E2=80=A6because we didn=E2=80=99t set= the SO_BROADCAST socket option. Do that, and now you can sendto() anywhere you want!

In fact, that=E2=80=99s the only difference between a UDP appli= cation that can broadcast and one that can=E2=80=99t. So let=E2=80=99s take= the old talker application and add one section that sets the = SO_BROADCAST socket option. We=E2=80=99ll call this program broadcas= ter.c42:

/*<=
/span>
** broadcaster.c -- a datagram "client" like talker.c, =
except
**                  this one can broadcast
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
<=
/a>#include <string.h>
<=
/a>#include <sys/types.h>=
;
<=
/a>#include <sys/socket.h&g=
t;
<=
/a>#include <netinet/in.h&g=
t;
<=
/a>#include <arpa/inet.h>=
;
<=
/a>#include <netdb.h>
<=
/a>
<=
/a>#define SERVERPORT 4950 // =
the port users will be connecting to
<=
/a>
<=
/a>int main(int argc, <=
span class=3D"dt">char *argv[])
<=
/a>{
<=
/a>    int sockfd;
<=
/a>    struct sockaddr_in their_addr; // connector's address information
<=
/a>    struct hostent *he;
<=
/a>    int numbytes;
<=
/a>    int broadcast =3D 1;
<=
/a>    //char broadcast =3D '1'; // if that doesn't work=
, try this
<=
/a>
<=
/a>    if (argc !=3D 3)=
 {
<=
/a>        fprintf(stderr,"usage: broadcaster hostname m=
essage\n");
<=
/a>        exit(1);
<=
/a>    }
<=
/a>
<=
/a>    if ((he=3Dgethostbyname(argv[1])) =3D=3D NULL) {  // get the host info=

<=
/a>        perror("gethostbyname");
<=
/a>        exit(1);
<=
/a>    }
<=
/a>
<=
/a>    if ((sockfd =3D socket(AF_INET, SOCK_DGRAM=
, 0)) =3D=3D -1) {
<=
/a>        perror("socket");
<=
/a>        exit(1);
<=
/a>    }
<=
/a>
<=
/a>    // this call is what allows broadcast packets to =
be sent:
<=
/a>    if (setsockopt(sockfd, SOL_SOCKET, SO_BROA=
DCAST, &broadcast,
<=
/a>        sizeof broadcast) =3D=3D -1) {
<=
/a>        perror("setsockopt (SO_BROADCAST)");
<=
/a>        exit(1);
<=
/a>    }
<=
/a>
<=
/a>    their_addr.sin_family =3D AF_INET;     // host by=
te order
<=
/a>    their_addr.sin_port =3D htons(SERVERPORT); // sho=
rt, network byte order
<=
/a>    their_addr.sin_addr =3D *((struct in_addr =
*)he->h_addr);
<=
/a>    memset(their_addr.sin_zero, '\0', sizeof their_addr.sin_zero);
<=
/a>
<=
/a>    if ((numbytes=3Dsendto(sockfd, argv[2], strlen(argv[2]), 0,
<=
/a>             (struct sockaddr *)&their_add=
r, sizeof their_addr)) =3D=3D -1) {
<=
/a>        perror("sendto");
<=
/a>        exit(1);
<=
/a>    }
<=
/a>
<=
/a>    printf("sent %d bytes to %s\n", numbytes,
<=
/a>        inet_ntoa(their_addr.sin_addr));
<=
/a>
<=
/a>    close(sockfd);
<=
/a>
<=
/a>    return 0;
<=
/a>}

What=E2=80=99s different between this and a =E2=80=9Cnormal=E2=80=9D UDP= client/server situation? Nothing! (With the exception of the client being = allowed to send broadcast packets in this case.) As such, go ahead and run = the old UDP lis= tener program in one window, and broadcaster in ano= ther. You should be now be able to do all those sends that failed, above.

    $ broadcaster 192.168.1.2 foo
    sent 3 bytes to 192.168.1.2
    $ broadcaster 192.168.1.255 foo
    sent 3 bytes to 192.168.1.255
    $ broadcaster 255.255.255.255 foo
    sent 3 bytes to 255.255.255.255

And you should see listener responding that it got the pack= ets. (If listener doesn=E2=80=99t respond, it could be because= it=E2=80=99s bound to an IPv6 address. Try changing the AF_UNSPEC in listener.c to AF_INET to force IPv4.)

Well, that=E2=80=99s kind of exciting. But now fire up listener on another machine next to you on the same network so that you have tw= o copies going, one on each machine, and run broadcaster again= with your broadcast address=E2=80=A6 Hey! Both listeners get = the packet even though you only called sendto() once! Cool!

If the listener gets data you send directly to it, but not = data on the broadcast address, it could be that you have a firewall on you= r local machine that is blocking the packets. (Yes, Pat and Bapper, thank= you for realizing before I did that this is why my sample code wasn=E2=80= =99t working. I told you I=E2=80=99d mention you in the guide, and here you= are. So nyah.)

Again, be careful with broadcast packets. Since every machine on the LAN= will be forced to deal with the packet whether it recvfrom()s= it or not, it can present quite a load to the entire computing network. Th= ey are definitely to be used sparingly and appropriately.

8 Common Questions

Where can I get those header files?

If you don=E2=80=99t have them on your system already, you probably don= =E2=80=99t need them. Check the manual for your particular platform. If you= =E2=80=99re building for Windows, you only need to #include <wins= ock.h>.

What do I do when bind() reports =E2=80=9CAddress = already in use=E2=80=9D?

You have to use setsockopt() with the SO_REUSEADDR<= /code> option on the listening socket. Check out the section on bind() and the section on select()= for an example.

How do I get a list of open sockets on the system?

Use the netstat. Check the man page for full = details, but you should get some good output just typing:

    $ netstat

The only trick is determining which socket is associated with which prog= ram. :-)

How can I view the routing table?

Run the route command (in /sbin on most Linux= es) or the command netstat -r.

How can I run the client and server programs if I only have one = computer? Don=E2=80=99t I need a network to write network programs?

Fortunately for you, virtually all machines implement a loopback networ= k =E2=80=9Cdevice=E2=80=9D that sits in the kernel and pretends to be a net= work card. (This is the interface listed as =E2=80=9Clo=E2=80= =9D in the routing table.)

Pretend you=E2=80=99re logged into a machine named =E2=80=9Cgoat<= /code>=E2=80=9D. Run the client in one window and the server in another. Or= start the server in the background (=E2=80=9Cserver &=E2= =80=9D) and run the client in the same window. The upshot of the loopback d= evice is that you can either client goat or client loca= lhost (since =E2=80=9Clocalhost=E2=80=9D is likely defi= ned in your /etc/hosts file) and you=E2=80=99ll have the clien= t talking to the server without a network!

In short, no changes are necessary to any of the code to make it run on = a single non-networked machine! Huzzah!

How can I tell if the remote side has closed connection?

You can tell because recv() will return 0.

How do I implement a =E2=80=9Cping=E2=80=9D utility? What is I= CMP? Where can I find out more about raw sockets and SOCK_RAW= ?

All your raw sockets questions will be answered in W. Richard Stevens=E2=80=99 UNIX Network Prog= ramming books. Also, look in the ping/ subdirectory in Ste= vens=E2=80=99 UNIX Network Programming source code, available online= 43.

How do I change or shorten the timeout on a call to connec= t()?

Instead of giving you exactly the same answer that W. Richard Stevens wo= uld give you, I=E2=80=99ll just refer you to lib/connect_nonb.c in the UNIX Network Programmi= ng source code44.

The gist of it is that you make a socket descriptor with socket()<= /code>, set it to non= -blocking, call connect(), and if all goes well conn= ect() will return -1 immediately and errno= will be set to EINPROGRESS. Then you call select() with whatever ti= meout you want, passing the socket descriptor in both the read and write se= ts. If it doesn=E2=80=99t timeout, it means the connect() call= completed. At this point, you=E2=80=99ll have to use getsockopt() with the SO_ERROR option to get the return value from the= connect() call, which should be zero if there was no error.

Finally, you=E2=80=99ll probably want to set the socket back to be block= ing again before you start transferring data over it.

Notice that this has the added benefit of allowing your program to do so= mething else while it=E2=80=99s connecting, too. You could, for example, se= t the timeout to something low, like 500 ms, and update an indicator onscre= en each timeout, then call select() again. When you=E2=80=99ve= called select() and timed-out, say, 20 times, you=E2=80=99ll = know it=E2=80=99s time to give up on the connection.

Like I said, check out Stevens=E2=80=99 source for a perfectly excellent= example.

How do I build for Windows?

First, delete Windows and install Linux or BSD. };-). No, a= ctually, just see the = section on building for Windows in the introduction.

How do I build for Solaris/SunOS? I keep getting linker errors w= hen I try to compile!

The linker errors happen because Sun boxes don=E2=80=99t automatically c= ompile in the socket libraries. See the section on building for Solaris/SunOS in the introduc= tion for an example of how to do this.

Why does select() keep falling out on a signal?

Signals tend to cause blocked system calls to return -1 wit= h errno set to EINTR. When you set up a signal ha= ndler with sigaction(), you can set the flag SA_RESTAR= T, which is supposed to restart the system call after it was interru= pted.

Naturally, this doesn=E2=80=99t always work.

My favorite solution to this involves a goto statement. Yo= u know this irritates your professors to no end, so go for it!

Sure, you don=E2=80=99t need to use goto in this c= ase; you can use other structures to control it. But I think the goto= statement is actually cleaner.

How can I implement a timeout on a call to recv()?<= /strong>

Use select()= ! It allows you to specify a timeout parameter for socket descri= ptors that you=E2=80=99re looking to read from. Or, you could wrap the enti= re functionality in a single function, like this:

Notice that recvtimeout() returns -2 in case = of a timeout. Why not return 0? Well, if you recall, a return = value of 0 on a call to recv() means that the rem= ote side closed the connection. So that return value is already spoken for,= and -1 means =E2=80=9Cerror=E2=80=9D, so I chose -2 as my timeout indicator.

How do I encrypt or compress the data before sending it through= the socket?

One easy way to do encryption is to use SSL (secure sockets layer), but= that=E2=80=99s beyond the scope of this guide. (Check out the OpenSSL project45 for more info.)

But assuming you want to plug in or implement your own compressor or en= cryption system, it=E2=80=99s just a matter of thinking of your data as run= ning through a sequence of steps between both ends. Each step changes the d= ata in some way.

  1. server reads data from file (or wherever)
  2. server encrypts/compresses data (you add this part)
  3. server send()s encrypted data

Now the other way around:

  1. client recv()s encrypted data
  2. client decrypts/decompresses data (you add this part)
  3. client writes data to file (or wherever)

If you=E2=80=99re going to compress and encrypt, just remember to compre= ss first. :-)

Just as long as the client properly undoes what the server does, the dat= a will be fine in the end no matter how many intermediate steps you add.

So all you need to do to use my code is to find the place between where = the data is read and the data is sent (using send()) over the = network, and stick some code in there that does the encryption.

What is this =E2=80=9CPF_INET=E2=80=9D I keep seein= g? Is it related to AF_INET?

Yes, yes it is. See = the section on socket() for details.

How can I write a server that accepts shell commands from a clie= nt and executes them?

For simplicity, lets say the client connect()s, send(= )s, and close()s the connection (that is, there are no = subsequent system calls without the client connecting again).

The process the client follows is this:

  1. connect() to server
  2. send("/sbin/ls > /tmp/client.out")
  3. close() the connection

Meanwhile, the server is handling the data and executing it:

  1. accept() the connection from the client
  2. recv(str) the command string
  3. close() the connection
  4. system(str) to run the command

Beware! Having the server execute what the client says is like= giving remote shell access and people can do things to your account when t= hey connect to the server. For instance, in the above example, what if the = client sends =E2=80=9Crm -rf ~=E2=80=9D? It deletes everything= in your account, that=E2=80=99s what!

So you get wise, and you prevent the client from using any except for a = couple utilities that you know are safe, like the foobar utili= ty:

    if (!strncmp(str, "foobar", 6)) {
        sprintf(sysstr, "%s > /tmp/server.out", str);
        system(sysstr);
    } 

But you=E2=80=99re still unsafe, unfortunately: what if the client enter= s =E2=80=9Cfoobar; rm -rf ~=E2=80=9D? The safest thing to do i= s to write a little routine that puts an escape (=E2=80=9C\=E2= =80=9D) character in front of all non-alphanumeric characters (including sp= aces, if appropriate) in the arguments for the command.

As you can see, security is a pretty big issue when the server starts ex= ecuting things the client sends.

I=E2=80=99m sending a slew of data, but when I recv(), it only receives 536 bytes or 1460 bytes at a time. But if I run it on = my local machine, it receives all the data at the same time. What=E2=80=99s= going on?

You=E2=80=99re hitting the MTU=E2=80=94the maximum size the physical me= dium can handle. On the local machine, you=E2=80=99re using the loopback de= vice which can handle 8K or more no problem. But on Ethernet, which can onl= y handle 1500 bytes with a header, you hit that limit. Over a modem, with 5= 76 MTU (again, with header), you hit the even lower limit.

You have to make sure all the data is being sent, first of all. (See the= sendall() function implementation for details.) Once you=E2=80=99re sure of tha= t, then you need to call recv() in a loop until all your data = is read.

Read the section Son of Data Encapsulation for details on receiving complete packet= s of data using multiple calls to recv().

I=E2=80=99m on a Windows box and I don=E2=80=99t have the = fork() system call or any kind of struct sigaction. Wha= t to do?

If they=E2=80=99re anywhere, they=E2=80=99ll be in POSIX libraries that= may have shipped with your compiler. Since I don=E2=80=99t have a Windows = box, I really can=E2=80=99t tell you the answer, but I seem to remember tha= t Microsoft has a POSIX compatibility layer and that=E2=80=99s where = fork() would be. (And maybe even sigaction.)

Search the help that came with VC++ for =E2=80=9Cfork=E2=80=9D or =E2=80= =9CPOSIX=E2=80=9D and see if it gives you any clues.

If that doesn=E2=80=99t work at all, ditch the fork()/sigaction stuff and replace it with the Win32 equivalent: Cr= eateProcess(). I don=E2=80=99t know how to use CreateProcess()= =E2=80=94it takes a bazillion arguments, but it should be covered in= the docs that came with VC++.

I=E2=80=99m behind a firewall=E2=80=94how do I let people outsi= de the firewall know my IP address so they can connect to my machine?

Unfortunately, the purpose of a firewall is to prevent people outside th= e firewall from connecting to machines inside the firewall, so allowing the= m to do so is basically considered a breach of security.

This isn=E2=80=99t to say that all is lost. For one thing, you can still= often connect() through the firewall if it=E2=80=99s doing so= me kind of masquerading or NAT or something like that. Just design your pro= grams so that you=E2=80=99re always the one initiating the connection, and = you=E2=80=99ll be fine.

If that=E2=80=99s not satisfactory, you can ask your sysadmins to poke = a hole in the firewall so that people can connect to you. The firewall can = forward to you either through it=E2=80=99s NAT software, or through a proxy= or something like that.

Be aware that a hole in the firewall is nothing to be taken lightly. You= have to make sure you don=E2=80=99t give bad people access to the internal= network; if you=E2=80=99re a beginner, it=E2=80=99s a lot harder to make s= oftware secure than you might imagine.

Don=E2=80=99t make your sysadmin mad at me. ;-)

How do I write a packet sniffer? How do I put my Ethernet inte= rface into promiscuous mode?

For those not in the know, when a network card is in =E2=80=9Cpromiscuou= s mode=E2=80=9D, it will forward ALL packets to the operating system, not j= ust those that were addressed to this particular machine. (We=E2=80=99re ta= lking Ethernet-layer addresses here, not IP addresses=E2=80=93but since eth= ernet is lower-layer than IP, all IP addresses are effectively forwarded as= well. See the section Low Level Nonsense and Network Theory for more info.)

This is the basis for how a packet sniffer works. It puts the interface = into promiscuous mode, then the OS gets every single packet that goes by on= the wire. You=E2=80=99ll have a socket of some type that you can read this= data from.

Unfortunately, the answer to the question varies depending on the platfo= rm, but if you Google for, for instance, =E2=80=9Cwindows promiscuous ioct= l=E2=80=9D you=E2=80=99ll probably get somewhere. For Linux, there=E2=80=99= s what looks like a useful Stack Overflow thread4= 6, as well.

How can I set a custom timeout value for a TCP or UDP socket?

It depends on your system. You might search the net for SO_RCVTIM= EO and SO_SNDTIMEO (for use with setsockopt()) to see if your system supports such functionality.

The Linux man page suggests using alarm() or setitime= r() as a substitute.

How can I tell which ports are available to use? Is there a list= of =E2=80=9Cofficial=E2=80=9D port numbers?

Usually this isn=E2=80=99t an issue. If you=E2=80=99re writing, say, a w= eb server, then it=E2=80=99s a good idea to use the well-known port 80 for = your software. If you=E2=80=99re writing just your own specialized server, = then choose a port at random (but greater than 1023) and give it a try.

If the port is already in use, you=E2=80=99ll get an =E2=80=9CAddress al= ready in use=E2=80=9D error when you try to bind(). Choose ano= ther port. (It=E2=80=99s a good idea to allow the user of your software to = specify an alternate port either with a config file or a command line switc= h.)

There is a lis= t of official port numbers47 maintained by the Internet Assigned Numbers Authority (IANA). Just b= ecause something (over 1023) is in that list doesn=E2=80=99t mean you can= =E2=80=99t use the port. For instance, Id Software=E2=80=99s DOOM uses the = same port as =E2=80=9Cmdqs=E2=80=9D, whatever that is. All that matters is = that no one else on the same machine is using that port when you w= ant to use it.

9 Man Pages

In the Unix world, there are a lot of manuals. They have little section= s that describe individual functions that you have at your disposal.

Of course, manual would be too much of a thing to type. I m= ean, no one in the Unix world, including myself, likes to type that much. I= ndeed I could go on and on at great length about how much I prefer to be te= rse but instead I shall be brief and not bore you with long-winded diatribe= s about how utterly amazingly brief I prefer to be in virtually all circums= tances in their entirety.

[Applause]

Thank you. What I am getting at is that these pages are called =E2=80=9C= man pages=E2=80=9D in the Unix world, and I have included my own personal t= runcated variant here for your reading enjoyment. The thing is, many of the= se functions are way more general purpose than I=E2=80=99m letting on, but = I=E2=80=99m only going to present the parts that are relevant for Internet = Sockets Programming.

But wait! That=E2=80=99s not all that=E2=80=99s wrong with my man pages:=

  • They are incomplete and only show the basics from the guide.
  • There are many more man pages than this in the real world.
  • They are different than the ones on your system.
  • The header files might be different for certain functions on your syste= m.
  • The function parameters might be different for certain functions on you= r system.

If you want the real information, check your local Unix man pages by typ= ing man whatever, where =E2=80=9Cwhatever=E2=80=9D is somethin= g that you=E2=80=99re incredibly interested in, such as =E2=80=9Cacce= pt=E2=80=9D. (I=E2=80=99m sure Microsoft Visual Studio has something= similar in their help section. But =E2=80=9Cman=E2=80=9D is better because= it is one byte more concise than =E2=80=9Chelp=E2=80=9D. Unix wins again!)=

So, if these are so flawed, why even include them at all in the Guide? W= ell, there are a few reasons, but the best are that (a) these versions are = geared specifically toward network programming and are easier to digest tha= n the real ones, and (b) these versions contain examples!

Oh! And speaking of the examples, I don=E2=80=99t tend to put in all the= error checking because it really increases the length of the code. But you= should absolutely do error checking pretty much any time you make any of t= he system calls unless you=E2=80=99re totally 100% sure it=E2=80=99s not go= ing to fail, and you should probably do it even then!

9.1 accept()

Accept an incoming connection on a listening socket

9.1.0.1 Synopsis

    #include <sys/types.h>
    #include <sys/socket.h>
    
    int acc=
ept(int s, struct socka=
ddr *addr, socklen_t *addrlen);

9.1.0.2 Description

Once you=E2=80=99ve gone through the trouble of getting a SOCK_S= TREAM socket and setting it up for incoming connections with l= isten(), then you call accept() to actually get yoursel= f a new socket descriptor to use for subsequent communication with the newl= y connected client.

The old socket that you are using for listening is still there, and will= be used for further accept() calls as they come in.

Parameter Description
s The listen()ing socket descriptor.
addr This is filled in with the address of the site that=E2=80=99s connectin= g to you.
addrlen This is filled in with the sizeof() the structure returned= in the addr parameter. You can safely ignore it if you assume= you=E2=80=99re getting a struct sockaddr_in back, which you = know you are, because that=E2=80=99s the type you passed in for addr<= /code>.

accept() will normally block, and you can use select(= ) to peek on the listening socket descriptor ahead of time to see if= it=E2=80=99s =E2=80=9Cready to read=E2=80=9D. If so, then there=E2=80=99s = a new connection waiting to be accept()ed! Yay! Alternatively,= you could set the O_NONBLOCK flag on the listening socket us= ing fcntl(), and then it will never block, choosing instead t= o return -1 with errno set to EWOULDBLOCK<= /code>.

The socket descriptor returned by accept() is a bona fide s= ocket descriptor, open and connected to the remote host. You have to = close() it when you=E2=80=99re done with it.

9.1.0.3 Return Value

accept() returns the newly connected socket descriptor, or = -1 on error, with errno set appropriately.

9.1.0.4 Example

9.1.0.5 See Also

socket(), getaddrinfo(), listen(), struct sockaddr_in

9.2 bind()

Associate a socket with an IP address and port number

9.2.0.1 Synopsis

    #include <sys/types.h>
    #include <sys/socket.h>
    
    int bin=
d(int sockfd, struct so=
ckaddr *my_addr, socklen_t addrlen);

9.2.0.2 Description

When a remote machine wants to connect to your server program, it needs= two pieces of information: the IP address and the port number. The bind() call allows you to do just that.

First, you call getaddrinfo() to load up a struct soc= kaddr with the destination address and port information. Then you ca= ll socket() to get a socket descriptor, and then you pass the = socket and address into bind(), and the IP address and port ar= e magically (using actual magic) bound to the socket!

If you don=E2=80=99t know your IP address, or you know you only have one= IP address on the machine, or you don=E2=80=99t care which of the machine= =E2=80=99s IP addresses is used, you can simply pass the AI_PASSIVE flag in the hints parameter to getaddrinfo(). What this does is fill in the IP address part of the struct sockad= dr with a special value that tells bind() that it shoul= d automatically fill in this host=E2=80=99s IP address.

What what? What special value is loaded into the struct sockaddr=E2=80=99s IP address to cause it to auto-fill the address with the cu= rrent host? I=E2=80=99ll tell you, but keep in mind this is only if you=E2= =80=99re filling out the struct sockaddr by hand; if not, use = the results from getaddrinfo(), as per above. In IPv4, the sin_addr.s_addr field of the struct sockaddr_in stru= cture is set to INADDR_ANY. In IPv6, the sin6_addr field of the struct sockaddr_in6 structure is assigned into = from the global variable in6addr_any. Or, if you=E2=80=99re de= claring a new struct in6_addr, you can initialize it to = IN6ADDR_ANY_INIT.

Lastly, the addrlen parameter should be set to sizeof= my_addr.

9.2.0.3 Return Value

Returns zero on success, or -1 on error (and errno will be set accordingly).

9.2.0.4 Example

// modern =
way of doing things with getaddrinfo()

struct addrinfo hints, *res;
int sockfd;

// first, load up address structs with getaddrinfo():

memset(&hints, 0, sizeof<=
/span> hints);
hints.ai_family =3D AF_UNSPEC;  // use IPv4 or IPv6, wh=
ichever
<=
/a>hints.ai_socktype =3D SOCK_STREAM;
<=
/a>hints.ai_flags =3D AI_PASSIVE;     // fill in my IP f=
or me
<=
/a>
<=
/a>getaddrinfo(NULL, "3490", &hints, &res=
);
<=
/a>
<=
/a>// make a socket:
<=
/a>// (you should actually walk the "res" linked list an=
d error-check!)
<=
/a>
<=
/a>sockfd =3D socket(res->ai_family, res->ai_socktype, res->ai_pro=
tocol);
<=
/a>
<=
/a>// bind it to the port we passed in to getaddrinfo():=

<=
/a>
<=
/a>bind(sockfd, res->ai_addr, res->ai_addrlen);

9.2.0.5 See Also

getadd= rinfo(), = socket(), struct sockaddr_in, struct in_addr

9.3 connect()

Connect a socket to a server

9.3.0.1 Synopsis

    #include <sys/types.h>
    #include <sys/socket.h>
    
    int con=
nect(int sockfd, const =
struct sockaddr *serv_addr,
                socklen_t addrlen);

9.3.0.2 Description

Once you=E2=80=99ve built a socket descriptor with the socket() call, you can connect() that socket to a remote server u= sing the well-named connect() system call. All you need to do = is pass it the socket descriptor and the address of the server you=E2=80=99= re interested in getting to know better. (Oh, and the length of the address= , which is commonly passed to functions like this.)

Usually this information comes along as the result of a call to ge= taddrinfo(), but you can fill out your own struct sockaddr if you want to.

If you haven=E2=80=99t yet called bind() on the socket desc= riptor, it is automatically bound to your IP address and a random local por= t. This is usually just fine with you if you=E2=80=99re not a server, since= you really don=E2=80=99t care what your local port is; you only care what = the remote port is so you can put it in the serv_addr paramete= r. You can call bind() if you really want your client= socket to be on a specific IP address and port, but this is pretty rare.

Once the socket is connect()ed, you=E2=80=99re free to send() and recv() data on it to your heart=E2=80=99s = content.

Special note: if you connect() a SOCK_DGRAM U= DP socket to a remote host, you can use send() and recv(= ) as well as sendto() and recvfrom(). If y= ou want.

9.3.0.3 Return Value

Returns zero on success, or -1 on error (and errno will be set accordingly).

9.3.0.4 Example

9.3.0.5 See Also

socket(), bind()=

9.4 close()

Close a socket descriptor

9.4.0.1 Synopsis

    #include <unistd.h>
    
    int clo=
se(int s);

9.4.0.2 Description

After you=E2=80=99ve finished using the socket for whatever demented sc= heme you have concocted and you don=E2=80=99t want to send() o= r recv() or, indeed, do anything else at all with the= socket, you can close() it, and it=E2=80=99ll be freed up, ne= ver to be used again.

The remote side can tell if this happens one of two ways. One: if the re= mote side calls recv(), it will return 0. Two: if= the remote side calls send(), it=E2=80=99ll receive a signal = SIGPIPE and send() will return -1 and errn= o will be set to EPIPE.

Windows users: the function you need to use is called = closesocket(), not close(). If you try to use close() on a socket descriptor, it=E2=80=99s possible Windows wi= ll get angry=E2=80=A6 And you wouldn=E2=80=99t like it when it=E2=80=99s an= gry.

9.4.0.3 Return Value

Returns zero on success, or -1 on error (and errno will be set accordingly).

9.4.0.4 Example

9.4.0.5 See Also

socket(), sh= utdown()

9.5 getaddrinfo(), freeaddrinfo()= , gai_strerror()

Get information about a host name and/or service and load up a str= uct sockaddr with the result.

9.5.0.1 Synopsis

    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netdb.h>
    
    int get=
addrinfo(const char *no=
dename, const char *ser=
vname,
                    const struct addrinfo *hints, struct addrinfo **res);
    
    void fr=
eeaddrinfo(struct addrinfo *ai);
    
    const=
 char *gai_strerror(int=
 ecode);
    
    struct addrinfo {
      int=
     ai_flags;          // AI_PASSIVE, AI_CANONNAME, ...=

      int=
     ai_family;         // AF_xxx
      int=
     ai_socktype;       // SOCK_xxx
      int=
     ai_protocol;       // 0 (auto) or IPPROTO_TCP, IPPR=
OTO_UDP 
    
      socklen_t  ai_addrlen;     // length of ai_addr
      char   *ai_canonname;      // canonical name for nodename
      struct sockaddr  *ai_addr; // binary address
      struct addrinfo  *ai_next; // next structure in linked list=

    };

9.5.0.2 Description

getaddrinfo() is an excellent function that will return inf= ormation on a particular host name (such as its IP address) and load up a <= code>struct sockaddr for you, taking care of the gritty details (lik= e if it=E2=80=99s IPv4 or IPv6). It replaces the old functions gethos= tbyname() and getservbyname().The description, below, c= ontains a lot of information that might be a little daunting, but actual us= age is pretty simple. It might be worth it to check out the examples first.=

The host name that you=E2=80=99re interested in goes in the nodena= me parameter. The address can be either a host name, like =E2=80=9Cw= ww.example.com=E2=80=9D, or an IPv4 or IPv6 address (passed as a string). T= his parameter can also be NULL if you=E2=80=99re using the AI_PASSIVE flag (see below).

The servname parameter is basically the port number. It can= be a port number (passed as a string, like =E2=80=9C80=E2=80=9D), or it ca= n be a service name, like =E2=80=9Chttp=E2=80=9D or =E2=80=9Ctftp=E2=80=9D = or =E2=80=9Csmtp=E2=80=9D or =E2=80=9Cpop=E2=80=9D, etc. Well-known service= names can be found in the IANA Port List48= or in your /etc/services file.

Lastly, for input parameters, we have hints. This is really= where you get to define what the getaddrinfo() function is go= ing to do. Zero the whole structure before use with memset(). = Let=E2=80=99s take a look at the fields you need to set up before use.

The ai_flags can be set to a variety of things, but here ar= e a couple important ones. (Multiple flags can be specified by bitwise-ORin= g them together with the | operator). Check your man page for = the complete list of flags.

AI_CANONNAME causes the ai_canonname of the re= sult to the filled out with the host=E2=80=99s canonical (real) name. AI_PASSIVE causes the result=E2=80=99s IP address to be filled out = with INADDR_ANY (IPv4) or in6addr_any (IPv6); thi= s causes a subsequent call to bind() to auto-fill the IP addre= ss of the struct sockaddr with the address of the current host= . That=E2=80=99s excellent for setting up a server when you don=E2=80=99t w= ant to hardcode the address.

If you do use the AI_PASSIVE, flag, then you can pass NULL in the nodename (since bind() will f= ill it in for you later).

Continuing on with the input paramters, you=E2=80=99ll likely want to se= t ai_family to AF_UNSPEC which tells getadd= rinfo() to look for both IPv4 and IPv6 addresses. You can also restr= ict yourself to one or the other with AF_INET or AF_INET= 6.

Next, the socktype field should be set to SOCK_STREAM= or SOCK_DGRAM, depending on which type of socket you w= ant.

Finally, just leave ai_protocol at 0 to automa= tically choose your protocol type.

Now, after you get all that stuff in there, you can finally mak= e the call to getaddrinfo()!

Of course, this is where the fun begins. The res will now p= oint to a linked list of struct addrinfos, and you can go thro= ugh this list to get all the addresses that match what you passed in with t= he hints.

Now, it=E2=80=99s possible to get some addresses that don=E2=80=99t work= for one reason or another, so what the Linux man page does is loops throug= h the list doing a call to socket() and connect()= (or bind() if you=E2=80=99re setting up a server with the AI_PASSIVE flag) until it succeeds.

Finally, when you=E2=80=99re done with the linked list, you need to call= freeaddrinfo() to free up the memory (or it will be leaked, a= nd Some People will get upset).

9.5.0.3 Return Value

Returns zero on success, or nonzero on error. If it returns nonzero, you= can use the function gai_strerror() to get a printable versio= n of the error code in the return value.

9.5.0.4 Example

9.5.0.5 See Also

geth= ostbyname(), getnameinfo()

9.6 gethostname()

Returns the name of the system

9.6.0.1 Synopsis

    #include <sys/unistd.h>
    
    int get=
hostname(char *name, size_t len);

9.6.0.2 Description

Your system has a name. They all do. This is a slightly more Unixy thin= g than the rest of the networky stuff we=E2=80=99ve been talking about, but= it still has its uses.

For instance, you can get your host name, and then call gethostby= name() to find out your IP address.

The parameter name should point to a buffer that will hold = the host name, and len is the size of that buffer in bytes. gethostname() won=E2=80=99t overwrite the end of the buffer (it = might return an error, or it might just stop writing), and it will NU= L-terminate the string if there=E2=80=99s room for it in the buffer.=

9.6.0.3 Return Value

Returns zero on success, or -1 on error (and errno will be set accordingly).

9.6.0.4 Example

9.6.0.5 See Also

geth= ostbyname()

9.7 gethostbyname(), gethostbyaddr()

Get an IP address for a hostname, or vice-versa

9.7.0.1 Synopsis

    #include <sys/socket.h>
    #include <netdb.h>
    
    struct =
hostent *gethostbyname(const c=
har *name); // DEPRECAT=
ED!
    struct =
hostent *gethostbyaddr(const c=
har *addr, int len, int=
 type);

9.7.0.2 Description

PLEASE NOTE: these two functions are superseded by getaddrin= fo() and getnameinfo()! In particular, getho= stbyname() doesn=E2=80=99t work well with IPv6.

These functions map back and forth between host names and IP addresses. = For instance, if you have =E2=80=9Cwww.example.com=E2=80=9D, you can use gethostbyname() to get its IP address and store it in a st= ruct in_addr.

Conversely, if you have a struct in_addr or a struct = in6_addr, you can use gethostbyaddr() to get the hostna= me back. gethostbyaddr() is IPv6 compatible, but you = should use the newer shinier getnameinfo() instead.

(If you have a string containing an IP address in dots-and-numbers forma= t that you want to look up the hostname of, you=E2=80=99d be better off usi= ng getaddrinfo() with the AI_CANONNAME flag.)

gethostbyname() takes a string like =E2=80=9Cwww.yahoo.com= =E2=80=9D, and returns a struct hostent which contains tons of= information, including the IP address. (Other information is the official= host name, a list of aliases, the address type, the length of the addresse= s, and the list of addresses=E2=80=94it=E2=80=99s a general-purpose structu= re that=E2=80=99s pretty easy to use for our specific purposes once you see= how.)

gethostbyaddr() takes a struct in_addr or struct in6_addr and brings you up a corresponding host name (if th= ere is one), so it=E2=80=99s sort of the reverse of gethostbyname(). As for parameters, even though addr is a char*, you actually want to pass in a pointer to a struct in_addr. len should be sizeof(struct in_addr), and type should be AF_INET.

So what is this struct hostent that gets returned? It has = a number of fields that contain information about the host in question.

Field Description
char *h_name The real canonical host name.
char **h_aliases A list of aliases that can be accessed with arrays=E2=80=94the last ele= ment is NULL
int h_addrtype The result=E2=80=99s address type, which really should be AF_INET= for our purposes.
int length The length of the addresses in bytes, which is 4 for IP (version 4) add= resses.
char **h_addr_list A list of IP addresses for this host. Although this is a char**, it=E2=80=99s really an array of struct in_addr*s in dis= guise. The last array element is NULL.
h_addr A commonly defined alias for h_addr_list[0]. If you just w= ant any old IP address for this host (yeah, they can have more than one) ju= st use this field.

9.7.0.3 Return Value

Returns a pointer to a resultant struct hostent on success,= or NULL on error.

Instead of the normal perror() and all that stuff you=E2=80= =99d normally use for error reporting, these functions have parallel result= s in the variable h_errno, which can be printed using the func= tions herror() or hstrerror(). These work just = like the classic errno, perror(), and strer= ror() functions you=E2=80=99re used to.

9.7.0.4 Example

9.7.0.5 See Also

getadd= rinfo(), getnameinfo(), gethostname(), errno, perror(), strerror(), struct in_a= ddr

9.8 getnameinfo()

Look up the host name and service name information for a given str= uct sockaddr.

9.8.0.1 Synopsis

    #include <sys/socket.h>
    #include <netdb.h>
    
    int get=
nameinfo(const struct s=
ockaddr *sa, socklen_t salen,
                    char *host, size_t hostlen,
                    char *serv, size_t servlen, int flags);

9.8.0.2 Description

This function is the opposite of getaddrinfo(), that is, th= is function takes an already loaded struct sockaddr and does a= name and service name lookup on it. It replaces the old gethostbyadd= r() and getservbyport() functions.

You have to pass in a pointer to a struct sockaddr (which i= n actuality is probably a struct sockaddr_in or struct s= ockaddr_in6 that you=E2=80=99ve cast) in the sa paramet= er, and the length of that struct in the salen.

The resultant host name and service name will be written to the area poi= nted to by the host and serv parameters. Of cours= e, you have to specify the max lengths of these buffers in hostlen and servlen.

Finally, there are several flags you can pass, but here a a couple good = ones. NI_NOFQDN will cause the host to only conta= in the host name, not the whole domain name. NI_NAMEREQD will = cause the function to fail if the name cannot be found with a DNS lookup (i= f you don=E2=80=99t specify this flag and the name can=E2=80=99t be found, = getnameinfo() will put a string version of the IP address in <= code>host instead).

As always, check your local man pages for the full scoop.

9.8.0.3 Return Value

Returns zero on success, or non-zero on error. If the return value is no= n-zero, it can be passed to gai_strerror() to get a human-read= able string. See getaddrinfo for more information.

9.8.0.4 Example

9.8.0.5 See Also

getadd= rinfo(), gethostbyaddr()

9.9 getpeername()

Return address info about the remote side of the connection

9.9.0.1 Synopsis

    #include <sys/socket.h>
    
    int get=
peername(int s, struct =
sockaddr *addr, socklen_t *len);

9.9.0.2 Description

Once you have either accept()ed a remote connection, or connect()ed to a server, you now have what is known as a pee= r. Your peer is simply the computer you=E2=80=99re connected to, ident= ified by an IP address and a port. So=E2=80=A6

getpeername() simply returns a struct sockaddr_in filled with information about the machine you=E2=80=99re connected to.<= /p>

Why is it called a =E2=80=9Cname=E2=80=9D? Well, there are a lot of diff= erent kinds of sockets, not just Internet Sockets like we=E2=80=99re using = in this guide, and so =E2=80=9Cname=E2=80=9D was a nice generic term that c= overed all cases. In our case, though, the peer=E2=80=99s =E2=80=9Cname=E2= =80=9D is it=E2=80=99s IP address and port.

Although the function returns the size of the resultant address in len, you must preload len with the size of addr<= /code>.

9.9.0.3 Return Value

Returns zero on success, or -1 on error (and errno will be set accordingly).

9.9.0.4 Example

// ass=
ume s is a connected socket
<=
/a>
<=
/a>socklen_t len;
<=
/a>struct sockaddr_storage addr;
<=
/a>char ipstr[INET6_ADDRSTRLEN];
<=
/a>int port;
<=
/a>
<=
/a>len =3D sizeof addr;
<=
/a>getpeername(s, (struct sockaddr*)&addr, &a=
mp;len);

// deal with both IPv4 and IPv6:
if (addr.ss_family =3D=3D AF_INET) {
    struct sockaddr_in *s =3D (struct sockaddr_in *)&addr;
    port =3D ntohs(s->sin_port);
    inet_ntop(AF_INET, &s->sin_addr, ipstr, =
sizeof ipstr);
} else { // AF_INET6
    struct sockaddr_in6 *s =3D (struct sockaddr_in6 *)&addr;
    port =3D ntohs(s->sin6_port);
    inet_ntop(AF_INET6, &s->sin6_addr, ipstr, sizeof ipstr);
}

printf("Peer IP address: %s\n", ipstr);
printf("Peer port      : %d\n", port);

9.9.0.5 See Also

gethos= tname(), gethostbyname(), gethostbyaddr()

9.10 errno

Holds the error code for the last system call

9.10.0.1 Synopsis

    #include <errno.h>
    
    int e=
rrno;

9.10.0.2 Description

This is the variable that holds error information for a lot of system c= alls. If you=E2=80=99ll recall, things like socket() and listen() return -1 on error, and they set the exact va= lue of errno to let you know specifically which error occurred= .

The header file errno.h lists a bunch of constant symbolic = names for errors, such as EADDRINUSE, EPIPE, ECONNREFUSED, etc. Your local man pages will tell you what codes c= an be returned as an error, and you can use these at run time to handle dif= ferent errors in different ways.

Or, more commonly, you can call perror() or strerro= r() to get a human-readable version of the error.

One thing to note, for you multithreading enthusiasts, is that on most s= ystems errno is defined in a threadsafe manner. (That is, it= =E2=80=99s not actually a global variable, but it behaves just like a globa= l variable would in a single-threaded environment.)

9.10.0.3 Return Value

The value of the variable is the latest error to have transpired, which = might be the code for =E2=80=9Csuccess=E2=80=9D if the last action succeede= d.

9.10.0.4 Example

s =3D socket(PF_INET, SOC=
K_STREAM, 0);
<=
/a>if (s =3D=3D -1) {
<=
/a>    perror("socket"); // or=
 use strerror()
<=
/a>}
<=
/a>
<=
/a>tryagain:
<=
/a>if (select(n, &readfds, NULL, NULL) =3D=3D=
 -1) {
<=
/a>    // an error has occurred!!
<=
/a>
    // if we were only interrupted, just restart th=
e select() call:
    if (errno =3D=3D EINTR) goto tryagain;  // AAAA! goto!!!

    // otherwise it's a more serious error:<=
/span>
    perror("select");
    exit(1);
}

9.10.0.5 See Also

perror(), stre= rror()

9.11 fcntl()

Control socket descriptors

9.11.0.1 Synopsis

    #include <sys/unistd.h>
    #include <sys/fcntl.h>
    
    int f=
cntl(int s, int cmd, long arg);

9.11.0.2 Description

This function is typically used to do file locking and other file-orien= ted stuff, but it also has a couple socket-related functions that you might= see or use from time to time.

Parameter s is the socket descriptor you wish to operate on= , cmd should be set to F_SETFL, and arg can be one of the following commands. (Like I said, there=E2=80=99s mo= re to fcntl() than I=E2=80=99m letting on here, but I=E2=80=99= m trying to stay socket-oriented.)

cmd Description
O_NONBLOCK Set the socket to be non-blocking. See the section on blocking for more details.
O_ASYNC Set the socket to do asynchronous I/O. When data is ready to be r= ecv()=E2=80=99d on the socket, the signal SIGIO will be= raised. This is rare to see, and beyond the scope of the guide. And I thin= k it=E2=80=99s only available on certain systems.

9.11.0.3 Return Value

Returns zero on success, or -1 on error (and errno will be set accordingly).

Different uses of the fcntl() system call actually have dif= ferent return values, but I haven=E2=80=99t covered them here because they= =E2=80=99re not socket-related. See your local fcntl() man pag= e for more information.

9.11.0.4 Example

9.11.0.5 See Also

Blocking, send()

9.12 htons(), htonl(), ntohs(), ntohl()

Convert multi-byte integer types from host byte order to network byte or= der

9.12.0.1 Synopsis

    #include <netinet/in.h>
    
    uint32_t htonl(uint32_t hostlong);
    uint16_t htons(uint16_t hostshort);
    uint32_t ntohl(uint32_t netlong);
    uint16_t ntohs(uint16_t netshort);
=

9.12.0.2 Description

Just to make you really unhappy, different computers use different b= yte orderings internally for their multibyte integers (i.e. any intege= r that=E2=80=99s larger than a char). The upshot of this is th= at if you send() a two-byte short int from an Int= el box to a Mac (before they became Intel boxes, too, I mean), what one com= puter thinks is the number 1, the other will think is the numb= er 256, and vice-versa.

The way to get around this problem is for everyone to put aside their d= ifferences and agree that Motorola and IBM had it right, and Intel did it t= he weird way, and so we all convert our byte orderings to =E2=80=9Cbig-endi= an=E2=80=9D before sending them out. Since Intel is a =E2=80=9Clittle-endia= n=E2=80=9D machine, it=E2=80=99s far more politically correct to call our p= referred byte ordering =E2=80=9CNetwork Byte Order=E2=80=9D. So these funct= ions convert from your native byte order to network byte order and back aga= in.

(This means on Intel these functions swap all the bytes around, and on P= owerPC they do nothing because the bytes are already in Network Byte Order.= But you should always use them in your code anyway, since someone might wa= nt to build it on an Intel machine and still have things work properly.)

Note that the types involved are 32-bit (4 byte, probably int) and 16-bit (2 byte, very likely short) numbers. 64-bit mac= hines might have a htonll() for 64-bit ints, but = I=E2=80=99ve not seen it. You=E2=80=99ll just have to write your own.

Anyway, the way these functions work is that you first decide if you=E2= =80=99re converting from host (your machine=E2=80=99s) byte order = or from network byte order. If =E2=80=9Chost=E2=80=9D, the the first letter= of the function you=E2=80=99re going to call is =E2=80=9Ch=E2=80=9D. Other= wise it=E2=80=99s =E2=80=9Cn=E2=80=9D for =E2=80=9Cnetwork=E2=80=9D. The mi= ddle of the function name is always =E2=80=9Cto=E2=80=9D because you=E2=80= =99re converting from one =E2=80=9Cto=E2=80=9D another, and the penultimate= letter shows what you=E2=80=99re converting to. The last letter i= s the size of the data, =E2=80=9Cs=E2=80=9D for short, or =E2=80=9Cl=E2=80= =9D for long. Thus:

Function Description
htons() host to network sho= rt
htonl() host to network lon= g
ntohs() network to host sho= rt
ntohl() network to host lon= g

9.12.0.3 Return Value

Each function returns the converted value.

9.12.0.4 Example

9.13 inet_ntoa(), inet_aton(), inet_addr

Convert IP addresses from a dots-and-number string to a struct in_= addr and back

9.13.0.1 Synopsis

    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    
    // ALL THESE=
 ARE DEPRECATED! Use in=
et_pton()  or inet_ntop() instead!!
    
    char =
*inet_ntoa(struct in_addr in);
    int i=
net_aton(const char *cp=
, struct in_addr *inp);
    in_addr_t inet_addr(const char *cp);

9.13.0.2 Description

These functions are deprecated because they don=E2=80=99t handle IPv= 6! Use inet_ntop() or inet_pton() instead! They a= re included here because they can still be found in the wild.

All of these functions convert from a struct in_addr (pa= rt of your struct sockaddr_in, most likely) to a string in dot= s-and-numbers format (e.g. =E2=80=9C192.168.5.10=E2=80=9D) and vice-versa. = If you have an IP address passed on the command line or something, this is = the easiest way to get a struct in_addr to connect() to, or whatever. If you need more power, try some of the DNS functions = like gethostbyname() or attempt a coup d=E2=80=99=C3=89tat= in your local country.

The function inet_ntoa() converts a network address in a struct in_addr to a dots-and-numbers format string. The =E2=80= =9Cn=E2=80=9D in =E2=80=9Cntoa=E2=80=9D stands for network, and the =E2=80= =9Ca=E2=80=9D stands for ASCII for historical reasons (so it=E2=80=99s =E2= =80=9CNetwork To ASCII=E2=80=9D=E2=80=94the =E2=80=9Ctoa=E2=80=9D suffix ha= s an analogous friend in the C library called atoi() which con= verts an ASCII string to an integer).

The function inet_aton() is the opposite, converting from a= dots-and-numbers string into a in_addr_t (which is the type o= f the field s_addr in your struct in_addr).

Finally, the function inet_addr() is an older function that= does basically the same thing as inet_aton(). It=E2=80=99s th= eoretically deprecated, but you=E2=80=99ll see it a lot and the police won= =E2=80=99t come get you if you use it.

9.13.0.3 Return Value

inet_aton() returns non-zero if the address is a valid one,= and it returns zero if the address is invalid.

inet_ntoa() returns the dots-and-numbers string in a static= buffer that is overwritten with each call to the function.

inet_addr() returns the address as an in_addr_t, or -1 if there=E2=80=99s an error. (That is the same result= as if you tried to convert the string =E2=80=9C255.255.255.255=E2=80=9D, which is a valid IP address. This is why inet_aton() is better.)

9.13.0.4 Example

9.13.0.5 See Also

inet_nto= p(), <= code>inet_pton(), gethostbyname(), gethostbyaddr()

9.14 inet_ntop(), inet_pton()

Convert IP addresses to human-readable form and back.

9.14.0.1 Synopsis

    #include <arpa/inet.h>
    
    const=
 char *inet_ntop(int af=
, const void *src,
                          char *dst, socklen_t size);
    
    int i=
net_pton(int af, const =
char *src, void *dst);<=
/span>

9.14.0.2 Description

These functions are for dealing with human-readable IP addresses and con= verting them to their binary representation for use with various functions = and system calls. The =E2=80=9Cn=E2=80=9D stands for =E2=80=9Cnetwork=E2=80= =9D, and =E2=80=9Cp=E2=80=9D for =E2=80=9Cpresentation=E2=80=9D. Or =E2=80= =9Ctext presentation=E2=80=9D. But you can think of it as =E2=80=9Cprintabl= e=E2=80=9D. =E2=80=9Cntop=E2=80=9D is =E2=80=9Cnetwork to printable=E2=80= =9D. See?

Sometimes you don=E2=80=99t want to look at a pile of binary numbers whe= n looking at an IP address. You want it in a nice printable form, like 192.0.2.180, or 2001:db8:8714:3a90::12. In that case,= inet_ntop() is for you.

inet_ntop() takes the address family in the af= parameter (either AF_INET or AF_INET6). The src parameter should be a pointer to either a struct in_addr= or struct in6_addr containing the address you wish to = convert to a string. Finally dst and size are the= pointer to the destination string and the maximum length of that string.

What should the maximum length of the dst string be? What i= s the maximum length for IPv4 and IPv6 addresses? Fortunately there are a c= ouple of macros to help you out. The maximum lengths are: INET_ADDRST= RLEN and INET6_ADDRSTRLEN.

Other times, you might have a string containing an IP address in readabl= e form, and you want to pack it into a struct sockaddr_in or a= struct sockaddr_in6. In that case, the opposite funcion inet_pton() is what you=E2=80=99re after.

inet_pton() also takes an address family (either AF_I= NET or AF_INET6) in the af parameter. The = src parameter is a pointer to a string containing the IP addre= ss in printable form. Lastly the dst parameter points to where= the result should be stored, which is probably a struct in_addr or struct in6_addr.

These functions don=E2=80=99t do DNS lookups=E2=80=94you=E2=80=99ll need= getaddrinfo() for that.

9.14.0.3 Return Value

inet_ntop() returns the dst parameter on succe= ss, or NULL on failure (and errno is set).

inet_pton() returns 1 on success. It returns <= code>-1 if there was an error (errno is set), or = 0 if the input isn=E2=80=99t a valid IP address.

9.14.0.4 Example

// IPv=
4 demo of inet_ntop() and inet_pton()
<=
/a>
<=
/a>struct sockaddr_in sa;
<=
/a>char str[INET_ADDRSTRLEN];
<=
/a>
<=
/a>// store this IP address in sa:
<=
/a>inet_pton(AF_INET, "192.0.2.33", &(sa.sin_=
addr));
<=
/a>
<=
/a>// now get it back and print it
inet_ntop(AF_INET, &(sa.sin_addr), str, INET_ADDRSTRLEN);

printf("%s\n", str); // prints "192.0.2.33"
// IPv=
6 demo of inet_ntop() and inet_pton()
<=
/a>// (basically the same except with a bunch of 6s thro=
wn around)
<=
/a>
<=
/a>struct sockaddr_in6 sa;
<=
/a>char str[INET6_ADDRSTRLEN];
<=
/a>
<=
/a>// store this IP address in sa:
<=
/a>inet_pton(AF_INET6, "2001:db8:8714:3a90::12", =
&(sa.sin6_addr));
<=
/a>
// now get it back and print it
inet_ntop(AF_INET6, &(sa.sin6_addr), str, INET6_ADDRSTRLEN);

printf("%s\n", str); // prints "2001:db8:8714:3a=
90::12"
// Hel=
per function you can use:
<=
/a>
<=
/a>//Convert a struct sockaddr address to a string, IPv4=
 and IPv6:
<=
/a>
<=
/a>char *get_ip_str(const struct sockaddr *sa, char *s, size_t maxlen)
<=
/a>{
<=
/a>    switch(sa->sa_family) {
<=
/a>        case AF_INET:
<=
/a>            inet_ntop(AF_INET, &(((struct =
sockaddr_in *)sa)->sin_addr),
                    s, maxlen);
            break;

        case AF_INET6:
            inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)sa)->sin6_addr),
                    s, maxlen);
            break;

        default:
            strncpy(s, "Unknown AF", maxlen)=
;
            return NULL;
    }

    return s;
}

9.14.0.5 See Also

getadd= rinfo()

9.15 listen()

Tell a socket to listen for incoming connections

9.15.0.1 Synopsis

    #include <sys/socket.h>
    
    int l=
isten(int s, int backlo=
g);

9.15.0.2 Description

You can take your socket descriptor (made with the socket() system call) and tell it to listen for incoming connections. This is what= differentiates the servers from the clients, guys.

The backlog parameter can mean a couple different things de= pending on the system you on, but loosely it is how many pending connection= s you can have before the kernel starts rejecting new ones. So as the new c= onnections come in, you should be quick to accept() them so th= at the backlog doesn=E2=80=99t fill. Try setting it to 10 or so, and if you= r clients start getting =E2=80=9CConnection refused=E2=80=9D under heavy lo= ad, set it higher.

Before calling listen(), your server should call bind= () to attach itself to a specific port number. That port number (on = the server=E2=80=99s IP address) will be the one that clients connect to.

9.15.0.3 Return Value

Returns zero on success, or -1 on error (and errno will be set accordingly).

9.15.0.4 Example

struct=
 addrinfo hints, *res;
<=
/a>int sockfd;
<=
/a>
<=
/a>// first, load up address structs with getaddrinfo():=

<=
/a>
<=
/a>memset(&hints, 0, sizeo=
f hints);
<=
/a>hints.ai_family =3D AF_UNSPEC;  // use IPv4 or IPv6, =
whichever
<=
/a>hints.ai_socktype =3D SOCK_STREAM;
<=
/a>hints.ai_flags =3D AI_PASSIVE;     // fill in my IP f=
or me

getaddrinfo(NULL, "3490", &hints, &r=
es);

// make a socket:

sockfd =3D socket(res->ai_family, res->ai_socktype, res->ai_p=
rotocol);

// bind it to the port we passed in to getaddrinfo(=
):

bind(sockfd, res->ai_addr, res->ai_addrlen);

listen(sockfd, 10); // se=
t s up to be a server (listening) socket

// then have an accept() loop down here somewhere

9.15.0.5 See Also

accept(), bind()= , s= ocket()

9.16 perror(), strerror()

Print an error as a human-readable string

9.16.0.1 Synopsis

    #include <stdio.h>
    #include <string.h>   =
// for strerror()
    
    void =
perror(const char *s);<=
/span>
    char =
*strerror(int errnum);

9.16.0.2 Description

Since so many functions return -1 on error and set the va= lue of the variable errno to be some number, it would sure be= nice if you could easily print that in a form that made sense to you.

Mercifully, perror() does that. If you want more descriptio= n to be printed before the error, you can point the parameter s to it (or you can leave s as NULL and nothing a= dditional will be printed).

In a nutshell, this function takes errno values, like ECONNRESET, and prints them nicely, like =E2=80=9CConnection reset = by peer.=E2=80=9D

The function strerror() is very similar to perror(), except it returns a pointer to the error message string for a given = value (you usually pass in the variable errno).

9.16.0.3 Return Value

strerror() returns a pointer to the error message string.

9.16.0.4 Example

int s;
<=
/a>
<=
/a>s =3D socket(PF_INET, SOCK_STREAM, 0);
<=
/a>
<=
/a>if (s =3D=3D -1) { <=
span class=3D"co">// some error has occurred
<=
/a>    // prints "socket error: " + the error message:
<=
/a>    perror("socket error");
<=
/a>}
<=
/a>
// similarly:
if (listen(s, 10) =
=3D=3D -1) {
    // this prints "an error: " + the error message=
 from errno:
    printf("an error: %s\=
n", strerror(errno));
}

9.16.0.5 See Also

errno=

9.17 poll()

Test for events on multiple sockets simultaneously

9.17.0.1 Synopsis

    #include <sys/poll.h>
    
    int p=
oll(struct pollfd *ufds, unsig=
ned int nfds, int timeout);

9.17.0.2 Description

This function is very similar to select() in that they bot= h watch sets of file descriptors for events, such as incoming data ready to= recv(), socket ready to send() data to, out-of-b= and data ready to recv(), errors, etc.

The basic idea is that you pass an array of nfds stru= ct pollfds in ufds, along with a timeout in millisecond= s (1000 milliseconds in a second). The timeout can be negative= if you want to wait forever. If no event happens on any of the socket desc= riptors by the timeout, poll() will return.

Each element in the array of struct pollfds represents one = socket descriptor, and contains the following fields:

    struct pollfd {
        int fd;         // the socket descriptor
        short events;   // bitmap of events we're interested in
        short revents;  // when poll() returns, bitmap of events =
that occurred
    };

Before calling poll(), load fd with the socket= descriptor (if you set fd to a negative number, this st= ruct pollfd is ignored and its revents field is set to = zero) and then construct the events field by bitwise-ORing the= following macros:

Macro Description
POLLIN Alert me when data is ready to recv() on this socket.
POLLOUT Alert me when I can send() data to this socket without blo= cking.
POLLPRI Alert me when out-of-band data is ready to recv() on this = socket.

Once the poll() call returns, the revents fiel= d will be constructed as a bitwise-OR of the above fields, telling you whic= h descriptors actually have had that event occur. Additionally, these other= fields might be present:

Macro Description
POLLERR An error has occurred on this socket.
POLLHUP The remote side of the connection hung up.
POLLNVAL Something was wrong with the socket descriptor fd=E2=80=94= maybe it=E2=80=99s uninitialized?

9.17.0.3 Return Value

Returns the number of elements in the ufds array that have = had event occur on them; this can be zero if the timeout occurred. Also ret= urns -1 on error (and errno will be set according= ly).

9.17.0.4 Example

int s1, s2;
<=
/a>int rv;
<=
/a>char buf1[256], buf2=
[256];
<=
/a>struct pollfd ufds[2=
];
<=
/a>
<=
/a>s1 =3D socket(PF_INET, SOCK_STREAM, 0);
<=
/a>s2 =3D socket(PF_INET, SOCK_STREAM, 0);
<=
/a>
<=
/a>// pretend we've connected both to a server at this p=
oint
//connect(s1, ...)...
//connect(s2, ...)...

// set up the array of file descriptors.
//
// in this example, we want to know when there's no=
rmal or out-of-band
// data ready to be recv()'d...

ufds[0].fd =3D s1;
ufds[0].events =3D POLLIN | POLLPRI; // check for normal or out-of-band

ufds[1].fd =3D s2;
ufds[1].events =3D POLLIN; // check for just normal data

// wait for events on the sockets, 3.5 second timeo=
ut
rv =3D poll(ufds, 2, 3500=
);

if (rv =3D=3D -1) =
{
    perror("poll"); // er=
ror occurred in poll()
} else if (rv =3D=
=3D 0) {
    printf("Timeout occurred! No data after 3.5 sec=
onds.\n");
} else {
    // check for events on s1:
    if (ufds[0].re=
vents & POLLIN) {
        recv(s1, buf1, sizeof buf1, 0); // receive normal data
    }
    if (ufds[0].re=
vents & POLLPRI) {
        recv(s1, buf1, sizeof buf1, MSG_OOB)=
; // out-of-band data
    }

    // check for events on s2:
    if (ufds[1].re=
vents & POLLIN) {
        recv(s1, buf2, sizeof buf2, 0);
    }
}

9.17.0.5 See Also

select()

9.18 recv(), recvfrom()

Receive data on a socket

9.18.0.1 Synopsis

    #include <sys/types.h>
    #include <sys/socket.h>
    
    ssize_t recv(int s, void *bu=
f, size_t len, int flag=
s);
    ssize_t recvfrom(int s, void=
 *buf, size_t len, int =
flags,
                     struct sockaddr *from, socklen_t *fromlen);
=

9.18.0.2 Description

Once you have a socket up and connected, you can read incoming data fr= om the remote side using the recv() (for TCP SOCK_STREA= M sockets) and recvfrom() (for UDP SOCK_DGRAM sockets).

Both functions take the socket descriptor s, a pointer to t= he buffer buf, the size (in bytes) of the buffer len, and a set of flags that control how the functions work.

Additionally, the recvfrom() takes a struct sockaddr= *, from that will tell you where the data came from, an= d will fill in fromlen with the size of struct sockaddr<= /code>. (You must also initialize fromlen to be the size of from or struct sockaddr.)

So what wondrous flags can you pass into this function? Here are some of= them, but you should check your local man pages for more information and w= hat is actually supported on your system. You bitwise-or these together, or= just set flags to 0 if you want it to be a regul= ar vanilla recv().

Macro Description
MSG_OOB Receive Out of Band data. This is how to get data that has been sent to= you with the MSG_OOB flag in send(). As the rece= iving side, you will have had signal SIGURG raised telling yo= u there is urgent data. In your handler for that signal, you could call recv() with this MSG_OOB flag.
MSG_PEEK If you want to call recv() =E2=80=9Cjust for pretend=E2=80= =9D, you can call it with this flag. This will tell you what=E2=80=99s wait= ing in the buffer for when you call recv() =E2=80=9Cfor real= =E2=80=9D (i.e. without the MSG_PEEK flag. It=E2= =80=99s like a sneak preview into the next recv() call.
MSG_WAITALL Tell recv() to not return until all the data you specified= in the len parameter. It will ignore your wishes in extreme c= ircumstances, however, like if a signal interrupts the call or if some erro= r occurs or if the remote side closes the connection, etc. Don=E2=80=99t be= mad with it.

When you call recv(), it will block until there is some dat= a to read. If you want to not block, set the socket to non-blocking or chec= k with select() or poll() to see if there is inco= ming data before calling recv() or recvfrom().

9.18.0.3 Return Value

Returns the number of bytes actually received (which might be less than = you requested in the len parameter), or -1 on err= or (and errno will be set accordingly).

If the remote side has closed the connection, recv() will r= eturn 0. This is the normal method for determining if the remo= te side has closed the connection. Normality is good, rebel!

9.18.0.4 Example

// str=
eam sockets and recv()
<=
/a>
<=
/a>struct addrinfo hints, *res;
<=
/a>int sockfd;
<=
/a>char buf[512];
<=
/a>int byte_count;
<=
/a>
<=
/a>// get host info, make socket, and connect it<=
/span>
<=
/a>memset(&hints, 0, sizeo=
f hints);
hints.ai_family =3D AF_UNSPEC;  // use IPv4 or IPv6=
, whichever
hints.ai_socktype =3D SOCK_STREAM;
getaddrinfo("www.example.com", "3490", &hints, &res);
sockfd =3D socket(res->ai_family, res->ai_socktype, res->ai_p=
rotocol);
connect(sockfd, res->ai_addr, res->ai_addrlen);

// all right! now that we're connected, we can rece=
ive some data!
byte_count =3D recv(sockfd, buf, sizeof buf,=
 0);
printf("recv()'d %d bytes of data in buf\n", byte_count);
// dat=
agram sockets and recvfrom()
<=
/a>
<=
/a>struct addrinfo hints, *res;
<=
/a>int sockfd;
<=
/a>int byte_count;
<=
/a>socklen_t fromlen;
<=
/a>struct sockaddr_storage addr;
<=
/a>char buf[512];
<=
/a>char ipstr[INET6_ADDRSTRLEN];

// get host info, make socket, bind it to port 4950=

memset(&hints, 0, siz=
eof hints);
hints.ai_family =3D AF_UNSPEC;  // use IPv4 or IPv6=
, whichever
hints.ai_socktype =3D SOCK_DGRAM;
hints.ai_flags =3D AI_PASSIVE;
getaddrinfo(NULL, "4950", &hints, &r=
es);
sockfd =3D socket(res->ai_family, res->ai_socktype, res->ai_p=
rotocol);
bind(sockfd, res->ai_addr, res->ai_addrlen);

// no need to accept(), just recvfrom():

fromlen =3D sizeof addr;
byte_count =3D recvfrom(sockfd, buf, sizeof =
buf, 0, &addr, &fromlen);

printf("recv()'d %d bytes of data in buf\n", byte_count);
printf("from IP address %s\n",
    inet_ntop(addr.ss_family,
        addr.ss_family =3D=3D AF_INET?
            ((struct sockadd_in *)&addr)=
->sin_addr:
            ((struct sockadd_in6 *)&addr=
)->sin6_addr,
        ipstr, sizeof ipstr);<=
/pre>

9.18.0.5 See Also

send()= , sendto(), sel= ect(), poll(), = Blocking

9.19 select()

Check if sockets descriptors are ready to read/write

9.19.0.1 Synopsis

    #include <sys/select.h>
    
    int s=
elect(int n, fd_set *readfds, fd_set *writefds, f=
d_set *exceptfds,
               s=
truct timeval *timeout);
    
    FD_SET(int fd, fd_set *set);
    FD_CLR(int fd, fd_set *set);
    FD_ISSET(int=
 fd, fd_set *set);
    FD_ZERO(fd_set *set);

9.19.0.2 Description

The select() function gives you a way to simultaneously ch= eck multiple sockets to see if they have data waiting to be recv()d, or if you can send() data to them without blocking, or = if some exception has occurred.

You populate your sets of socket descriptors using the macros, like FD_SET(), above. Once you have the set, you pass it into the funct= ion as one of the following parameters: readfds if you want to= know when any of the sockets in the set is ready to recv() da= ta, writefds if any of the sockets is ready to send() data to, and/or exceptfds if you need to know when an exc= eption (error) occurs on any of the sockets. Any or all of these parameters= can be NULL if you=E2=80=99re not interested in those types o= f events. After select() returns, the values in the sets will = be changed to show which are ready for reading or writing, and which have e= xceptions.

The first parameter, n is the highest-numbered socket descr= iptor (they=E2=80=99re just ints, remember?) plus one.

Lastly, the struct timeval, timeout, at the e= nd=E2=80=94this lets you tell select() how long to check these= sets for. It=E2=80=99ll return after the timeout, or when an event occurs,= whichever is first. The struct timeval has two fields: = tv_sec is the number of seconds, to which is added tv_usec, the number of microseconds (1,000,000 microseconds in a second).

The helper macros do the following:

Macro Description
FD_SET(int fd, fd_set *set); Add fd to the set.
FD_CLR(int fd, fd_set *set); Remove fd from the set.
FD_ISSET(int fd, fd_set *set); Return true if fd is in the set.
FD_ZERO(fd_set *set); Clear all entries from the set.

Note for Linux users: Linux=E2=80=99s select() can return = =E2=80=9Cready-to-read=E2=80=9D and then not actually be ready to read, thu= s causing the subsequent read() call to block. You can work ar= ound this bug by setting O_NONBLOCK flag on the receiving soc= ket so it errors with EWOULDBLOCK, then ignoring this error if= it occurs. See the <= code>fcntl() reference page for more info on setting a socket to= non-blocking.

9.19.0.3 Return Value

Returns the number of descriptors in the set on success, 0 = if the timeout was reached, or -1 on error (and errno will be set accordingly). Also, the sets are modified to show which so= ckets are ready.

9.19.0.4 Example

int s1, s2, n;
<=
/a>fd_set readfds;
<=
/a>struct timeval tv;
<=
/a>char buf1[256], buf2=
[256];
<=
/a>
<=
/a>// pretend we've connected both to a server at this p=
oint
<=
/a>//s1 =3D socket(...);
<=
/a>//s2 =3D socket(...);
<=
/a>//connect(s1, ...)...
//connect(s2, ...)...

// clear the set ahead of time
FD_ZERO(&readfds);

// add our descriptors to the set
FD_SET(s1, &readfds);
FD_SET(s2, &readfds);

// since we got s2 second, it's the "greater", so w=
e use that for
// the n param in select()
n =3D s2 + 1;

// wait until either socket has data ready to be re=
cv()d (timeout 10.5 secs)
tv.tv_sec =3D 10;
tv.tv_usec =3D 500000;
rv =3D select(n, &readfds, NULL, NULL, &tv);

if (rv =3D=3D -1) =
{
    perror("select"); // =
error occurred in select()
} else if (rv =3D=
=3D 0) {
    printf("Timeout occurred! No data after 10.5 se=
conds.\n");
} else {
    // one or both of the descriptors have data
    if (FD_ISSET(s1, &readfds)) {
        recv(s1, buf1, sizeof buf1, 0);
    }
    if (FD_ISSET(s2, &readfds)) {
        recv(s2, buf2, sizeof buf2, 0);
    }
}

9.19.0.5 See Also

poll()=

9.20 setsockopt(), getsockopt()

Set various options for a socket

9.20.0.1 Synopsis

    #include <sys/types.h>
    #include <sys/socket.h>
    
    int g=
etsockopt(int s, int le=
vel, int optname, void =
*optval,
                   socklen_t *optle=
n);
    int s=
etsockopt(int s, int le=
vel, int optname, const=
 void *optval,
                   socklen_t optlen=
);

9.20.0.2 Description

Sockets are fairly configurable beasts. In fact, they are so configura= ble, I=E2=80=99m not even going to cover it all here. It=E2=80=99s probably= system-dependent anyway. But I will talk about the basics.

Obviously, these functions get and set certain options on a socket. On a= Linux box, all the socket information is in the man page for socket in sec= tion 7. (Type: =E2=80=9Cman 7 socket=E2=80=9D to get all these= goodies.)

As for parameters, s is the socket you=E2=80=99re talking a= bout, level should be set to SOL_SOCKET. Then you set the optname to the name you=E2=80=99re interested in. Again, see your= man page for all the options, but here are some of the most fun ones:

optname Description
SO_BINDTODEVICE Bind this socket to a symbolic device name like eth0 inste= ad of using bind() to bind it to an IP address. Type the comma= nd ifconfig under Unix to see the device names.
SO_REUSEADDR Allows other sockets to bind() to this port, unless there = is an active listening socket bound to the port already. This enables you t= o get around those =E2=80=9CAddress already in use=E2=80=9D error messages = when you try to restart your server after a crash.
SOCK_DGRAM Allows UDP datagram (SOCK_DGRAM) sockets to send and rece= ive packets sent to and from the broadcast address. Does nothing=E2=80=94NOTHING!!=E2=80=94to TCP stream sockets! Hahaha!

As for the parameter optval, it=E2=80=99s usually a pointer= to an int indicating the value in question. For booleans, zer= o is false, and non-zero is true. And that=E2=80=99s an absolute fact, unle= ss it=E2=80=99s different on your system. If there is no parameter to be pa= ssed, optval can be NULL.

The final parameter, optlen, should be set to the length of= optval, probably sizeof(int), but varies dependi= ng on the option. Note that in the case of getsockopt(), this = is a pointer to a socklen_t, and it specifies the maximum size= object that will be stored in optval (to prevent buffer overf= lows). And getsockopt() will modify the value of optlen<= /code> to reflect the number of bytes actually set.

Warning: on some systems (notably Sun and Windows), = the option can be a char instead of an int, and i= s set to, for example, a character value of '1' instead of an = int value of 1. Again, check your own man pages f= or more info with =E2=80=9Cman setsockopt=E2=80=9D and =E2=80= =9Cman 7 socket=E2=80=9D!

9.20.0.3 Return Value

Returns zero on success, or -1 on error (and errno will be set accordingly).

9.20.0.4 Example

int optval;
<=
/a>int optlen;
<=
/a>char *optval2;
<=
/a>
<=
/a>// set SO_REUSEADDR on a socket to true (1):
<=
/a>optval =3D 1;
<=
/a>setsockopt(s1, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval);
<=
/a>
<=
/a>// bind a socket to a device name (might not work on =
all systems):
optval2 =3D "eth1"; // 4 =
bytes long, so 4, below:
setsockopt(s2, SOL_SOCKET, SO_BINDTODEVICE, optval2, 4);

// see if the SO_BROADCAST flag is set:
getsockopt(s3, SOL_SOCKET, SO_BROADCAST, &optval, &optlen);
if (optval !=3D 0)=
 {
    print("SO_BROADCAST enabled on s3!\n");
}

9.20.0.5 See Also

fcntl()

9.21 send(), sendto()

Send data out over a socket

9.21.0.1 Synopsis

    #include <sys/types.h>
    #include <sys/socket.h>
    
    ssize_t send(int s, const void *buf, size_t len, int flags);
    ssize_t sendto(int s, const =
void *buf, size_t len,<=
/span>
                   int flags, const str=
uct sockaddr *to,
                   socklen_t tolen)=
;

9.21.0.2 Description

These functions send data to a socket. Generally speaking, send(= ) is used for TCP SOCK_STREAM connected sockets, and <= code>sendto() is used for UDP SOCK_DGRAM unconnected d= atagram sockets. With the unconnected sockets, you must specify the destina= tion of a packet each time you send one, and that=E2=80=99s why the last pa= rameters of sendto() define where the packet is going.

With both send() and sendto(), the parameter <= code>s is the socket, buf is a pointer to the data you = want to send, len is the number of bytes you want to send, and= flags allows you to specify more information about how the da= ta is to be sent. Set flags to zero if you want it to be =E2= =80=9Cnormal=E2=80=9D data. Here are some of the commonly used flags, but c= heck your local send() man pages for more details:

Macro Description
MSG_OOB Send as =E2=80=9Cout of band=E2=80=9D data. TCP supports this, and it= =E2=80=99s a way to tell the receiving system that this data has a higher p= riority than the normal data. The receiver will receive the signal S= IGURG and it can then receive this data without first receiving all = the rest of the normal data in the queue.
MSG_DONTROUTE Don=E2=80=99t send this data over a router, just keep it local.
MSG_DONTWAIT If send() would block because outbound traffic is clogged,= have it return EAGAIN. This is like a =E2=80=9Cenable non-b= locking just for this send.=E2=80=9D See the section on blocking for more details.
MSG_NOSIGNAL If you send() to a remote host which is no longer re= cv()ing, you=E2=80=99ll typically get the signal SIGPIPE. Adding this flag prevents that signal from being raised.

9.21.0.3 Return Value

Returns the number of bytes actually sent, or -1 on error (= and errno will be set accordingly). Note that the number of by= tes actually sent might be less than the number you asked it to send! See t= he section on handling= partial send()s for a helper function to get around this.=

Also, if the socket has been closed by either side, the process calling = send() will get the signal SIGPIPE. (Unless send() was called with the MSG_NOSIGNAL flag.)

9.21.0.4 Example

int spatula_count =3D 3490;
<=
/a>char *secret_message =3D "T=
he Cheese is in The Toaster";
<=
/a>
<=
/a>int stream_socket, dgram_socket;
<=
/a>struct sockaddr_in dest;
<=
/a>int temp;
<=
/a>
<=
/a>// first with TCP stream sockets:
<=
/a>
// assume sockets are made and connected
//stream_socket =3D socket(...
//connect(stream_socket, ...

// convert to network byte order
temp =3D htonl(spatula_count);
// send data normally:
send(stream_socket, &temp, sizeof temp, =
0);

// send secret message out of band:
send(stream_socket, secret_message, strlen(secret_message)+1, MSG_OOB);

// now with UDP datagram sockets:
//getaddrinfo(...
//dest =3D ... // assume "dest" holds the address o=
f the destination
//dgram_socket =3D socket(...

// send secret message normally:
sendto(dgram_socket, secret_message, strlen(secret_message)+1, 0, 
       (struct sockaddr*)&dest, sizeof dest);

9.21.0.5 See Also

recv()= , recvfrom()=

9.22 shutdown()

Stop further sends and receives on a socket

9.22.0.1 Synopsis

    #include <sys/socket.h>
    
    int s=
hutdown(int s, int how)=
;

9.22.0.2 Description

That=E2=80=99s it! I=E2=80=99ve had it! No more send()s ar= e allowed on this socket, but I still want to recv() data on i= t! Or vice-versa! How can I do this?

When you close() a socket descriptor, it closes both sides = of the socket for reading and writing, and frees the socket descriptor. If = you just want to close one side or the other, you can use this shutdo= wn() call.

As for parameters, s is obviously the socket you want to pe= rform this action on, and what action that is can be specified with the how parameter. How can be SHUT_RD to prevent further= recv()s, SHUT_WR to prohibit further send(= )s, or SHUT_RDWR to do both.

Note that shutdown() doesn=E2=80=99t free up the socket des= criptor, so you still have to eventually close() the socket ev= en if it has been fully shut down.

This is a rarely used system call.

9.22.0.3 Return Value

Returns zero on success, or -1 on error (and errno will be set accordingly).

9.22.0.4 Example

9.22.0.5 See Also

close()

9.23 socket()

Allocate a socket descriptor

9.23.0.1 Synopsis

    #include <sys/types.h>
    #include <sys/socket.h>
    
    int s=
ocket(int domain, int t=
ype, int protocol);

9.23.0.2 Description

Returns a new socket descriptor that you can use to do sockety things w= ith. This is generally the first call in the whopping process of writing a = socket program, and you can use the result for subsequent calls to li= sten(), bind(), accept(), or a variety of = other functions.

In usual usage, you get the values for these parameters from a call to <= code>getaddrinfo(), as shown in the example below. But you can fill = them in by hand if you really want to.

Macro Description
domain domain describes what kind of socket you=E2=80=99re intere= sted in. This can, believe me, be a wide variety of things, but since this = is a socket guide, it=E2=80=99s going to be PF_INET for IPv4,= and PF_INET6 for IPv6.
type Also, the type parameter can be a number of things, but yo= u=E2=80=99ll probably be setting it to either SOCK_STREAM for= reliable TCP sockets (send(), recv()) or SOCK_DGRAM for unreliable fast UDP sockets (sendto(),= recvfrom()). (Another interesting socket type is SOCK_= RAW which can be used to construct packets by hand. It=E2=80=99s pre= tty cool.)
protocol Finally, the protocol parameter tells which protocol to us= e with a certain socket type. Like I=E2=80=99ve already said, for instance,= SOCK_STREAM uses TCP. Fortunately for you, when using S= OCK_STREAM or SOCK_DGRAM, you can just set the protocol= to 0, and it=E2=80=99ll use the proper protocol automatically. Otherwise, = you can use getprotobyname() to look up the proper protocol n= umber.

9.23.0.3 Return Value

The new socket descriptor to be used in subsequent calls, or -1 on error (and errno will be set accordingly).

9.23.0.4 Example

struct=
 addrinfo hints, *res;
<=
/a>int sockfd;
<=
/a>
<=
/a>// first, load up address structs with getaddrinfo():=

<=
/a>
<=
/a>memset(&hints, 0, sizeo=
f hints);
<=
/a>hints.ai_family =3D AF_UNSPEC;     // AF_INET, AF_INE=
T6, or AF_UNSPEC
<=
/a>hints.ai_socktype =3D SOCK_STREAM; // SOCK_STREAM or =
SOCK_DGRAM
<=
/a>
getaddrinfo("www.example.com", "3490", &hints, &res);

// make a socket using the information gleaned from=
 getaddrinfo():
sockfd =3D socket(res->ai_family, res->ai_socktype, res->ai_p=
rotocol);

9.23.0.5 See Also

accept(), bind()= , getaddrinfo(), listen()

9.24 struct sockaddr and pals

Structures for handling internet addresses

9.24.0.1 Synopsis

    #include <netinet/in.h>
    
    // All point=
ers to socket address structures are often cast to pointers
    // to this t=
ype before use in various functions and system calls:
    
    struct sockaddr {
        unsigned=
 short    sa_family;    // address family, AF_xxx
        char              sa_data[14];  // 14 bytes of protocol address
    };
    
    
    // IPv4 AF=
_INET sockets:
    
    struct sockaddr_in {
        short<=
/span>            sin_family;   // e.g. AF_INET, AF_INET=
6
        unsign=
ed short   sin_port;     // e.g. htons(3490)
        struct=
 in_addr   sin_addr;     // see struct in_addr, b=
elow
        char             sin_zero[8];  // zero this if you want to
    };
    
    struct in_addr {
        unsign=
ed long s_addr;          // load with inet_pton()
    };
    
    
    // IPv6 AF=
_INET6 sockets:
    
    struct sockaddr_in6 {
        u_int16_t       sin6_fami=
ly;   // address family, AF_INET6
        u_int16_t       sin6_port=
;     // port number, Network Byte Order
        u_int32_t       sin6_flow=
info; // IPv6 flow information
        struct=
 in6_addr sin6_addr;     // IPv6 address
        u_int32_t       sin6_scop=
e_id; // Scope ID
    };
    
    struct in6_addr {
        unsign=
ed char   s6_addr[16];   // load with inet_pton()
    };
    
    
    // General=
 socket address holding structure, big enough to hold either
    // struct =
sockaddr_in or struct sockaddr_in6 data:
    
    struct sockaddr_storage {
        sa_family_t  ss_family;  =
   // address family
    
        // all=
 this is padding, implementation specific, ignore it:
        char      __ss_pad1[_SS_PAD1SIZE];
        int64_=
t   __ss_align;
        char      __ss_pad2[_SS_PAD2SIZE];
    };

9.24.0.2 Description

These are the basic structures for all syscalls and functions that dea= l with internet addresses. Often you=E2=80=99ll use getaddrinfo() to fill these structures out, and then will read them when you have to.=

In memory, the struct sockaddr_in and struct sockaddr= _in6 share the same beginning structure as struct sockaddr, and you can freely cast the pointer of one type to the other without = any harm, except the possible end of the universe.

Just kidding on that end-of-the-universe thing=E2=80=A6if the universe d= oes end when you cast a struct sockaddr_in* to a struct = sockaddr*, I promise you it=E2=80=99s pure coincidence and you shoul= dn=E2=80=99t even worry about it.

So, with that in mind, remember that whenever a function says it takes a= struct sockaddr* you can cast your struct sockaddr_in*<= /code>, struct sockaddr_in6*, or struct sockadd_storage*= to that type with ease and safety.

struct sockaddr_in is the structure used with IPv4 addresse= s (e.g. =E2=80=9C192.0.2.10=E2=80=9D). It holds an address family (AF= _INET), a port in sin_port, and an IPv4 address in sin_addr.

There=E2=80=99s also this sin_zero field in struct so= ckaddr_in which some people claim must be set to zero. Other people = don=E2=80=99t claim anything about it (the Linux documentation doesn=E2=80= =99t even mention it at all), and setting it to zero doesn=E2=80=99t seem t= o be actually necessary. So, if you feel like it, set it to zero using memset().

Now, that struct in_addr is a weird beast on different syst= ems. Sometimes it=E2=80=99s a crazy union with all kinds of #defines and other nonsense. But what you should do is only use = the s_addr field in this structure, because many systems only = implement that one.

struct sockadd_in6 and struct in6_addr are ver= y similar, except they=E2=80=99re used for IPv6.

struct sockaddr_storage is a struct you can pass to a= ccept() or recvfrom() when you=E2=80=99re trying to wri= te IP version-agnostic code and you don=E2=80=99t know if the new address i= s going to be IPv4 or IPv6. The struct sockaddr_storage struct= ure is large enough to hold both types, unlike the original small str= uct sockaddr.

9.24.0.3 Example

9.24.0.4 See Also

accept(), bind()= , = connect(), inet_aton(), inet_ntoa()

10 More References

You=E2=80=99ve come this far, and now you=E2=80=99re screaming for more!= Where else can you go to learn more about all this stuff?

10.1 Books

For old-school actual hold-it-in-your-hand pulp paper books, try some = of the following excellent books. These redirect to affiliate links with a = popular bookseller, giving me nice kickbacks. If you=E2=80=99re merely feel= ing generous, you can paypal a donation to = beej@beej.us. :-)

Unix Network Programming, volumes 1-2 by W. Richard Ste= vens. Published by Addison-Wesley Professional and Prentice Hall. ISBNs for= volumes 1-2: 978-0131411555= 49, 978-013081081650.

Internetworking with TCP/IP, volume I by Douglas E. Com= er. Published by Pearson. ISBN 978-013608530051.<= /p>

TCP/IP Illustrated, volumes 1-3 by W. Richard Stevens a= nd Gary R. Wright. Published by Addison Wesley. ISBNs for volumes 1, 2, and= 3 (and a 3-volume set): 978-02= 0163346752, 978-020163354253, 9= 78-020163495254, (978-020177631755).

TCP/IP Network Administration by Craig Hunt. Published = by O=E2=80=99Reilly & Associates, Inc. ISBN 978-05960029785= 6.

Advanced Programming in the UNIX Environment by W. Rich= ard Stevens. Published by Addison Wesley. ISBN 978-0321637734= 57.

10.2 Web References

On the web:

BSD Sockets: A Quick And Dirty Primer58 (Unix system programming in= fo, too!)

The Unix Socket FAQ= 59

TCP/IP FAQ60

The Winsock FAQ<= a href=3D"http://beej.us/guide/bgnet/html/#fn61" class=3D"footnote-ref" id= =3D"fnref61" role=3D"doc-noteref">61

And here are some relevant Wikipedia pages:

Berke= ley Sockets62=

Inte= rnet Protocol (IP)63

Transmission Control Protocol (TCP)64

User Datagram Protocol (UDP)65<= /sup>

Client-S= erver66

Serializ= ation67 (pack= ing and unpacking data)

= 10.3 RFCs

RFCs68=E2=80=94the real dirt! These are documents that= describe assigned numbers, programming APIs, and protocols that are used o= n the Internet. I=E2=80=99ve included links to a few of them here for your = enjoyment, so grab a bucket of popcorn and put on your thinking cap:

RFC 169 =E2=80=94The First RFC; = this gives you an idea of what the =E2=80=9CInternet=E2=80=9D was like just= as it was coming to life, and an insight into how it was being designed fr= om the ground up. (This RFC is completely obsolete, obviously!)

RFC 76870 =E2=80=94The User D= atagram Protocol (UDP)

RFC 79171 =E2=80=94The Intern= et Protocol (IP)

RFC 79372 =E2=80=94The Transm= ission Control Protocol (TCP)

RFC 85473 =E2=80=94The Telnet= Protocol

RFC 95974 =E2=80=94File Trans= fer Protocol (FTP)

RFC 135075 =E2=80=94The Triv= ial File Transfer Protocol (TFTP)

RFC 145976 =E2=80=94Internet= Relay Chat Protocol (IRC)

RFC 191877 =E2=80=94Address A= llocation for Private Internets

RFC 213178 =E2=80=94Dynamic = Host Configuration Protocol (DHCP)

RFC 261679 =E2=80=94Hypertex= t Transfer Protocol (HTTP)

RFC 282180 =E2=80=94Simple M= ail Transfer Protocol (SMTP)

RFC 333081 =E2=80=94Special-U= se IPv4 Addresses

RFC 349382 =E2=80=94Basic Soc= ket Interface Extensions for IPv6

RFC 354283 =E2=80=94Advanced = Sockets Application Program Interface (API) for IPv6

RFC 384984 =E2=80=94IPv6 Addr= ess Prefix Reserved for Documentation

RFC 392085 =E2=80=94Extensib= le Messaging and Presence Protocol (XMPP)

RFC 397786 =E2=80=94Network = News Transfer Protocol (NNTP)

RFC 419387 =E2=80=94Unique Lo= cal IPv6 Unicast Addresses

RFC 450688 =E2=80=94External= Data Representation Standard (XDR)

The IETF has a nice online tool for searching and browsing RFCs8= 9.


  1. https://www.linux.com/=E2=86=A9=EF=B8=8E

  2. https://bsd.org/=E2=86=A9=EF=B8=8E

  3. https://cygwin.com/=E2=86=A9=EF=B8=8E

  4. https://docs.microsoft.com/en-us/win= dows/wsl/about=E2=86=A9=EF=B8=8E

  5. https://tangentsoft.net/wskfaq/=E2=86=A9=EF=B8=8E

  6. http://www.catb.org/~esr/faqs/smart-= questions.html=E2=86=A9=EF=B8=8E

  7. https://beej.us/guide/bgnet/examples= /telnot.c=E2=86=A9=EF=B8=8E

  8. https://tools.ietf.org/html/rfc854=E2=86=A9=EF=B8=8E

  9. https://tools.ietf.org/html/rfc793=E2=86=A9=EF=B8=8E

  10. https://tools.ietf.org/html/rfc791<= a href=3D"http://beej.us/guide/bgnet/html/#fnref10" class=3D"footnote-back"= role=3D"doc-backlink">=E2=86=A9=EF=B8=8E

  11. https://tools.ietf.org/html/rfc768<= a href=3D"http://beej.us/guide/bgnet/html/#fnref11" class=3D"footnote-back"= role=3D"doc-backlink">=E2=86=A9=EF=B8=8E

  12. https://tools.ietf.org/html/rfc791<= a href=3D"http://beej.us/guide/bgnet/html/#fnref12" class=3D"footnote-back"= role=3D"doc-backlink">=E2=86=A9=EF=B8=8E

  13. https://en.wikipedia.org/wiki/Vint_= Cerf=E2=86=A9=EF=B8=8E

  14. https://en.wikipedia.org/wiki/ELIZA= =E2=86=A9=EF=B8=8E

  15. https://www.iana.org/assignments/po= rt-numbers=E2=86=A9=EF=B8=8E

  16. https://en.wikipedia.org/wiki/Doom_= (1993_video_game)=E2=86=A9=EF=B8=8E

  17. https://en.wikipedia.org/wiki/Wilfo= rd_Brimley=E2=86=A9=EF=B8=8E

  18. https://tools.ietf.org/html/rfc1918= =E2=86=A9=EF=B8=8E

  19. https://tools.ietf.org/html/rfc4193= =E2=86=A9=EF=B8=8E

  20. https://www.iana.org/assignments/po= rt-numbers=E2=86=A9=EF=B8=8E

  21. https://beej.us/guide/bgnet/example= s/showip.c=E2=86=A9=EF=B8=8E

  22. https://tools.ietf.org/html/rfc1413= =E2=86=A9=EF=B8=8E

  23. https://beej.us/guide/bgnet/example= s/server.c=E2=86=A9=EF=B8=8E

  24. https://beej.us/guide/bgnet/example= s/client.c=E2=86=A9=EF=B8=8E

  25. https://beej.us/guide/bgnet/example= s/listener.c=E2=86=A9=EF=B8=8E

  26. https://beej.us/guide/bgnet/example= s/talker.c=E2=86=A9=EF=B8=8E

  27. https://libevent.org/=E2=86=A9=EF=B8=8E

  28. https://beej.us/guide/bgnet/example= s/poll.c=E2=86=A9=EF=B8=8E

  29. https://beej.us/guide/bgnet/example= s/pollserver.c=E2=86=A9=EF=B8=8E

  30. https://libevent.org/=E2=86=A9=EF=B8=8E

  31. https://beej.us/guide/bgnet/example= s/select.c=E2=86=A9=EF=B8=8E

  32. https://beej.us/guide/bgnet/example= s/selectserver.c=E2=86=A9=EF=B8=8E

  33. https://en.wikipedia.org/wiki/Inter= net_Relay_Chat=E2=86=A9=EF=B8=8E

  34. https://beej.us/guide/bgnet/example= s/pack.c=E2=86=A9=EF=B8=8E

  35. https://en.wikipedia.org/wiki/IEEE_= 754=E2=86=A9=EF=B8=8E

  36. https://beej.us/guide/bgnet/example= s/ieee754.c=E2=86=A9=EF=B8=8E

  37. https://beej.us/guide/url/tpop=E2=86=A9=EF=B8=8E

  38. https://github.com/protobuf-c/proto= buf-c=E2=86=A9=EF=B8=8E

  39. https://beej.us/guide/bgnet/example= s/pack2.c=E2=86=A9=EF=B8=8E

  40. https://beej.us/guide/bgnet/example= s/pack2.c=E2=86=A9=EF=B8=8E

  41. https://tools.ietf.org/html/rfc4506= =E2=86=A9=EF=B8=8E

  42. https://beej.us/guide/bgnet/example= s/broadcaster.c=E2=86=A9=EF=B8=8E

  43. http://www.unpbook.com/src.html=E2=86=A9=EF=B8=8E

  44. http://www.unpbook.com/src.html=E2=86=A9=EF=B8=8E

  45. https://www.openssl.org/=E2=86=A9=EF=B8=8E

  46. https://stackoverflow.com/questions= /21323023/=E2=86=A9=EF=B8=8E

  47. https://www.iana.org/assignments/po= rt-numbers=E2=86=A9=EF=B8=8E

  48. https://www.iana.org/assignments/po= rt-numbers=E2=86=A9=EF=B8=8E

  49. https://beej.us/guide/url/unixnet1<= a href=3D"http://beej.us/guide/bgnet/html/#fnref49" class=3D"footnote-back"= role=3D"doc-backlink">=E2=86=A9=EF=B8=8E

  50. https://beej.us/guide/url/unixnet2<= a href=3D"http://beej.us/guide/bgnet/html/#fnref50" class=3D"footnote-back"= role=3D"doc-backlink">=E2=86=A9=EF=B8=8E

  51. https://beej.us/guide/url/intertcp1= =E2=86=A9=EF=B8=8E

  52. https://beej.us/guide/url/tcpi1=E2=86=A9=EF=B8=8E

  53. https://beej.us/guide/url/tcpi2=E2=86=A9=EF=B8=8E

  54. https://beej.us/guide/url/tcpi3=E2=86=A9=EF=B8=8E

  55. https://beej.us/guide/url/tcpi123=E2=86=A9=EF=B8=8E

  56. https://beej.us/guide/url/tcpna=E2=86=A9=EF=B8=8E

  57. https://beej.us/guide/url/advunix=E2=86=A9=EF=B8=8E

  58. https://cis.temple.edu/~giorgio/old= /cis307s96/readings/docs/sockets.html=E2=86=A9=EF= =B8=8E

  59. https://developerweb.net/?f=3D70=E2=86=A9=EF=B8=8E

  60. http://www.faqs.org/faqs/internet/t= cp-ip/tcp-ip-faq/part1/=E2=86=A9=EF=B8=8E

  61. https://tangentsoft.net/wskfaq/=E2=86=A9=EF=B8=8E

  62. https://en.wikipedia.org/wiki/Berke= ley_sockets=E2=86=A9=EF=B8=8E

  63. https://en.wikipedia.org/wiki/Inter= net_Protocol=E2=86=A9=EF=B8=8E

  64. https://en.wikipedia.org/wiki/Trans= mission_Control_Protocol=E2=86=A9=EF=B8=8E

    <= /li>
  65. https://en.wikipedia.org/wiki/User_= Datagram_Protocol=E2=86=A9=EF=B8=8E

  66. https://en.wikipedia.org/wiki/Clien= t-server=E2=86=A9=EF=B8=8E

  67. https://en.wikipedia.org/wiki/Seria= lization=E2=86=A9=EF=B8=8E

  68. https://www.rfc-editor.org/=E2=86=A9=EF=B8=8E

  69. https://tools.ietf.org/html/rfc1=E2=86=A9=EF=B8=8E

  70. https://tools.ietf.org/html/rfc768<= a href=3D"http://beej.us/guide/bgnet/html/#fnref70" class=3D"footnote-back"= role=3D"doc-backlink">=E2=86=A9=EF=B8=8E

  71. https://tools.ietf.org/html/rfc791<= a href=3D"http://beej.us/guide/bgnet/html/#fnref71" class=3D"footnote-back"= role=3D"doc-backlink">=E2=86=A9=EF=B8=8E

  72. https://tools.ietf.org/html/rfc793<= a href=3D"http://beej.us/guide/bgnet/html/#fnref72" class=3D"footnote-back"= role=3D"doc-backlink">=E2=86=A9=EF=B8=8E

  73. https://tools.ietf.org/html/rfc854<= a href=3D"http://beej.us/guide/bgnet/html/#fnref73" class=3D"footnote-back"= role=3D"doc-backlink">=E2=86=A9=EF=B8=8E

  74. https://tools.ietf.org/html/rfc959<= a href=3D"http://beej.us/guide/bgnet/html/#fnref74" class=3D"footnote-back"= role=3D"doc-backlink">=E2=86=A9=EF=B8=8E

  75. https://tools.ietf.org/html/rfc1350= =E2=86=A9=EF=B8=8E

  76. https://tools.ietf.org/html/rfc1459= =E2=86=A9=EF=B8=8E

  77. https://tools.ietf.org/html/rfc1918= =E2=86=A9=EF=B8=8E

  78. https://tools.ietf.org/html/rfc2131= =E2=86=A9=EF=B8=8E

  79. https://tools.ietf.org/html/rfc2616= =E2=86=A9=EF=B8=8E

  80. https://tools.ietf.org/html/rfc2821= =E2=86=A9=EF=B8=8E

  81. https://tools.ietf.org/html/rfc3330= =E2=86=A9=EF=B8=8E

  82. https://tools.ietf.org/html/rfc3493= =E2=86=A9=EF=B8=8E

  83. https://tools.ietf.org/html/rfc3542= =E2=86=A9=EF=B8=8E

  84. https://tools.ietf.org/html/rfc3849= =E2=86=A9=EF=B8=8E

  85. https://tools.ietf.org/html/rfc3920= =E2=86=A9=EF=B8=8E

  86. https://tools.ietf.org/html/rfc3977= =E2=86=A9=EF=B8=8E

  87. https://tools.ietf.org/html/rfc4193= =E2=86=A9=EF=B8=8E

  88. https://tools.ietf.org/html/rfc4506= =E2=86=A9=EF=B8=8E

  89. https://tools.ietf.org/rfc/=E2=86=A9=EF=B8=8E

3D"Google

Origi= nal text

Contribute a = better translation

------MultipartBoundary--Ed8mr4hq2PkKv7UclxPAzEF7J8M75erKKbPS2p3d0i---- Content-Type: text/css Content-Transfer-Encoding: quoted-printable Content-Location: cid:css-75488a59-b8bd-4b05-96c4-a573b4b11f55@mhtml.blink @charset "utf-8"; html { line-height: 1.5; font-family: Georgia, serif; font-size: 20px; colo= r: rgb(26, 26, 26); background-color: rgb(253, 253, 253); } body { margin: 0px auto; max-width: 36em; padding: 50px; hyphens: auto; ove= rflow-wrap: break-word; text-rendering: optimizelegibility; font-kerning: n= ormal; } @media (max-width: 600px) { body { font-size: 0.9em; padding: 1em; } } @media print { body { background-color: transparent; color: black; font-size: 12pt; } p, h2, h3 { orphans: 3; widows: 3; } h2, h3, h4 { break-after: avoid; } } p { margin: 1em 0px; } a { color: rgb(26, 26, 26); } a:visited { color: rgb(26, 26, 26); } img { max-width: 100%; } h1, h2, h3, h4, h5, h6 { margin-top: 1.4em; } h5, h6 { font-size: 1em; font-style: italic; } h6 { font-weight: normal; } ol, ul { padding-left: 1.7em; margin-top: 1em; } li > ol, li > ul { margin-top: 0px; } blockquote { margin: 1em 0px 1em 1.7em; padding-left: 1em; border-left: 2px= solid rgb(230, 230, 230); color: rgb(96, 96, 96); } code { font-family: Menlo, Monaco, "Lucida Console", Consolas, monospace; f= ont-size: 85%; margin: 0px; } pre { margin: 1em 0px; overflow: auto; } pre code { padding: 0px; overflow: visible; } .sourceCode { background-color: transparent; overflow: visible; } hr { background-color: rgb(26, 26, 26); border: none; height: 1px; margin: = 1em 0px; } table { margin: 1em 0px; 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 rgb(26, 26, 26); border-bo= ttom: 1px solid rgb(26, 26, 26); } th { border-top: 1px solid rgb(26, 26, 26); padding: 0.25em 0.5em; } td { padding: 0.125em 0.5em 0.25em; } header { margin-bottom: 4em; text-align: center; } #TOC li { list-style: none; } #TOC a:not(:hover) { text-decoration: none; } code { white-space: pre-wrap; } span.smallcaps { font-variant: small-caps; } span.underline { text-decoration: underline; } div.column { display: inline-block; vertical-align: top; width: 50%; } div.hanging-indent { margin-left: 1.5em; text-indent: -1.5em; } ul.task-list { list-style: none; } pre > code.sourceCode { white-space: pre; position: relative; } pre > code.sourceCode > span { display: inline-block; line-height: 1.25; } pre > code.sourceCode > span:empty { height: 1.2em; } code.sourceCode > span { color: inherit; text-decoration: inherit; } div.sourceCode { margin: 1em 0px; } pre.sourceCode { margin: 0px; } @media screen { div.sourceCode { overflow: auto; } } @media print { pre > code.sourceCode { white-space: pre-wrap; } pre > code.sourceCode > span { text-indent: -5em; padding-left: 5em; } } pre.numberSource code { counter-reset: source-line 0; } pre.numberSource code > span { position: relative; left: -4em; counter-incr= ement: source-line 1; } pre.numberSource code > span > a:first-child::before { content: counter(sou= rce-line); position: relative; left: -1em; text-align: right; vertical-alig= n: baseline; border: none; display: inline-block; user-select: none; paddin= g: 0px 4px; width: 4em; color: rgb(170, 170, 170); } pre.numberSource { margin-left: 3em; border-left: 1px solid rgb(170, 170, 1= 70); padding-left: 4px; } div.sourceCode { } @media screen { pre > code.sourceCode > span > a:first-child::before { text-decoration: u= nderline; } } code span.al { color: rgb(255, 0, 0); font-weight: bold; } code span.an { color: rgb(96, 160, 176); font-weight: bold; font-style: ita= lic; } code span.at { color: rgb(125, 144, 41); } code span.bn { color: rgb(64, 160, 112); } code span.bu { } code span.cf { color: rgb(0, 112, 32); font-weight: bold; } code span.ch { color: rgb(64, 112, 160); } code span.cn { color: rgb(136, 0, 0); } code span.co { color: rgb(96, 160, 176); font-style: italic; } code span.cv { color: rgb(96, 160, 176); font-weight: bold; font-style: ita= lic; } code span.do { color: rgb(186, 33, 33); font-style: italic; } code span.dt { color: rgb(144, 32, 0); } code span.dv { color: rgb(64, 160, 112); } code span.er { color: rgb(255, 0, 0); font-weight: bold; } code span.ex { } code span.fl { color: rgb(64, 160, 112); } code span.fu { color: rgb(6, 40, 126); } code span.im { } code span.in { color: rgb(96, 160, 176); font-weight: bold; font-style: ita= lic; } code span.kw { color: rgb(0, 112, 32); font-weight: bold; } code span.op { color: rgb(102, 102, 102); } code span.ot { color: rgb(0, 112, 32); } code span.pp { color: rgb(188, 122, 0); } code span.sc { color: rgb(64, 112, 160); } code span.ss { color: rgb(187, 102, 136); } code span.st { color: rgb(64, 112, 160); } code span.va { color: rgb(25, 23, 124); } code span.vs { color: rgb(64, 112, 160); } code span.wa { color: rgb(96, 160, 176); font-weight: bold; font-style: ita= lic; } ------MultipartBoundary--Ed8mr4hq2PkKv7UclxPAzEF7J8M75erKKbPS2p3d0i---- Content-Type: text/css Content-Transfer-Encoding: quoted-printable Content-Location: cid:css-e4c7c85a-3007-44b0-ba64-826d5f67cae5@mhtml.blink @charset "utf-8"; pre.numberSource code > span { left: -1em; } pre.numberSource { margin-left: initial; } span.toc-section-number::after { content: "=C2=A0=C2=A0=C2=A0"; } pre > code.sourceCode > span > a:first-child::before { text-decoration: non= e; } tbody code { white-space: nowrap; } ------MultipartBoundary--Ed8mr4hq2PkKv7UclxPAzEF7J8M75erKKbPS2p3d0i---- Content-Type: text/css Content-Transfer-Encoding: quoted-printable Content-Location: cid:css-bead104f-1cae-46f0-b4a4-07eeedfaad7e@mhtml.blink @charset "utf-8"; body, .edition2 p, .content-wrapper .content { font-family: Merriweather, P= anton-RegularX, "SF Compact Rounded", Nunito, Montserrat, "Trebuchet MS", "= Open sans", "Lantinghei SC"; } pre, code, #json *, kbd, code *, pre * { line-height: 1.3em; font-family: C= onsolas, "Source Code Pro", Menlo !important; } .property:not(.token) { color: black !important; } #json { font-size: 14px; } b, strong { font-weight: 500; } #ad, .ad, #sidebar-sponsors-special, .adblock, .adsbygoogle { display: none= !important; } ------MultipartBoundary--Ed8mr4hq2PkKv7UclxPAzEF7J8M75erKKbPS2p3d0i---- Content-Type: text/css Content-Transfer-Encoding: quoted-printable Content-Location: https://fonts.googleapis.com/css?family=Roboto|Roboto+Mono&display=swap @charset "utf-8"; @font-face { font-family: Roboto; font-style: normal; font-weight: 400; fon= t-display: swap; src: url("https://fonts.gstatic.com/s/roboto/v29/KFOmCnqEu= 92Fr1Mu72xKKTU1Kvnz.woff2") format("woff2"); unicode-range: U+460-52F, U+1C= 80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; } @font-face { font-family: Roboto; font-style: normal; font-weight: 400; fon= t-display: swap; src: url("https://fonts.gstatic.com/s/roboto/v29/KFOmCnqEu= 92Fr1Mu5mxKKTU1Kvnz.woff2") format("woff2"); unicode-range: U+400-45F, U+49= 0-491, U+4B0-4B1, U+2116; } @font-face { font-family: Roboto; font-style: normal; font-weight: 400; fon= t-display: swap; src: url("https://fonts.gstatic.com/s/roboto/v29/KFOmCnqEu= 92Fr1Mu7mxKKTU1Kvnz.woff2") format("woff2"); unicode-range: U+1F00-1FFF; } @font-face { font-family: Roboto; font-style: normal; font-weight: 400; fon= t-display: swap; src: url("https://fonts.gstatic.com/s/roboto/v29/KFOmCnqEu= 92Fr1Mu4WxKKTU1Kvnz.woff2") format("woff2"); unicode-range: U+370-3FF; } @font-face { font-family: Roboto; font-style: normal; font-weight: 400; fon= t-display: swap; src: url("https://fonts.gstatic.com/s/roboto/v29/KFOmCnqEu= 92Fr1Mu7WxKKTU1Kvnz.woff2") format("woff2"); unicode-range: U+102-103, U+11= 0-111, U+128-129, U+168-169, U+1A0-1A1, U+1AF-1B0, U+1EA0-1EF9, U+20AB; } @font-face { font-family: Roboto; font-style: normal; font-weight: 400; fon= t-display: swap; src: url("https://fonts.gstatic.com/s/roboto/v29/KFOmCnqEu= 92Fr1Mu7GxKKTU1Kvnz.woff2") format("woff2"); unicode-range: U+100-24F, U+25= 9, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A7= 20-A7FF; } @font-face { font-family: Roboto; font-style: normal; font-weight: 400; fon= t-display: swap; src: url("https://fonts.gstatic.com/s/roboto/v29/KFOmCnqEu= 92Fr1Mu4mxKKTU1Kg.woff2") format("woff2"); unicode-range: U+0-FF, U+131, U+= 152-153, U+2BB-2BC, U+2C6, U+2DA, U+2DC, U+2000-206F, U+2074, U+20AC, U+212= 2, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; } @font-face { font-family: "Roboto Mono"; font-style: normal; font-weight: 4= 00; font-display: swap; src: url("https://fonts.gstatic.com/s/robotomono/v1= 3/L0xuDF4xlVMF-BfR8bXMIhJHg45mwgGEFl0_3vq_SeW-AJi8SJQtQ4Y.woff") format("wo= ff"); unicode-range: U+460-52F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A6= 9F, U+FE2E-FE2F; } @font-face { font-family: "Roboto Mono"; font-style: normal; font-weight: 4= 00; font-display: swap; src: url("https://fonts.gstatic.com/s/robotomono/v1= 3/L0xuDF4xlVMF-BfR8bXMIhJHg45mwgGEFl0_3vq_QOW-AJi8SJQtQ4Y.woff") format("wo= ff"); unicode-range: U+400-45F, U+490-491, U+4B0-4B1, U+2116; } @font-face { font-family: "Roboto Mono"; font-style: normal; font-weight: 4= 00; font-display: swap; src: url("https://fonts.gstatic.com/s/robotomono/v1= 3/L0xuDF4xlVMF-BfR8bXMIhJHg45mwgGEFl0_3vq_R-W-AJi8SJQtQ4Y.woff") format("wo= ff"); unicode-range: U+370-3FF; } @font-face { font-family: "Roboto Mono"; font-style: normal; font-weight: 4= 00; font-display: swap; src: url("https://fonts.gstatic.com/s/robotomono/v1= 3/L0xuDF4xlVMF-BfR8bXMIhJHg45mwgGEFl0_3vq_S-W-AJi8SJQtQ4Y.woff") format("wo= ff"); unicode-range: U+102-103, U+110-111, U+128-129, U+168-169, U+1A0-1A1,= U+1AF-1B0, U+1EA0-1EF9, U+20AB; } @font-face { font-family: "Roboto Mono"; font-style: normal; font-weight: 4= 00; font-display: swap; src: url("https://fonts.gstatic.com/s/robotomono/v1= 3/L0xuDF4xlVMF-BfR8bXMIhJHg45mwgGEFl0_3vq_SuW-AJi8SJQtQ4Y.woff") format("wo= ff"); unicode-range: U+100-24F, U+259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+= 20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; } @font-face { font-family: "Roboto Mono"; font-style: normal; font-weight: 4= 00; font-display: swap; src: url("https://fonts.gstatic.com/s/robotomono/v1= 3/L0xuDF4xlVMF-BfR8bXMIhJHg45mwgGEFl0_3vq_ROW-AJi8SJQt.woff") format("woff"= ); unicode-range: U+0-FF, U+131, U+152-153, U+2BB-2BC, U+2C6, U+2DA, U+2DC,= U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEF= F, U+FFFD; } ------MultipartBoundary--Ed8mr4hq2PkKv7UclxPAzEF7J8M75erKKbPS2p3d0i---- Content-Type: text/css Content-Transfer-Encoding: quoted-printable Content-Location: https://translate.googleapis.com/translate_static/css/translateelement.css @charset "utf-8"; .goog-te-banner-frame { left: 0px; top: 0px; height: 39px; width: 100%; z-i= ndex: 10000001; position: fixed; border-top: none; border-right: none; bord= er-left: none; border-image: initial; border-bottom: 1px solid rgb(107, 144= , 218); margin: 0px; box-shadow: rgb(153, 153, 153) 0px 0px 8px 1px; } .goog-te-menu-frame { z-index: 10000002; position: fixed; border: none; box= -shadow: rgb(153, 153, 153) 0px 3px 8px 2px; } .goog-te-ftab-frame { z-index: 10000000; border: none; margin: 0px; } .goog-te-gadget { font-family: arial; font-size: 11px; color: rgb(102, 102,= 102); white-space: nowrap; } .goog-te-gadget img { vertical-align: middle; border: none; } .goog-te-gadget-simple { background-color: rgb(255, 255, 255); border-width= : 1px; border-style: solid; border-color: rgb(155, 155, 155) rgb(213, 213, = 213) rgb(232, 232, 232); font-size: 10pt; display: inline-block; padding-to= p: 1px; padding-bottom: 2px; cursor: pointer; zoom: 1; } .goog-te-gadget-icon { margin-left: 2px; margin-right: 2px; width: 19px; he= ight: 19px; border: none; vertical-align: middle; } .goog-te-combo { margin-left: 4px; margin-right: 4px; vertical-align: basel= ine; } .goog-te-gadget .goog-te-combo { margin: 4px 0px; } .goog-logo-link, .goog-logo-link:link, .goog-logo-link:visited, .goog-logo-= link:hover, .goog-logo-link:active { font-size: 12px; font-weight: bold; co= lor: rgb(68, 68, 68); text-decoration: none; } .goog-te-banner .goog-logo-link, .goog-close-link { display: block; margin:= 0px 10px; } .goog-te-banner .goog-logo-link { padding-top: 2px; padding-left: 4px; } .goog-te-combo, .goog-te-banner *, .goog-te-ftab *, .goog-te-menu *, .goog-= te-menu2 *, .goog-te-balloon * { font-family: arial; font-size: 10pt; } .goog-te-banner { margin: 0px; background-color: rgb(228, 239, 251); overfl= ow: hidden; } .goog-te-banner img { border: none; } .goog-te-banner-content { color: rgb(0, 0, 0); } .goog-te-banner-content img { vertical-align: middle; } .goog-te-banner-info { color: rgb(102, 102, 102); vertical-align: top; marg= in-top: 0px; font-size: 7pt; } .goog-te-banner-margin { width: 8px; } .goog-te-button { border-color: rgb(231, 231, 231); border-style: none soli= d solid none; border-width: 0px 1px 1px 0px; } .goog-te-button div { border-color: rgb(204, 204, 204) rgb(153, 153, 153) r= gb(153, 153, 153) rgb(204, 204, 204); border-style: solid; border-width: 1p= x; height: 20px; } .goog-te-button button { background: transparent; border: none; cursor: poi= nter; height: 20px; overflow: hidden; margin: 0px; vertical-align: top; whi= te-space: nowrap; } .goog-te-button button:active { background: none 0px 0px repeat scroll rgb(= 204, 204, 204); } .goog-te-ftab { margin: 0px; background-color: rgb(255, 255, 255); white-sp= ace: nowrap; } .goog-te-ftab-link { text-decoration: none; font-weight: bold; font-size: 1= 0pt; border: 1px outset rgb(136, 136, 136); padding: 6px 10px; white-space:= nowrap; position: absolute; left: 0px; top: 0px; } .goog-te-ftab-link img { margin-left: 2px; margin-right: 2px; width: 19px; = height: 19px; border: none; vertical-align: middle; } .goog-te-ftab-link span { text-decoration: underline; margin-left: 2px; mar= gin-right: 2px; vertical-align: middle; } .goog-float-top .goog-te-ftab-link { padding: 2px; border-top-width: 0px; } .goog-float-bottom .goog-te-ftab-link { padding: 2px; border-bottom-width: = 0px; } .goog-te-menu-value { text-decoration: none; color: rgb(0, 0, 204); white-s= pace: nowrap; margin-left: 4px; margin-right: 4px; } .goog-te-menu-value span { text-decoration: underline; } .goog-te-menu-value img { margin-left: 2px; margin-right: 2px; } .goog-te-gadget-simple .goog-te-menu-value { color: rgb(0, 0, 0); } .goog-te-gadget-simple .goog-te-menu-value span { text-decoration: none; } .goog-te-menu { background-color: rgb(255, 255, 255); text-decoration: none= ; border: 2px solid rgb(195, 217, 255); overflow: hidden scroll; position: = absolute; left: 0px; top: 0px; } .goog-te-menu-item { padding: 3px; text-decoration: none; } .goog-te-menu-item, .goog-te-menu-item:link { color: rgb(0, 0, 204); backgr= ound: rgb(255, 255, 255); } .goog-te-menu-item:visited { color: rgb(85, 26, 139); } .goog-te-menu-item:hover { background: rgb(195, 217, 255); } .goog-te-menu-item:active { color: rgb(0, 0, 204); } .goog-te-menu2 { background-color: rgb(255, 255, 255); text-decoration: non= e; border: 1px solid rgb(107, 144, 218); overflow: hidden; padding: 4px; } .goog-te-menu2-colpad { width: 16px; } .goog-te-menu2-separator { margin: 6px 0px; height: 1px; background-color: = rgb(170, 170, 170); overflow: hidden; } .goog-te-menu2-item div, .goog-te-menu2-item-selected div { padding: 4px; } .goog-te-menu2-item .indicator { display: none; } .goog-te-menu2-item-selected .indicator { } .goog-te-menu2-item-selected .text { padding-left: 4px; padding-right: 4px;= } .goog-te-menu2-item, .goog-te-menu2-item-selected { text-decoration: none; = } .goog-te-menu2-item div, .goog-te-menu2-item:link div, .goog-te-menu2-item:= visited div, .goog-te-menu2-item:active div { color: rgb(0, 0, 204); backgr= ound: rgb(255, 255, 255); } .goog-te-menu2-item:hover div { color: rgb(255, 255, 255); background: rgb(= 51, 102, 204); } .goog-te-menu2-item-selected div, .goog-te-menu2-item-selected:link div, .g= oog-te-menu2-item-selected:visited div, .goog-te-menu2-item-selected:hover = div, .goog-te-menu2-item-selected:active div { color: rgb(0, 0, 0); font-we= ight: bold; } .goog-te-balloon { background-color: rgb(255, 255, 255); overflow: hidden; = padding: 8px; border: none; border-radius: 10px; } .goog-te-balloon-frame { background-color: rgb(255, 255, 255); border: 1px = solid rgb(107, 144, 218); box-shadow: rgb(153, 153, 153) 0px 3px 8px 2px; b= order-radius: 8px; } .goog-te-balloon img { border: none; } .goog-te-balloon-text { margin-top: 6px; } .goog-te-balloon-zippy { margin-top: 6px; white-space: nowrap; } .goog-te-balloon-zippy * { vertical-align: middle; } .goog-te-balloon-zippy .minus { background-image: url("//www.google.com/ima= ges/zippy_minus_sm.gif"); } .goog-te-balloon-zippy .plus { background-image: url("//www.google.com/imag= es/zippy_plus_sm.gif"); } .goog-te-balloon-zippy span { color: rgb(0, 0, 204); text-decoration: under= line; cursor: pointer; margin: 0px 4px; } .goog-te-balloon-form { margin: 6px 0px 0px; } .goog-te-balloon-form form { margin: 0px; } .goog-te-balloon-form form textarea { margin-bottom: 4px; width: 100%; } .goog-te-balloon-footer { margin: 6px 0px 4px; } .goog-te-spinner-pos { z-index: 1000; position: fixed; transition-delay: 0.= 6s; left: -1000px; top: -1000px; } .goog-te-spinner-animation { display: flex; align-items: center; justify-co= ntent: center; width: 104px; height: 104px; border-radius: 50px; background= : url("//www.gstatic.com/images/branding/product/2x/translate_24dp.png") 50= % 50% no-repeat rgb(255, 255, 255); transition: all 0.6s ease-in-out 0s; tr= ansform: scale(0.4); opacity: 0; } .goog-te-spinner-animation-show { transform: scale(0.5); opacity: 1; } .goog-te-spinner { margin: 2px 0px 0px 2px; animation: 1.4s linear 0s infin= ite normal none running goog-te-spinner-rotator; } @keyframes goog-te-spinner-rotator {=20 0% { transform: rotate(0deg); } 100% { transform: rotate(270deg); } } .goog-te-spinner-path { stroke-dasharray: 187; stroke-dashoffset: 0; stroke= : rgb(66, 133, 244); transform-origin: center center; animation: 1.4s ease-= in-out 0s infinite normal none running goog-te-spinner-dash; } @keyframes goog-te-spinner-dash {=20 0% { stroke-dashoffset: 187; } 50% { stroke-dashoffset: 46.75; transform: rotate(135deg); } 100% { stroke-dashoffset: 187; transform: rotate(450deg); } } #goog-gt-tt html, #goog-gt-tt body, #goog-gt-tt div, #goog-gt-tt span, #goo= g-gt-tt iframe, #goog-gt-tt h1, #goog-gt-tt h2, #goog-gt-tt h3, #goog-gt-tt= h4, #goog-gt-tt h5, #goog-gt-tt h6, #goog-gt-tt p, #goog-gt-tt a, #goog-gt= -tt img, #goog-gt-tt ol, #goog-gt-tt ul, #goog-gt-tt li, #goog-gt-tt table,= #goog-gt-tt form, #goog-gt-tt tbody, #goog-gt-tt tr, #goog-gt-tt td { marg= in: 0px; padding: 0px; border: 0px; font-style: inherit; font-variant: inhe= rit; font-weight: inherit; font-stretch: inherit; font-size: inherit; font-= family: inherit; vertical-align: baseline; text-align: left; line-height: n= ormal; } #goog-gt-tt ol, #goog-gt-tt ul { list-style: none; } #goog-gt-tt table { border-collapse: collapse; border-spacing: 0px; } #goog-gt-tt caption, #goog-gt-tt th, #goog-gt-tt td { text-align: left; fon= t-weight: normal; } div#goog-gt-tt { padding: 10px 14px; } #goog-gt-tt { color: rgb(34, 34, 34); background-color: rgb(255, 255, 255);= border: 1px solid rgb(238, 238, 238); box-shadow: rgba(0, 0, 0, 0.2) 0px 4= px 16px; display: none; font-family: arial; font-size: 10pt; width: 420px; = padding: 12px; position: absolute; z-index: 10000; } #goog-gt-tt .original-text, .gt-hl-layer { clear: both; font-size: 10pt; po= sition: relative; text-align: justify; width: 100%; } #goog-gt-tt .title { color: rgb(153, 153, 153); font-family: arial, sans-se= rif; margin: 4px 0px; text-align: left; } #goog-gt-tt .close-button { display: none; } #goog-gt-tt .logo { float: left; margin: 0px; } #goog-gt-tt .activity-links { display: inline-block; } #goog-gt-tt .started-activity-container { display: none; width: 100%; } #goog-gt-tt .activity-root { margin-top: 20px; } #goog-gt-tt .left { float: left; } #goog-gt-tt .right { float: right; } #goog-gt-tt .bottom { min-height: 15px; position: relative; height: 1%; } #goog-gt-tt .status-message { background: rgb(41, 145, 13); border-radius: = 4px; box-shadow: rgb(30, 102, 9) 0px 2px 2px inset; color: white; font-size= : 9pt; font-weight: bolder; margin-top: 12px; padding: 6px; text-shadow: rg= b(30, 102, 9) 1px 1px 1px; } #goog-gt-tt .activity-link { color: rgb(17, 85, 204); cursor: pointer; font= -family: arial; font-size: 11px; margin-right: 15px; text-decoration: none;= } #goog-gt-tt textarea { font-family: arial; resize: vertical; width: 100%; m= argin-bottom: 10px; border-radius: 1px; border-width: 1px; border-style: so= lid; border-color: silver rgb(217, 217, 217) rgb(217, 217, 217); border-ima= ge: initial; font-size: 13px; height: auto; overflow-y: auto; padding: 1px;= } #goog-gt-tt textarea:focus { box-shadow: rgba(0, 0, 0, 0.3) 0px 1px 2px ins= et; border: 1px solid rgb(77, 144, 254); outline: none; } #goog-gt-tt .activity-cancel { margin-right: 10px; } #goog-gt-tt .translate-form { min-height: 25px; vertical-align: middle; pad= ding-top: 8px; } #goog-gt-tt .translate-form .activity-form { margin-bottom: 0px; } #goog-gt-tt .translate-form .activity-form input { display: inline-block; m= in-width: 54px; border: 1px solid rgba(0, 0, 0, 0.1); text-align: center; c= olor: rgb(68, 68, 68); font-size: 11px; font-weight: bold; height: 27px; ou= tline: 0px; padding: 0px 8px; vertical-align: middle; line-height: 27px; ma= rgin: 0px 16px 0px 0px; box-shadow: rgba(0, 0, 0, 0.1) 0px 1px 2px; border-= radius: 2px; transition: all 0.218s ease 0s; background-color: rgb(245, 245= , 245); background-image: -webkit-linear-gradient(top, rgb(245, 245, 245), = rgb(241, 241, 241)); user-select: none; cursor: default; } #goog-gt-tt .translate-form .activity-form input:hover { border: 1px solid = rgb(198, 198, 198); color: rgb(34, 34, 34); transition: all 0s ease 0s; bac= kground-color: rgb(248, 248, 248); background-image: -webkit-linear-gradien= t(top, rgb(248, 248, 248), rgb(241, 241, 241)); } #goog-gt-tt .translate-form .activity-form input:active { border: 1px solid= rgb(198, 198, 198); color: rgb(51, 51, 51); background-color: rgb(246, 246= , 246); background-image: -webkit-linear-gradient(top, rgb(246, 246, 246), = rgb(241, 241, 241)); } #goog-gt-tt .translate-form .activity-form input:focus, #goog-gt-tt .transl= ate-form .activity-form input.focus { outline: none; border: 1px solid rgb(= 77, 144, 254); z-index: 4 !important; } #goog-gt-tt .translate-form .activity-form input.selected { background-colo= r: rgb(238, 238, 238); background-image: -webkit-linear-gradient(top, rgb(2= 38, 238, 238), rgb(224, 224, 224)); box-shadow: rgba(0, 0, 0, 0.1) 0px 1px = 2px inset; border: 1px solid rgb(204, 204, 204); color: rgb(51, 51, 51); } #goog-gt-tt .translate-form .activity-form input.activity-submit { color: w= hite; border-color: rgb(48, 121, 237); background-color: rgb(77, 144, 254);= background-image: -webkit-linear-gradient(top, rgb(77, 144, 254), rgb(71, = 135, 237)); } #goog-gt-tt .translate-form .activity-form input.activity-submit:hover #goo= g-gt-tt .translate-form .activity-form input.activity-submit:focus, #goog-g= t-tt .translate-form .activity-form input.activity-submit.focus #goog-gt-tt= .translate-form .activity-form input.activity-submit:active { border-color= : rgb(48, 121, 237); background-color: rgb(53, 122, 232); background-image:= -webkit-linear-gradient(top, rgb(77, 144, 254), rgb(53, 122, 232)); } #goog-gt-tt .translate-form .activity-form input.activity-submit:hover { bo= x-shadow: rgb(255, 255, 255) 0px 0px 0px 1px inset, rgba(0, 0, 0, 0.1) 0px = 1px 1px; } #goog-gt-tt .translate-form .activity-form input:focus, #goog-gt-tt .transl= ate-form .activity-form input.focus, #goog-gt-tt .translate-form .activity-= form input:active, #goog-gt-tt .translate-form .activity-form input:hover, = #goog-gt-tt .translate-form .activity-form input.activity-submit:focus, #go= og-gt-tt .translate-form .activity-form input.activity-submit.focus, #goog-= gt-tt .translate-form .activity-form input.activity-submit:active, #goog-gt= -tt .translate-form .activity-form input.activity-submit:hover { border-col= or: rgb(48, 121, 237); } #goog-gt-tt .gray { color: rgb(153, 153, 153); font-family: arial, sans-ser= if; } #goog-gt-tt .alt-helper-text { color: rgb(153, 153, 153); font-size: 11px; = font-family: arial, sans-serif; margin: 15px 0px 5px; } #goog-gt-tt .alt-error-text { color: rgb(136, 0, 0); display: none; font-si= ze: 9pt; } .goog-text-highlight { background-color: rgb(201, 215, 241); box-shadow: rg= b(153, 153, 170) 2px 2px 4px; box-sizing: border-box; position: relative; } #goog-gt-tt .alt-menu.goog-menu { background: rgb(255, 255, 255); border: 1= px solid rgb(221, 221, 221); box-shadow: rgb(153, 153, 170) 0px 2px 4px; mi= n-width: 0px; outline: none; padding: 0px; position: absolute; z-index: 200= 0; } #goog-gt-tt .alt-menu .goog-menuitem { cursor: pointer; padding: 2px 5px 5p= x; margin-right: 0px; border-style: none; } #goog-gt-tt .alt-menu div.goog-menuitem:hover { background: rgb(221, 221, 2= 21); } #goog-gt-tt .alt-menu .goog-menuitem h1 { font-size: 100%; font-weight: bol= d; margin: 4px 0px; } #goog-gt-tt .alt-menu .goog-menuitem strong { color: rgb(52, 90, 173); } #goog-gt-tt .goog-submenu-arrow { text-align: right; position: absolute; ri= ght: 0px; left: auto; } #goog-gt-tt .goog-menuitem-rtl .goog-submenu-arrow { text-align: left; posi= tion: absolute; left: 0px; right: auto; } #goog-gt-tt .gt-hl-text, #goog-gt-tt .trans-target-highlight { background-c= olor: rgb(241, 234, 0); border-radius: 4px; box-shadow: rgba(0, 0, 0, 0.5) = 3px 3px 4px; box-sizing: border-box; color: rgb(241, 234, 0); cursor: point= er; margin: -2px -2px -2px -3px; padding: 2px 2px 2px 3px; position: relati= ve; } #goog-gt-tt .trans-target-highlight { color: rgb(34, 34, 34); } #goog-gt-tt .gt-hl-layer { color: white; position: absolute !important; } #goog-gt-tt .trans-target, #goog-gt-tt .trans-target .trans-target-highligh= t { background-color: rgb(201, 215, 241); border-radius: 4px 4px 0px 0px; b= ox-shadow: rgba(0, 0, 0, 0.5) 3px 3px 4px; box-sizing: border-box; cursor: = pointer; margin: -2px -2px -2px -3px; padding: 2px 2px 3px 3px; position: r= elative; } #goog-gt-tt span:focus { outline: none; } #goog-gt-tt .trans-edit { background-color: transparent; border: 1px solid = rgb(77, 144, 254); border-radius: 0em; margin: -2px; padding: 1px; } #goog-gt-tt .gt-trans-highlight-l { border-left: 2px solid red; margin-left= : -2px; } #goog-gt-tt .gt-trans-highlight-r { border-right: 2px solid red; margin-rig= ht: -2px; } #goog-gt-tt #alt-input { padding: 2px; } #goog-gt-tt #alt-input-text { font-size: 11px; padding: 2px 2px 3px; margin= : 0px; background-color: rgb(255, 255, 255); color: rgb(51, 51, 51); border= -width: 1px; border-style: solid; border-color: rgb(192, 192, 192) rgb(217,= 217, 217) rgb(217, 217, 217); border-image: initial; display: inline-block= ; vertical-align: top; height: 21px; box-sizing: border-box; border-radius:= 1px; } #goog-gt-tt #alt-input-text:hover { border-width: 1px; border-style: solid;= border-color: rgb(160, 160, 160) rgb(185, 185, 185) rgb(185, 185, 185); bo= rder-image: initial; box-shadow: rgba(0, 0, 0, 0.1) 0px 1px 2px inset; } #goog-gt-tt #alt-input-text:focus { box-shadow: rgba(0, 0, 0, 0.3) 0px 1px = 2px inset; outline: none; border: 1px solid rgb(77, 144, 254); } #goog-gt-tt #alt-input-submit { font-size: 11px; padding: 2px 6px 3px; marg= in: 0px 0px 0px 2px; height: 21px; } ------MultipartBoundary--Ed8mr4hq2PkKv7UclxPAzEF7J8M75erKKbPS2p3d0i---- Content-Type: image/png Content-Transfer-Encoding: base64 Content-Location: https://www.gstatic.com/images/branding/product/2x/translate_24dp.png iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAG+UlEQVR4Ae2YVXfbWBCAtc/L8H+W ocztYpmflrfccGKIU2ZmZuY2jLbMDjNvw693dkbOKIrWcpR18JzNOV987dL3SXMlpdJE+fr/CwDe WHqgY+6inb2e+Tv7hJ55OwaY288cJiPMbA3r97a+hUijjbpYvLdz/oJdfYKJNWBhWtsMRBptBt7s 7HVr5WMNmGnvfIRIo426IEkjeUKVNxkwy4F/319F7yLSaKIuWHTkApCkujmINJqoCxYd/vgwOnnC 3vkYkUYTdWFe3nwAj9G4jBBLG8tHHx9iJjI7qXoeIo0W6kIvbCTPAXMz+kDLHEeY2VrS+2Dl/g5w uspFVVWDaG5pFa2tYVpaWlSam5sVmpqaItLY2EjQWq6urp+GSIy6GI48oZdntPLMtYceEQxVoQAJ //cAprKyZgYiERIvjKWNR2eoo88kn66C3DxZVFXXk3DMAfX1jU5EIiRezDUhvvhAnzj5ohvkik5o auuAZsRd2Qmn8LPF+yLLz0KW7WmHzCynkOWAqG9ojDWAkQiJF0biTPL1HtHY2gGvOyJDv7btYk/E AOIqjlFhkUcEAiGSGvkAkjSC5F+/HpCtbOiEx65OuF3QBaGa8Gf0uvJQb0T5mfaBMXJ7AqK0tIzE WJ4xko8hAOf8p/196pFv/7sDjj3r1l42aQ177vfA0v2R5Tlgaf8YuVx+EQiGRHl5OQmOYADJRODk 824+8sqs66/32rk3OvrM1QfhMfL7g3QWKIJEhj0+DQ0NhERIvDAKoA1L8k14FubtHCzPmJGfgSSd wjHKpTHyi1CoVJSVqRGxB7CYHhKngNxAJ+jFjTb0g+KuiAFLduMYZdIY+USwP4BYtc0Ka5MywIR8 bAEkbSbgibNLL8+oY+Tz0RiFA1Zus8DK7VYgsRELYEntCM3dyc84YWy3elT2PRzYK1dyuv4lP92G WPtg3tZnsPgPCyzbhNJbrQi+bmOssDohA9Yk7kAyGOUzjXzkABbWc0KziekmxvIq6WGOPBn4fSnX elieUeSJmSk18OPvFli6MRywYmuaGrACA1Zut6GwQyMfY8AP+wYuo214GT3ytFvMyhgsn3KjR7S2 h39PTVMXzM/oZfEwNgYjkCsP3DhGbmWMtJu5oqJCIf34BSXizrMs/fgYB5CQEQlXB9/IKuhG5uyE m3gj81Z2qp/T70m40mMozwGJeDXKyXUJ2e0XwWBoUIDb6xOr4+ywJj4dyvC9gfzwAjiisYVEI0Nn wHare0h5YvGudojLOAVLN1hg56mLwAHELnxPG3rniYtQWVlJouYCeByiQeN0/Fk3uMo7lU3d3NYJ HjwD5zO7YemBXmFGnphm7YVTNwrFsg1WWLbZCpm5+Yr8q9wCsQr3AJ2BIqcsKKCqqoqFYwuYEYXp 9gHMyBOJJyvBcfginoU0+CVtN5TIsvjVskfZzEcu3wIaJwrgiPr6+ugBM4xFTYkzRuIsz/y0sx1e vioWG6wHYfmWNFiXkA4rUH6D4wCU4khxgHGELiAWaWJaP2bkp/Zz5b5bPH2ZJ5Zv4cupDYqdsjJO HECvHFBdXc0RxgHGwsbieqLLMzRGVZC06wzeE9JwL6TBcryp7Tp5CTiA0QbU1NREDjCWNCHN2MJo xA3kEUsvzLE0wPe/psKqzTa4cOeRWBfvgBUYsePkRYowDKitrSUkQuKFeWljccaMPDElrRd+2HAY 7j58pTxiv8wpEGtxLyzfhhEnLsCwAowFzYsTU/vRiBvKE38dCEB2jkt9xM7MKxTrEhzKOO04rpwJ bQARQ4DNmKk6hpL/hgJw/QNejV71P2IHwndljChQIujZyH7sHHAAYRgww9brMpY0L05MsfaKSOIM yzOX78mioFAe9Iid1R9x/ModOgP6MSIkQuLFbEv77FikWVxLJPkpOigmQXk2Un7g1z/cMdEDmKnx 1fOmpr72TbV0Ci1ThuCbtH/zNTIltRO0fKPj65QOhR8czco+cMm0D8q0AfwaPWC02JL4NO6zuTfh Ux2fzLmh8umcm7A5+Qnk5eMZcA8+A8S4BsTZn3/0xYI7oOXz+YPZnvoCcvNcorjEK/wBZRMz4x9A rP3jRcuXi+7DF3oW3od420vIL5BFEcp7PPyzQdQAjiAkgr6NKkmOrA0UoMLy9hco7xTFxR4cHR/9 lyOOTwivQqVGAczYBjgcDz7QihNx1uc482F5WfYJnz+ARz8YLYAZ+wBizW8vWlg+3vYcZ75EFBW5 FXmvz49HP3oArzmgtLxCRiSCvo06ybacP5Qjj/I5ucWiEG9aTqdHkff7owfwe23Aq+yS+YhE0LdR Jw7HKM7yGDKz8kVOTpEoKCgRThddNt0KHg/GeL3C5/NxEEFrbSD9Xu+jpzkLEInhxWRl8gf8A1/5 iBrINb9BAAAAAElFTkSuQmCC ------MultipartBoundary--Ed8mr4hq2PkKv7UclxPAzEF7J8M75erKKbPS2p3d0i---- Content-Type: image/png Content-Transfer-Encoding: base64 Content-Location: https://www.gstatic.com/images/branding/product/1x/translate_24dp.png iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAADFUlEQVR4AWKgC0gC9E5OXW6FUQDt c41/VI89UxvvtcZVXNu2jbEV28nYNze3j+f0npV8cY271o6z9/10IZBddOILX3hcAKLgmAD5YfII lQC5IjtuDE77rUDxCYErOiHAjwLFR0eyfivAxHEBJmcBQsG///1ARE4k3z2RoxRgg8Qy45cDTJoo z1cJSOQpBcwNo3jcjy5XHwwODcFQmMHBQRgYGIjQ398fcDo96XGB/BjywjB5JKAQcMOZcexRm0Xp dwP0PBkJJIrLH/HQY+dwYGQC1fZJLH/ARwI5Ii8/m8FstlOE5EScnBEJkJRR9pCH8fEJfNIawMPP eHjYzOG+e3xEThy560W1xgQOp4vJvx+ghWTQnb/o4JAtKrtzFsiWC7ju1Dh2dOrBYrGBy+X6cYBk jIHhCVS85IHk12oDMD4xgYTeOUlyArNEXnw2gU5vBpvNDpsrZJgY6OvriwZIxmAjyKYteSEIO+8E od0yiZ+1XESeKROwsLwG1+2V4IbSo7ipTIKbK+S4tVqFW6pUmBQgGaP0QWgNHotrcOgpD3cbOaT3 ++7ymEUBWYi1J8fx2oOX0NrZDQ6HA6SXbuOzj7WpR5CtECCWA2Kk28bhwHBoF1WKuypWnhlGefUz 7FVdxLd1jbBdcgrtdjt4vV6SxweyRGkqMuVREuUZ0iAeuuPBUuUl3FAmwfqWTnA6nbToLJI6wISM jDCJ8nSRVcdHcGupCndITuPZe4+RAoTb7Qa/3x8NpJDGIwtBYiYn0iRBPH6jFrrUeig9fgHP3XmM LODz+WIDQS6VlJHOSJATh257UaMxgt5ghNKTF/FjQ0tyIOfoSFaaNBhMl/LASIthqSREmoTHtKMB ApeGWX1iFLVaI50H2k1x6zDlV6+9ez/NW1T0GhcWvSJwQeErPKRsQIPBDLSDCIr8doCuLbvqBxcW v0WiWlGPPWoDmMwWcQS2uIDH4/m9wGF5865FJW+xSl6PnZ1a0OmMYI4PsAj3W4GKipa51fJabG9X g1qtA4NBHIHJBBaLBaxWKz0TfEODOnfK/7i+AovHxWW/Lj+SAAAAAElFTkSuQmCC ------MultipartBoundary--Ed8mr4hq2PkKv7UclxPAzEF7J8M75erKKbPS2p3d0i---- Content-Type: image/svg+xml Content-ID: Content-Transfer-Encoding: quoted-printable Content-Location: http://beej.us/guide/bgnet/html/dataencap.svg image/svg+xml ------MultipartBoundary--Ed8mr4hq2PkKv7UclxPAzEF7J8M75erKKbPS2p3d0i---- Content-Type: image/svg+xml Content-ID: Content-Transfer-Encoding: quoted-printable Content-Location: http://beej.us/guide/bgnet/html/cs.svg image/svg+xml Client Server request response send() recv() recv() send() The Network ------MultipartBoundary--Ed8mr4hq2PkKv7UclxPAzEF7J8M75erKKbPS2p3d0i------