698 lines
85 KiB
HTML
698 lines
85 KiB
HTML
<!DOCTYPE html>
|
||
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
|
||
<head>
|
||
<meta charset="utf-8" />
|
||
<meta name="generator" content="pandoc" />
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
|
||
<title>Beej's Guide to Network Programming</title>
|
||
<style>
|
||
html {
|
||
color: #1a1a1a;
|
||
background-color: #fdfdfd;
|
||
}
|
||
body {
|
||
margin: 0 auto;
|
||
max-width: 36em;
|
||
padding-left: 50px;
|
||
padding-right: 50px;
|
||
padding-top: 50px;
|
||
padding-bottom: 50px;
|
||
hyphens: auto;
|
||
overflow-wrap: break-word;
|
||
text-rendering: optimizeLegibility;
|
||
font-kerning: normal;
|
||
}
|
||
@media (max-width: 600px) {
|
||
body {
|
||
font-size: 0.9em;
|
||
padding: 12px;
|
||
}
|
||
h1 {
|
||
font-size: 1.8em;
|
||
}
|
||
}
|
||
@media print {
|
||
html {
|
||
background-color: white;
|
||
}
|
||
body {
|
||
background-color: transparent;
|
||
color: black;
|
||
font-size: 12pt;
|
||
}
|
||
p, h2, h3 {
|
||
orphans: 3;
|
||
widows: 3;
|
||
}
|
||
h2, h3, h4 {
|
||
page-break-after: avoid;
|
||
}
|
||
}
|
||
p {
|
||
margin: 1em 0;
|
||
}
|
||
a {
|
||
color: #1a1a1a;
|
||
}
|
||
a:visited {
|
||
color: #1a1a1a;
|
||
}
|
||
img {
|
||
max-width: 100%;
|
||
}
|
||
h1, h2, h3, h4, h5, h6 {
|
||
margin-top: 1.4em;
|
||
}
|
||
h5, h6 {
|
||
font-size: 1em;
|
||
font-style: italic;
|
||
}
|
||
h6 {
|
||
font-weight: normal;
|
||
}
|
||
ol, ul {
|
||
padding-left: 1.7em;
|
||
margin-top: 1em;
|
||
}
|
||
li > ol, li > ul {
|
||
margin-top: 0;
|
||
}
|
||
blockquote {
|
||
margin: 1em 0 1em 1.7em;
|
||
padding-left: 1em;
|
||
border-left: 2px solid #e6e6e6;
|
||
color: #606060;
|
||
}
|
||
code {
|
||
font-family: Menlo, Monaco, Consolas, 'Lucida Console', monospace;
|
||
font-size: 85%;
|
||
margin: 0;
|
||
hyphens: manual;
|
||
}
|
||
pre {
|
||
margin: 1em 0;
|
||
overflow: auto;
|
||
}
|
||
pre code {
|
||
padding: 0;
|
||
overflow: visible;
|
||
overflow-wrap: normal;
|
||
}
|
||
.sourceCode {
|
||
background-color: transparent;
|
||
overflow: visible;
|
||
}
|
||
hr {
|
||
background-color: #1a1a1a;
|
||
border: none;
|
||
height: 1px;
|
||
margin: 1em 0;
|
||
}
|
||
table {
|
||
margin: 1em 0;
|
||
border-collapse: collapse;
|
||
width: 100%;
|
||
overflow-x: auto;
|
||
display: block;
|
||
font-variant-numeric: lining-nums tabular-nums;
|
||
}
|
||
table caption {
|
||
margin-bottom: 0.75em;
|
||
}
|
||
tbody {
|
||
margin-top: 0.5em;
|
||
border-top: 1px solid #1a1a1a;
|
||
border-bottom: 1px solid #1a1a1a;
|
||
}
|
||
th {
|
||
border-top: 1px solid #1a1a1a;
|
||
padding: 0.25em 0.5em 0.25em 0.5em;
|
||
}
|
||
td {
|
||
padding: 0.125em 0.5em 0.25em 0.5em;
|
||
}
|
||
header {
|
||
margin-bottom: 4em;
|
||
text-align: center;
|
||
}
|
||
#TOC li {
|
||
list-style: none;
|
||
}
|
||
#TOC ul {
|
||
padding-left: 1.3em;
|
||
}
|
||
#TOC > ul {
|
||
padding-left: 0;
|
||
}
|
||
#TOC a:not(:hover) {
|
||
text-decoration: none;
|
||
}
|
||
code{white-space: pre-wrap;}
|
||
span.smallcaps{font-variant: small-caps;}
|
||
div.columns{display: flex; gap: min(4vw, 1.5em);}
|
||
div.column{flex: auto; overflow-x: auto;}
|
||
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
|
||
ul.task-list{list-style: none;}
|
||
ul.task-list li input[type="checkbox"] {
|
||
width: 0.8em;
|
||
margin: 0 0.8em 0.2em -1.6em;
|
||
vertical-align: middle;
|
||
}
|
||
/* CSS for syntax highlighting */
|
||
pre > code.sourceCode { white-space: pre; position: relative; }
|
||
pre > code.sourceCode > span { display: inline-block; line-height: 1.25; }
|
||
pre > code.sourceCode > span:empty { height: 1.2em; }
|
||
.sourceCode { overflow: visible; }
|
||
code.sourceCode > span { color: inherit; text-decoration: inherit; }
|
||
div.sourceCode { margin: 1em 0; }
|
||
pre.sourceCode { margin: 0; }
|
||
@media screen {
|
||
div.sourceCode { overflow: auto; }
|
||
}
|
||
@media print {
|
||
pre > code.sourceCode { white-space: pre-wrap; }
|
||
pre > code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
|
||
}
|
||
pre.numberSource code
|
||
{ counter-reset: source-line 0; }
|
||
pre.numberSource code > span
|
||
{ position: relative; left: -4em; counter-increment: source-line; }
|
||
pre.numberSource code > span > a:first-child::before
|
||
{ content: counter(source-line);
|
||
position: relative; left: -1em; text-align: right; vertical-align: baseline;
|
||
border: none; display: inline-block;
|
||
-webkit-touch-callout: none; -webkit-user-select: none;
|
||
-khtml-user-select: none; -moz-user-select: none;
|
||
-ms-user-select: none; user-select: none;
|
||
padding: 0 4px; width: 4em;
|
||
color: #aaaaaa;
|
||
}
|
||
pre.numberSource { margin-left: 3em; border-left: 1px solid #aaaaaa; padding-left: 4px; }
|
||
div.sourceCode
|
||
{ }
|
||
@media screen {
|
||
pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
|
||
}
|
||
code span.al { color: #ff0000; font-weight: bold; } /* Alert */
|
||
code span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
|
||
code span.at { color: #7d9029; } /* Attribute */
|
||
code span.bn { color: #40a070; } /* BaseN */
|
||
code span.bu { color: #008000; } /* BuiltIn */
|
||
code span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
|
||
code span.ch { color: #4070a0; } /* Char */
|
||
code span.cn { color: #880000; } /* Constant */
|
||
code span.co { color: #60a0b0; font-style: italic; } /* Comment */
|
||
code span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
|
||
code span.do { color: #ba2121; font-style: italic; } /* Documentation */
|
||
code span.dt { color: #902000; } /* DataType */
|
||
code span.dv { color: #40a070; } /* DecVal */
|
||
code span.er { color: #ff0000; font-weight: bold; } /* Error */
|
||
code span.ex { } /* Extension */
|
||
code span.fl { color: #40a070; } /* Float */
|
||
code span.fu { color: #06287e; } /* Function */
|
||
code span.im { color: #008000; font-weight: bold; } /* Import */
|
||
code span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
|
||
code span.kw { color: #007020; font-weight: bold; } /* Keyword */
|
||
code span.op { color: #666666; } /* Operator */
|
||
code span.ot { color: #007020; } /* Other */
|
||
code span.pp { color: #bc7a00; } /* Preprocessor */
|
||
code span.sc { color: #4070a0; } /* SpecialChar */
|
||
code span.ss { color: #bb6688; } /* SpecialString */
|
||
code span.st { color: #4070a0; } /* String */
|
||
code span.va { color: #19177c; } /* Variable */
|
||
code span.vs { color: #4070a0; } /* VerbatimString */
|
||
code span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
|
||
</style>
|
||
<link href="https://fonts.googleapis.com/css?family=Roboto|Roboto+Mono&display=swap" rel="stylesheet">
|
||
|
||
<!-- BG custom styling -->
|
||
<style type="text/css">
|
||
/* Fix for line numbers not visible */
|
||
pre.numberSource code > span {
|
||
left: -1em;
|
||
}
|
||
pre.numberSource {
|
||
margin-left: initial;
|
||
}
|
||
|
||
/* Put some space after the section numbers */
|
||
span.toc-section-number::after {
|
||
content: "\a0\a0\a0"; /* non-breaking whitespace */
|
||
}
|
||
|
||
/* Hide underlines on code number links */
|
||
pre > code.sourceCode > span > a:first-child::before {
|
||
text-decoration: none;
|
||
}
|
||
|
||
/* Color the source blocks */
|
||
div.sourceCode {
|
||
background-color: #f0f0f0;
|
||
}
|
||
|
||
/* Fix iOS big text rendering issue */
|
||
pre > code.sourceCode > span {
|
||
display: initial;
|
||
}
|
||
|
||
|
||
/* Color the inline code */
|
||
code:not(.sourceCode) {
|
||
background: #f0f0f0;
|
||
padding-left: 0.2em;
|
||
padding-right: 0.2em;
|
||
border-radius: 0.2em;
|
||
}
|
||
|
||
/* Keep code tags from wrapping in tables */
|
||
tbody code {
|
||
white-space: nowrap;
|
||
}
|
||
|
||
td {
|
||
vertical-align: top;
|
||
}
|
||
|
||
body {
|
||
font-size: 12pt;
|
||
max-width: 43em;
|
||
}
|
||
|
||
figure {
|
||
text-align: center;
|
||
}
|
||
</style>
|
||
<!--[if lt IE 9]>
|
||
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
|
||
<![endif]-->
|
||
</head>
|
||
<body>
|
||
<div style="text-align:center"><span><a href="jumping-from-ipv4-to-ipv6.html">Prev</a> | </span><a href="index.html">Contents</a><span> | <a href="client-server-background.html">Next</a></span></div><hr>
|
||
<h1 data-number="5" id="system-calls-or-bust"><span class="header-section-number">5</span> System Calls or Bust</h1>
|
||
<p>This is the section where we get into the system calls (and other library calls) that allow you to access the network functionality of a Unix box, or any box that supports the sockets API for that matter (BSD, Windows, Linux, Mac, what-have-you.) When you call one of these functions, the kernel takes over and does all the work for you automagically.</p>
|
||
<p>The place most people get stuck around here is what order to call these things in. In that, the <code>man</code> pages are no use, as you’ve probably discovered. Well, to help with that dreadful situation, I’ve tried to lay out the system calls in the following sections in <em>exactly</em> (approximately) the same order that you’ll need to call them in your programs.</p>
|
||
<p>That, coupled with a few pieces of sample code here and there, some milk and cookies (which I fear you will have to supply yourself), and some raw guts and courage, and you’ll be beaming data around the Internet like the Son of Jon Postel!</p>
|
||
<p><em>(Please note that for brevity, many code snippets below do not include necessary error checking. And they very commonly assume that the result from calls to <code>getaddrinfo()</code> succeed and return a valid entry in the linked list. Both of these situations are properly addressed in the stand-alone programs, though, so use those as a model.)</em></p>
|
||
<h2 data-number="5.1" id="getaddrinfoprepare-to-launch"><span class="header-section-number">5.1</span> <code>getaddrinfo()</code>—Prepare to launch!</h2>
|
||
<p> This is a real workhorse of a function with a lot of options, but usage is actually pretty simple. It helps set up the <code>struct</code>s you need later on.</p>
|
||
<p>A tiny bit of history: it used to be that you would use a function called <code>gethostbyname()</code> to do DNS lookups. Then you’d load that information by hand into a <code>struct sockaddr_in</code>, and use that in your calls.</p>
|
||
<p>This is no longer necessary, thankfully. (Nor is it desirable, if you want to write code that works for both IPv4 and IPv6!) In these modern times, you now have the function <code>getaddrinfo()</code> that does all kinds of good stuff for you, including DNS and service name lookups, and fills out the <code>struct</code>s you need, besides!</p>
|
||
<p>Let’s take a look!</p>
|
||
<div class="sourceCode" id="cb20"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb20-1"><a href="system-calls-or-bust.html#cb20-1" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im"><sys/types.h></span></span>
|
||
<span id="cb20-2"><a href="system-calls-or-bust.html#cb20-2" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im"><sys/socket.h></span></span>
|
||
<span id="cb20-3"><a href="system-calls-or-bust.html#cb20-3" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im"><netdb.h></span></span>
|
||
<span id="cb20-4"><a href="system-calls-or-bust.html#cb20-4" aria-hidden="true" tabindex="-1"></a></span>
|
||
<span id="cb20-5"><a href="system-calls-or-bust.html#cb20-5" aria-hidden="true" tabindex="-1"></a><span class="dt">int</span> getaddrinfo<span class="op">(</span><span class="dt">const</span> <span class="dt">char</span> <span class="op">*</span>node<span class="op">,</span> <span class="co">// e.g. "www.example.com" or IP</span></span>
|
||
<span id="cb20-6"><a href="system-calls-or-bust.html#cb20-6" aria-hidden="true" tabindex="-1"></a> <span class="dt">const</span> <span class="dt">char</span> <span class="op">*</span>service<span class="op">,</span> <span class="co">// e.g. "http" or port number</span></span>
|
||
<span id="cb20-7"><a href="system-calls-or-bust.html#cb20-7" aria-hidden="true" tabindex="-1"></a> <span class="dt">const</span> <span class="kw">struct</span> addrinfo <span class="op">*</span>hints<span class="op">,</span></span>
|
||
<span id="cb20-8"><a href="system-calls-or-bust.html#cb20-8" aria-hidden="true" tabindex="-1"></a> <span class="kw">struct</span> addrinfo <span class="op">**</span>res<span class="op">);</span></span></code></pre></div>
|
||
<p>You give this function three input parameters, and it gives you a pointer to a linked-list, <code>res</code>, of results.</p>
|
||
<p>The <code>node</code> parameter is the host name to connect to, or an IP address.</p>
|
||
<p>Next is the parameter <code>service</code>, which can be a port number, like “80”, or the name of a particular service (found in <a href="https://www.iana.org/assignments/port-numbers">The IANA Port List</a><a href="footnotes.html#fn20" class="footnote-ref" id="fnref20" role="doc-noteref"><sup>20</sup></a> or the <code>/etc/services</code> file on your Unix machine) like “http” or “ftp” or “telnet” or “smtp” or whatever.</p>
|
||
<p>Finally, the <code>hints</code> parameter points to a <code>struct addrinfo</code> that you’ve already filled out with relevant information.</p>
|
||
<p>Here’s a sample call if you’re a server who wants to listen on your host’s IP address, port 3490. Note that this doesn’t actually do any listening or network setup; it merely sets up structures we’ll use later:</p>
|
||
<div class="sourceCode" id="cb21"><pre class="sourceCode numberSource c numberLines"><code class="sourceCode c"><span id="cb21-1"><a href="system-calls-or-bust.html#cb21-1"></a><span class="dt">int</span> status<span class="op">;</span></span>
|
||
<span id="cb21-2"><a href="system-calls-or-bust.html#cb21-2"></a><span class="kw">struct</span> addrinfo hints<span class="op">;</span></span>
|
||
<span id="cb21-3"><a href="system-calls-or-bust.html#cb21-3"></a><span class="kw">struct</span> addrinfo <span class="op">*</span>servinfo<span class="op">;</span> <span class="co">// will point to the results</span></span>
|
||
<span id="cb21-4"><a href="system-calls-or-bust.html#cb21-4"></a></span>
|
||
<span id="cb21-5"><a href="system-calls-or-bust.html#cb21-5"></a>memset<span class="op">(&</span>hints<span class="op">,</span> <span class="dv">0</span><span class="op">,</span> <span class="kw">sizeof</span> hints<span class="op">);</span> <span class="co">// make sure the struct is empty</span></span>
|
||
<span id="cb21-6"><a href="system-calls-or-bust.html#cb21-6"></a>hints<span class="op">.</span>ai_family <span class="op">=</span> AF_UNSPEC<span class="op">;</span> <span class="co">// don't care IPv4 or IPv6</span></span>
|
||
<span id="cb21-7"><a href="system-calls-or-bust.html#cb21-7"></a>hints<span class="op">.</span>ai_socktype <span class="op">=</span> SOCK_STREAM<span class="op">;</span> <span class="co">// TCP stream sockets</span></span>
|
||
<span id="cb21-8"><a href="system-calls-or-bust.html#cb21-8"></a>hints<span class="op">.</span>ai_flags <span class="op">=</span> AI_PASSIVE<span class="op">;</span> <span class="co">// fill in my IP for me</span></span>
|
||
<span id="cb21-9"><a href="system-calls-or-bust.html#cb21-9"></a></span>
|
||
<span id="cb21-10"><a href="system-calls-or-bust.html#cb21-10"></a><span class="cf">if</span> <span class="op">((</span>status <span class="op">=</span> getaddrinfo<span class="op">(</span>NULL<span class="op">,</span> <span class="st">"3490"</span><span class="op">,</span> <span class="op">&</span>hints<span class="op">,</span> <span class="op">&</span>servinfo<span class="op">))</span> <span class="op">!=</span> <span class="dv">0</span><span class="op">)</span> <span class="op">{</span></span>
|
||
<span id="cb21-11"><a href="system-calls-or-bust.html#cb21-11"></a> fprintf<span class="op">(</span>stderr<span class="op">,</span> <span class="st">"getaddrinfo error: </span><span class="sc">%s\n</span><span class="st">"</span><span class="op">,</span> gai_strerror<span class="op">(</span>status<span class="op">));</span></span>
|
||
<span id="cb21-12"><a href="system-calls-or-bust.html#cb21-12"></a> exit<span class="op">(</span><span class="dv">1</span><span class="op">);</span></span>
|
||
<span id="cb21-13"><a href="system-calls-or-bust.html#cb21-13"></a><span class="op">}</span></span>
|
||
<span id="cb21-14"><a href="system-calls-or-bust.html#cb21-14"></a></span>
|
||
<span id="cb21-15"><a href="system-calls-or-bust.html#cb21-15"></a><span class="co">// servinfo now points to a linked list of 1 or more struct addrinfos</span></span>
|
||
<span id="cb21-16"><a href="system-calls-or-bust.html#cb21-16"></a></span>
|
||
<span id="cb21-17"><a href="system-calls-or-bust.html#cb21-17"></a><span class="co">// ... do everything until you don't need servinfo anymore ....</span></span>
|
||
<span id="cb21-18"><a href="system-calls-or-bust.html#cb21-18"></a></span>
|
||
<span id="cb21-19"><a href="system-calls-or-bust.html#cb21-19"></a>freeaddrinfo<span class="op">(</span>servinfo<span class="op">);</span> <span class="co">// free the linked-list</span></span></code></pre></div>
|
||
<p>Notice that I set the <code>ai_family</code> to <code>AF_UNSPEC</code>, thereby saying that I don’t care if we use IPv4 or IPv6. You can set it to <code>AF_INET</code> or <code>AF_INET6</code> if you want one or the other specifically.</p>
|
||
<p>Also, you’ll see the <code>AI_PASSIVE</code> flag in there; this tells <code>getaddrinfo()</code> to assign the address of my local host to the socket structures. This is nice because then you don’t have to hardcode it. (Or you can put a specific address in as the first parameter to <code>getaddrinfo()</code> where I currently have <code>NULL</code>, up there.)</p>
|
||
<p>Then we make the call. If there’s an error (<code>getaddrinfo()</code> returns non-zero), we can print it out using the function <code>gai_strerror()</code>, as you see. If everything works properly, though, <code>servinfo</code> will point to a linked list of <code>struct addrinfo</code>s, each of which contains a <code>struct sockaddr</code> of some kind that we can use later! Nifty!</p>
|
||
<p>Finally, when we’re eventually all done with the linked list that <code>getaddrinfo()</code> so graciously allocated for us, we can (and should) free it all up with a call to <code>freeaddrinfo()</code>.</p>
|
||
<p>Here’s a sample call if you’re a client who wants to connect to a particular server, say “www.example.net” port 3490. Again, this doesn’t actually connect, but it sets up the structures we’ll use later:</p>
|
||
<div class="sourceCode" id="cb22"><pre class="sourceCode numberSource c numberLines"><code class="sourceCode c"><span id="cb22-1"><a href="system-calls-or-bust.html#cb22-1"></a><span class="dt">int</span> status<span class="op">;</span></span>
|
||
<span id="cb22-2"><a href="system-calls-or-bust.html#cb22-2"></a><span class="kw">struct</span> addrinfo hints<span class="op">;</span></span>
|
||
<span id="cb22-3"><a href="system-calls-or-bust.html#cb22-3"></a><span class="kw">struct</span> addrinfo <span class="op">*</span>servinfo<span class="op">;</span> <span class="co">// will point to the results</span></span>
|
||
<span id="cb22-4"><a href="system-calls-or-bust.html#cb22-4"></a></span>
|
||
<span id="cb22-5"><a href="system-calls-or-bust.html#cb22-5"></a>memset<span class="op">(&</span>hints<span class="op">,</span> <span class="dv">0</span><span class="op">,</span> <span class="kw">sizeof</span> hints<span class="op">);</span> <span class="co">// make sure the struct is empty</span></span>
|
||
<span id="cb22-6"><a href="system-calls-or-bust.html#cb22-6"></a>hints<span class="op">.</span>ai_family <span class="op">=</span> AF_UNSPEC<span class="op">;</span> <span class="co">// don't care IPv4 or IPv6</span></span>
|
||
<span id="cb22-7"><a href="system-calls-or-bust.html#cb22-7"></a>hints<span class="op">.</span>ai_socktype <span class="op">=</span> SOCK_STREAM<span class="op">;</span> <span class="co">// TCP stream sockets</span></span>
|
||
<span id="cb22-8"><a href="system-calls-or-bust.html#cb22-8"></a></span>
|
||
<span id="cb22-9"><a href="system-calls-or-bust.html#cb22-9"></a><span class="co">// get ready to connect</span></span>
|
||
<span id="cb22-10"><a href="system-calls-or-bust.html#cb22-10"></a>status <span class="op">=</span> getaddrinfo<span class="op">(</span><span class="st">"www.example.net"</span><span class="op">,</span> <span class="st">"3490"</span><span class="op">,</span> <span class="op">&</span>hints<span class="op">,</span> <span class="op">&</span>servinfo<span class="op">);</span></span>
|
||
<span id="cb22-11"><a href="system-calls-or-bust.html#cb22-11"></a></span>
|
||
<span id="cb22-12"><a href="system-calls-or-bust.html#cb22-12"></a><span class="co">// servinfo now points to a linked list of 1 or more struct addrinfos</span></span>
|
||
<span id="cb22-13"><a href="system-calls-or-bust.html#cb22-13"></a></span>
|
||
<span id="cb22-14"><a href="system-calls-or-bust.html#cb22-14"></a><span class="co">// etc.</span></span></code></pre></div>
|
||
<p>I keep saying that <code>servinfo</code> is a linked list with all kinds of address information. Let’s write a quick demo program to show off this information. <a href="https://beej.us/guide/bgnet/examples/showip.c">This short program</a><a href="footnotes.html#fn21" class="footnote-ref" id="fnref21" role="doc-noteref"><sup>21</sup></a> will print the IP addresses for whatever host you specify on the command line:</p>
|
||
<div class="sourceCode" id="cb23"><pre class="sourceCode numberSource c numberLines"><code class="sourceCode c"><span id="cb23-1"><a href="system-calls-or-bust.html#cb23-1"></a><span class="co">/*</span></span>
|
||
<span id="cb23-2"><a href="system-calls-or-bust.html#cb23-2"></a><span class="co">** showip.c -- show IP addresses for a host given on the command line</span></span>
|
||
<span id="cb23-3"><a href="system-calls-or-bust.html#cb23-3"></a><span class="co">*/</span></span>
|
||
<span id="cb23-4"><a href="system-calls-or-bust.html#cb23-4"></a></span>
|
||
<span id="cb23-5"><a href="system-calls-or-bust.html#cb23-5"></a><span class="pp">#include </span><span class="im"><stdio.h></span></span>
|
||
<span id="cb23-6"><a href="system-calls-or-bust.html#cb23-6"></a><span class="pp">#include </span><span class="im"><string.h></span></span>
|
||
<span id="cb23-7"><a href="system-calls-or-bust.html#cb23-7"></a><span class="pp">#include </span><span class="im"><sys/types.h></span></span>
|
||
<span id="cb23-8"><a href="system-calls-or-bust.html#cb23-8"></a><span class="pp">#include </span><span class="im"><sys/socket.h></span></span>
|
||
<span id="cb23-9"><a href="system-calls-or-bust.html#cb23-9"></a><span class="pp">#include </span><span class="im"><netdb.h></span></span>
|
||
<span id="cb23-10"><a href="system-calls-or-bust.html#cb23-10"></a><span class="pp">#include </span><span class="im"><arpa/inet.h></span></span>
|
||
<span id="cb23-11"><a href="system-calls-or-bust.html#cb23-11"></a><span class="pp">#include </span><span class="im"><netinet/in.h></span></span>
|
||
<span id="cb23-12"><a href="system-calls-or-bust.html#cb23-12"></a></span>
|
||
<span id="cb23-13"><a href="system-calls-or-bust.html#cb23-13"></a><span class="dt">int</span> main<span class="op">(</span><span class="dt">int</span> argc<span class="op">,</span> <span class="dt">char</span> <span class="op">*</span>argv<span class="op">[])</span></span>
|
||
<span id="cb23-14"><a href="system-calls-or-bust.html#cb23-14"></a><span class="op">{</span></span>
|
||
<span id="cb23-15"><a href="system-calls-or-bust.html#cb23-15"></a> <span class="kw">struct</span> addrinfo hints<span class="op">,</span> <span class="op">*</span>res<span class="op">,</span> <span class="op">*</span>p<span class="op">;</span></span>
|
||
<span id="cb23-16"><a href="system-calls-or-bust.html#cb23-16"></a> <span class="dt">int</span> status<span class="op">;</span></span>
|
||
<span id="cb23-17"><a href="system-calls-or-bust.html#cb23-17"></a> <span class="dt">char</span> ipstr<span class="op">[</span>INET6_ADDRSTRLEN<span class="op">];</span></span>
|
||
<span id="cb23-18"><a href="system-calls-or-bust.html#cb23-18"></a></span>
|
||
<span id="cb23-19"><a href="system-calls-or-bust.html#cb23-19"></a> <span class="cf">if</span> <span class="op">(</span>argc <span class="op">!=</span> <span class="dv">2</span><span class="op">)</span> <span class="op">{</span></span>
|
||
<span id="cb23-20"><a href="system-calls-or-bust.html#cb23-20"></a> fprintf<span class="op">(</span>stderr<span class="op">,</span><span class="st">"usage: showip hostname</span><span class="sc">\n</span><span class="st">"</span><span class="op">);</span></span>
|
||
<span id="cb23-21"><a href="system-calls-or-bust.html#cb23-21"></a> <span class="cf">return</span> <span class="dv">1</span><span class="op">;</span></span>
|
||
<span id="cb23-22"><a href="system-calls-or-bust.html#cb23-22"></a> <span class="op">}</span></span>
|
||
<span id="cb23-23"><a href="system-calls-or-bust.html#cb23-23"></a></span>
|
||
<span id="cb23-24"><a href="system-calls-or-bust.html#cb23-24"></a> memset<span class="op">(&</span>hints<span class="op">,</span> <span class="dv">0</span><span class="op">,</span> <span class="kw">sizeof</span> hints<span class="op">);</span></span>
|
||
<span id="cb23-25"><a href="system-calls-or-bust.html#cb23-25"></a> hints<span class="op">.</span>ai_family <span class="op">=</span> AF_UNSPEC<span class="op">;</span> <span class="co">// AF_INET or AF_INET6 to force version</span></span>
|
||
<span id="cb23-26"><a href="system-calls-or-bust.html#cb23-26"></a> hints<span class="op">.</span>ai_socktype <span class="op">=</span> SOCK_STREAM<span class="op">;</span></span>
|
||
<span id="cb23-27"><a href="system-calls-or-bust.html#cb23-27"></a></span>
|
||
<span id="cb23-28"><a href="system-calls-or-bust.html#cb23-28"></a> <span class="cf">if</span> <span class="op">((</span>status <span class="op">=</span> getaddrinfo<span class="op">(</span>argv<span class="op">[</span><span class="dv">1</span><span class="op">],</span> NULL<span class="op">,</span> <span class="op">&</span>hints<span class="op">,</span> <span class="op">&</span>res<span class="op">))</span> <span class="op">!=</span> <span class="dv">0</span><span class="op">)</span> <span class="op">{</span></span>
|
||
<span id="cb23-29"><a href="system-calls-or-bust.html#cb23-29"></a> fprintf<span class="op">(</span>stderr<span class="op">,</span> <span class="st">"getaddrinfo: </span><span class="sc">%s\n</span><span class="st">"</span><span class="op">,</span> gai_strerror<span class="op">(</span>status<span class="op">));</span></span>
|
||
<span id="cb23-30"><a href="system-calls-or-bust.html#cb23-30"></a> <span class="cf">return</span> <span class="dv">2</span><span class="op">;</span></span>
|
||
<span id="cb23-31"><a href="system-calls-or-bust.html#cb23-31"></a> <span class="op">}</span></span>
|
||
<span id="cb23-32"><a href="system-calls-or-bust.html#cb23-32"></a></span>
|
||
<span id="cb23-33"><a href="system-calls-or-bust.html#cb23-33"></a> printf<span class="op">(</span><span class="st">"IP addresses for </span><span class="sc">%s</span><span class="st">:</span><span class="sc">\n\n</span><span class="st">"</span><span class="op">,</span> argv<span class="op">[</span><span class="dv">1</span><span class="op">]);</span></span>
|
||
<span id="cb23-34"><a href="system-calls-or-bust.html#cb23-34"></a></span>
|
||
<span id="cb23-35"><a href="system-calls-or-bust.html#cb23-35"></a> <span class="cf">for</span><span class="op">(</span>p <span class="op">=</span> res<span class="op">;</span>p <span class="op">!=</span> NULL<span class="op">;</span> p <span class="op">=</span> p<span class="op">-></span>ai_next<span class="op">)</span> <span class="op">{</span></span>
|
||
<span id="cb23-36"><a href="system-calls-or-bust.html#cb23-36"></a> <span class="dt">void</span> <span class="op">*</span>addr<span class="op">;</span></span>
|
||
<span id="cb23-37"><a href="system-calls-or-bust.html#cb23-37"></a> <span class="dt">char</span> <span class="op">*</span>ipver<span class="op">;</span></span>
|
||
<span id="cb23-38"><a href="system-calls-or-bust.html#cb23-38"></a></span>
|
||
<span id="cb23-39"><a href="system-calls-or-bust.html#cb23-39"></a> <span class="co">// get the pointer to the address itself,</span></span>
|
||
<span id="cb23-40"><a href="system-calls-or-bust.html#cb23-40"></a> <span class="co">// different fields in IPv4 and IPv6:</span></span>
|
||
<span id="cb23-41"><a href="system-calls-or-bust.html#cb23-41"></a> <span class="cf">if</span> <span class="op">(</span>p<span class="op">-></span>ai_family <span class="op">==</span> AF_INET<span class="op">)</span> <span class="op">{</span> <span class="co">// IPv4</span></span>
|
||
<span id="cb23-42"><a href="system-calls-or-bust.html#cb23-42"></a> <span class="kw">struct</span> sockaddr_in <span class="op">*</span>ipv4 <span class="op">=</span> <span class="op">(</span><span class="kw">struct</span> sockaddr_in <span class="op">*)</span>p<span class="op">-></span>ai_addr<span class="op">;</span></span>
|
||
<span id="cb23-43"><a href="system-calls-or-bust.html#cb23-43"></a> addr <span class="op">=</span> <span class="op">&(</span>ipv4<span class="op">-></span>sin_addr<span class="op">);</span></span>
|
||
<span id="cb23-44"><a href="system-calls-or-bust.html#cb23-44"></a> ipver <span class="op">=</span> <span class="st">"IPv4"</span><span class="op">;</span></span>
|
||
<span id="cb23-45"><a href="system-calls-or-bust.html#cb23-45"></a> <span class="op">}</span> <span class="cf">else</span> <span class="op">{</span> <span class="co">// IPv6</span></span>
|
||
<span id="cb23-46"><a href="system-calls-or-bust.html#cb23-46"></a> <span class="kw">struct</span> sockaddr_in6 <span class="op">*</span>ipv6 <span class="op">=</span> <span class="op">(</span><span class="kw">struct</span> sockaddr_in6 <span class="op">*)</span>p<span class="op">-></span>ai_addr<span class="op">;</span></span>
|
||
<span id="cb23-47"><a href="system-calls-or-bust.html#cb23-47"></a> addr <span class="op">=</span> <span class="op">&(</span>ipv6<span class="op">-></span>sin6_addr<span class="op">);</span></span>
|
||
<span id="cb23-48"><a href="system-calls-or-bust.html#cb23-48"></a> ipver <span class="op">=</span> <span class="st">"IPv6"</span><span class="op">;</span></span>
|
||
<span id="cb23-49"><a href="system-calls-or-bust.html#cb23-49"></a> <span class="op">}</span></span>
|
||
<span id="cb23-50"><a href="system-calls-or-bust.html#cb23-50"></a></span>
|
||
<span id="cb23-51"><a href="system-calls-or-bust.html#cb23-51"></a> <span class="co">// convert the IP to a string and print it:</span></span>
|
||
<span id="cb23-52"><a href="system-calls-or-bust.html#cb23-52"></a> inet_ntop<span class="op">(</span>p<span class="op">-></span>ai_family<span class="op">,</span> addr<span class="op">,</span> ipstr<span class="op">,</span> <span class="kw">sizeof</span> ipstr<span class="op">);</span></span>
|
||
<span id="cb23-53"><a href="system-calls-or-bust.html#cb23-53"></a> printf<span class="op">(</span><span class="st">" </span><span class="sc">%s</span><span class="st">: </span><span class="sc">%s\n</span><span class="st">"</span><span class="op">,</span> ipver<span class="op">,</span> ipstr<span class="op">);</span></span>
|
||
<span id="cb23-54"><a href="system-calls-or-bust.html#cb23-54"></a> <span class="op">}</span></span>
|
||
<span id="cb23-55"><a href="system-calls-or-bust.html#cb23-55"></a></span>
|
||
<span id="cb23-56"><a href="system-calls-or-bust.html#cb23-56"></a> freeaddrinfo<span class="op">(</span>res<span class="op">);</span> <span class="co">// free the linked list</span></span>
|
||
<span id="cb23-57"><a href="system-calls-or-bust.html#cb23-57"></a></span>
|
||
<span id="cb23-58"><a href="system-calls-or-bust.html#cb23-58"></a> <span class="cf">return</span> <span class="dv">0</span><span class="op">;</span></span>
|
||
<span id="cb23-59"><a href="system-calls-or-bust.html#cb23-59"></a><span class="op">}</span></span></code></pre></div>
|
||
<p>As you see, the code calls <code>getaddrinfo()</code> on whatever you pass on the command line, that fills out the linked list pointed to by <code>res</code>, and then we can iterate over the list and print stuff out or do whatever.</p>
|
||
<p>(There’s a little bit of ugliness there where we have to dig into the different types of <code>struct sockaddr</code>s depending on the IP version. Sorry about that! I’m not sure of a better way around it.)</p>
|
||
<p>Sample run! Everyone loves screenshots:</p>
|
||
<pre><code>$ showip www.example.net
|
||
IP addresses for www.example.net:
|
||
|
||
IPv4: 192.0.2.88
|
||
|
||
$ showip ipv6.example.com
|
||
IP addresses for ipv6.example.com:
|
||
|
||
IPv4: 192.0.2.101
|
||
IPv6: 2001:db8:8c00:22::171</code></pre>
|
||
<p>Now that we have that under control, we’ll use the results we get from <code>getaddrinfo()</code> to pass to other socket functions and, at long last, get our network connection established! Keep reading!</p>
|
||
<h2 data-number="5.2" id="socket"><span class="header-section-number">5.2</span> <code>socket()</code>—Get the File Descriptor!</h2>
|
||
<p>I guess I can put it off no longer—I have to talk about the <code>socket()</code> system call. Here’s the breakdown:</p>
|
||
<div class="sourceCode" id="cb25"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb25-1"><a href="system-calls-or-bust.html#cb25-1" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im"><sys/types.h></span></span>
|
||
<span id="cb25-2"><a href="system-calls-or-bust.html#cb25-2" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im"><sys/socket.h></span></span>
|
||
<span id="cb25-3"><a href="system-calls-or-bust.html#cb25-3" aria-hidden="true" tabindex="-1"></a></span>
|
||
<span id="cb25-4"><a href="system-calls-or-bust.html#cb25-4" aria-hidden="true" tabindex="-1"></a><span class="dt">int</span> socket<span class="op">(</span><span class="dt">int</span> domain<span class="op">,</span> <span class="dt">int</span> type<span class="op">,</span> <span class="dt">int</span> protocol<span class="op">);</span> </span></code></pre></div>
|
||
<p>But what are these arguments? They allow you to say what kind of socket you want (IPv4 or IPv6, stream or datagram, and TCP or UDP).</p>
|
||
<p>It used to be people would hardcode these values, and you can absolutely still do that. (<code>domain</code> is <code>PF_INET</code> or <code>PF_INET6</code>, <code>type</code> is <code>SOCK_STREAM</code> or <code>SOCK_DGRAM</code>, and <code>protocol</code> can be set to <code>0</code> to choose the proper protocol for the given <code>type</code>. Or you can call <code>getprotobyname()</code> to look up the protocol you want, “tcp” or “udp”.)</p>
|
||
<p>(This <code>PF_INET</code> thing is a close relative of the <code>AF_INET</code> that you can use when initializing the <code>sin_family</code> field in your <code>struct sockaddr_in</code>. In fact, they’re so closely related that they actually have the same value, and many programmers will call <code>socket()</code> and pass <code>AF_INET</code> as the first argument instead of <code>PF_INET</code>. Now, get some milk and cookies, because it’s time for a story. Once upon a time, a long time ago, it was thought that maybe an address family (what the “AF” in “<code>AF_INET</code>” stands for) might support several protocols that were referred to by their protocol family (what the “PF” in “<code>PF_INET</code>” stands for). That didn’t happen. And they all lived happily ever after, The End. So the most correct thing to do is to use <code>AF_INET</code> in your <code>struct sockaddr_in</code> and <code>PF_INET</code> in your call to <code>socket()</code>.)</p>
|
||
<p>Anyway, enough of that. What you really want to do is use the values from the results of the call to <code>getaddrinfo()</code>, and feed them into <code>socket()</code> directly like this:</p>
|
||
<div class="sourceCode" id="cb26"><pre class="sourceCode numberSource c numberLines"><code class="sourceCode c"><span id="cb26-1"><a href="system-calls-or-bust.html#cb26-1"></a><span class="dt">int</span> s<span class="op">;</span></span>
|
||
<span id="cb26-2"><a href="system-calls-or-bust.html#cb26-2"></a><span class="kw">struct</span> addrinfo hints<span class="op">,</span> <span class="op">*</span>res<span class="op">;</span></span>
|
||
<span id="cb26-3"><a href="system-calls-or-bust.html#cb26-3"></a></span>
|
||
<span id="cb26-4"><a href="system-calls-or-bust.html#cb26-4"></a><span class="co">// do the lookup</span></span>
|
||
<span id="cb26-5"><a href="system-calls-or-bust.html#cb26-5"></a><span class="co">// [pretend we already filled out the "hints" struct]</span></span>
|
||
<span id="cb26-6"><a href="system-calls-or-bust.html#cb26-6"></a>getaddrinfo<span class="op">(</span><span class="st">"www.example.com"</span><span class="op">,</span> <span class="st">"http"</span><span class="op">,</span> <span class="op">&</span>hints<span class="op">,</span> <span class="op">&</span>res<span class="op">);</span></span>
|
||
<span id="cb26-7"><a href="system-calls-or-bust.html#cb26-7"></a></span>
|
||
<span id="cb26-8"><a href="system-calls-or-bust.html#cb26-8"></a><span class="co">// again, you should do error-checking on getaddrinfo(), and walk</span></span>
|
||
<span id="cb26-9"><a href="system-calls-or-bust.html#cb26-9"></a><span class="co">// the "res" linked list looking for valid entries instead of just</span></span>
|
||
<span id="cb26-10"><a href="system-calls-or-bust.html#cb26-10"></a><span class="co">// assuming the first one is good (like many of these examples do).</span></span>
|
||
<span id="cb26-11"><a href="system-calls-or-bust.html#cb26-11"></a><span class="co">// See the section on client/server for real examples.</span></span>
|
||
<span id="cb26-12"><a href="system-calls-or-bust.html#cb26-12"></a></span>
|
||
<span id="cb26-13"><a href="system-calls-or-bust.html#cb26-13"></a>s <span class="op">=</span> socket<span class="op">(</span>res<span class="op">-></span>ai_family<span class="op">,</span> res<span class="op">-></span>ai_socktype<span class="op">,</span> res<span class="op">-></span>ai_protocol<span class="op">);</span></span></code></pre></div>
|
||
<p><code>socket()</code> simply returns to you a <em>socket descriptor</em> that you can use in later system calls, or <code>-1</code> on error. The global variable <code>errno</code> is set to the error’s value (see the <a href="man-pages.html#errnoman"><code>errno</code></a> man page for more details, and a quick note on using <code>errno</code> in multithreaded programs).</p>
|
||
<p>Fine, fine, fine, but what good is this socket? The answer is that it’s really no good by itself, and you need to read on and make more system calls for it to make any sense.</p>
|
||
<h2 data-number="5.3" id="bind"><span class="header-section-number">5.3</span> <code>bind()</code>—What port am I on?</h2>
|
||
<p> 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’re going to <code>listen()</code> for incoming connections on a specific port—multiplayer network games do this when they tell you to “connect to 192.168.5.10 port 3490”.) The port number is used by the kernel to match an incoming packet to a certain process’s socket descriptor. If you’re going to only be doing a <code>connect()</code> (because you’re the client, not the server), this is probably unnecessary. Read it anyway, just for kicks.</p>
|
||
<p>Here is the synopsis for the <code>bind()</code> system call:</p>
|
||
<div class="sourceCode" id="cb27"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb27-1"><a href="system-calls-or-bust.html#cb27-1" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im"><sys/types.h></span></span>
|
||
<span id="cb27-2"><a href="system-calls-or-bust.html#cb27-2" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im"><sys/socket.h></span></span>
|
||
<span id="cb27-3"><a href="system-calls-or-bust.html#cb27-3" aria-hidden="true" tabindex="-1"></a></span>
|
||
<span id="cb27-4"><a href="system-calls-or-bust.html#cb27-4" aria-hidden="true" tabindex="-1"></a><span class="dt">int</span> bind<span class="op">(</span><span class="dt">int</span> sockfd<span class="op">,</span> <span class="kw">struct</span> sockaddr <span class="op">*</span>my_addr<span class="op">,</span> <span class="dt">int</span> addrlen<span class="op">);</span></span></code></pre></div>
|
||
<p><code>sockfd</code> is the socket file descriptor returned by <code>socket()</code>. <code>my_addr</code> is a pointer to a <code>struct sockaddr</code> that contains information about your address, namely, port and IP address. <code>addrlen</code> is the length in bytes of that address.</p>
|
||
<p>Whew. That’s a bit to absorb in one chunk. Let’s have an example that binds the socket to the host the program is running on, port 3490:</p>
|
||
<div class="sourceCode" id="cb28"><pre class="sourceCode numberSource c numberLines"><code class="sourceCode c"><span id="cb28-1"><a href="system-calls-or-bust.html#cb28-1"></a><span class="kw">struct</span> addrinfo hints<span class="op">,</span> <span class="op">*</span>res<span class="op">;</span></span>
|
||
<span id="cb28-2"><a href="system-calls-or-bust.html#cb28-2"></a><span class="dt">int</span> sockfd<span class="op">;</span></span>
|
||
<span id="cb28-3"><a href="system-calls-or-bust.html#cb28-3"></a></span>
|
||
<span id="cb28-4"><a href="system-calls-or-bust.html#cb28-4"></a><span class="co">// first, load up address structs with getaddrinfo():</span></span>
|
||
<span id="cb28-5"><a href="system-calls-or-bust.html#cb28-5"></a></span>
|
||
<span id="cb28-6"><a href="system-calls-or-bust.html#cb28-6"></a>memset<span class="op">(&</span>hints<span class="op">,</span> <span class="dv">0</span><span class="op">,</span> <span class="kw">sizeof</span> hints<span class="op">);</span></span>
|
||
<span id="cb28-7"><a href="system-calls-or-bust.html#cb28-7"></a>hints<span class="op">.</span>ai_family <span class="op">=</span> AF_UNSPEC<span class="op">;</span> <span class="co">// use IPv4 or IPv6, whichever</span></span>
|
||
<span id="cb28-8"><a href="system-calls-or-bust.html#cb28-8"></a>hints<span class="op">.</span>ai_socktype <span class="op">=</span> SOCK_STREAM<span class="op">;</span></span>
|
||
<span id="cb28-9"><a href="system-calls-or-bust.html#cb28-9"></a>hints<span class="op">.</span>ai_flags <span class="op">=</span> AI_PASSIVE<span class="op">;</span> <span class="co">// fill in my IP for me</span></span>
|
||
<span id="cb28-10"><a href="system-calls-or-bust.html#cb28-10"></a></span>
|
||
<span id="cb28-11"><a href="system-calls-or-bust.html#cb28-11"></a>getaddrinfo<span class="op">(</span>NULL<span class="op">,</span> <span class="st">"3490"</span><span class="op">,</span> <span class="op">&</span>hints<span class="op">,</span> <span class="op">&</span>res<span class="op">);</span></span>
|
||
<span id="cb28-12"><a href="system-calls-or-bust.html#cb28-12"></a></span>
|
||
<span id="cb28-13"><a href="system-calls-or-bust.html#cb28-13"></a><span class="co">// make a socket:</span></span>
|
||
<span id="cb28-14"><a href="system-calls-or-bust.html#cb28-14"></a></span>
|
||
<span id="cb28-15"><a href="system-calls-or-bust.html#cb28-15"></a>sockfd <span class="op">=</span> socket<span class="op">(</span>res<span class="op">-></span>ai_family<span class="op">,</span> res<span class="op">-></span>ai_socktype<span class="op">,</span> res<span class="op">-></span>ai_protocol<span class="op">);</span></span>
|
||
<span id="cb28-16"><a href="system-calls-or-bust.html#cb28-16"></a></span>
|
||
<span id="cb28-17"><a href="system-calls-or-bust.html#cb28-17"></a><span class="co">// bind it to the port we passed in to getaddrinfo():</span></span>
|
||
<span id="cb28-18"><a href="system-calls-or-bust.html#cb28-18"></a></span>
|
||
<span id="cb28-19"><a href="system-calls-or-bust.html#cb28-19"></a>bind<span class="op">(</span>sockfd<span class="op">,</span> res<span class="op">-></span>ai_addr<span class="op">,</span> res<span class="op">-></span>ai_addrlen<span class="op">);</span></span></code></pre></div>
|
||
<p>By using the <code>AI_PASSIVE</code> flag, I’m telling the program to bind to the IP of the host it’s running on. If you want to bind to a specific local IP address, drop the <code>AI_PASSIVE</code> and put an IP address in for the first argument to <code>getaddrinfo()</code>.</p>
|
||
<p><code>bind()</code> also returns <code>-1</code> on error and sets <code>errno</code> to the error’s value.</p>
|
||
<p>Lots of old code manually packs the <code>struct sockaddr_in</code> before calling <code>bind()</code>. Obviously this is IPv4-specific, but there’s really nothing stopping you from doing the same thing with IPv6, except that using <code>getaddrinfo()</code> is going to be easier, generally. Anyway, the old code looks something like this:</p>
|
||
<div class="sourceCode" id="cb29"><pre class="sourceCode numberSource c numberLines"><code class="sourceCode c"><span id="cb29-1"><a href="system-calls-or-bust.html#cb29-1"></a><span class="co">// !!! THIS IS THE OLD WAY !!!</span></span>
|
||
<span id="cb29-2"><a href="system-calls-or-bust.html#cb29-2"></a></span>
|
||
<span id="cb29-3"><a href="system-calls-or-bust.html#cb29-3"></a><span class="dt">int</span> sockfd<span class="op">;</span></span>
|
||
<span id="cb29-4"><a href="system-calls-or-bust.html#cb29-4"></a><span class="kw">struct</span> sockaddr_in my_addr<span class="op">;</span></span>
|
||
<span id="cb29-5"><a href="system-calls-or-bust.html#cb29-5"></a></span>
|
||
<span id="cb29-6"><a href="system-calls-or-bust.html#cb29-6"></a>sockfd <span class="op">=</span> socket<span class="op">(</span>PF_INET<span class="op">,</span> SOCK_STREAM<span class="op">,</span> <span class="dv">0</span><span class="op">);</span></span>
|
||
<span id="cb29-7"><a href="system-calls-or-bust.html#cb29-7"></a></span>
|
||
<span id="cb29-8"><a href="system-calls-or-bust.html#cb29-8"></a>my_addr<span class="op">.</span>sin_family <span class="op">=</span> AF_INET<span class="op">;</span></span>
|
||
<span id="cb29-9"><a href="system-calls-or-bust.html#cb29-9"></a>my_addr<span class="op">.</span>sin_port <span class="op">=</span> htons<span class="op">(</span>MYPORT<span class="op">);</span> <span class="co">// short, network byte order</span></span>
|
||
<span id="cb29-10"><a href="system-calls-or-bust.html#cb29-10"></a>my_addr<span class="op">.</span>sin_addr<span class="op">.</span>s_addr <span class="op">=</span> inet_addr<span class="op">(</span><span class="st">"10.12.110.57"</span><span class="op">);</span></span>
|
||
<span id="cb29-11"><a href="system-calls-or-bust.html#cb29-11"></a>memset<span class="op">(</span>my_addr<span class="op">.</span>sin_zero<span class="op">,</span> <span class="ch">'</span><span class="sc">\0</span><span class="ch">'</span><span class="op">,</span> <span class="kw">sizeof</span> my_addr<span class="op">.</span>sin_zero<span class="op">);</span></span>
|
||
<span id="cb29-12"><a href="system-calls-or-bust.html#cb29-12"></a></span>
|
||
<span id="cb29-13"><a href="system-calls-or-bust.html#cb29-13"></a>bind<span class="op">(</span>sockfd<span class="op">,</span> <span class="op">(</span><span class="kw">struct</span> sockaddr <span class="op">*)&</span>my_addr<span class="op">,</span> <span class="kw">sizeof</span> my_addr<span class="op">);</span></span></code></pre></div>
|
||
<p>In the above code, you could also assign <code>INADDR_ANY</code> to the <code>s_addr</code> field if you wanted to bind to your local IP address (like the <code>AI_PASSIVE</code> flag, above). The IPv6 version of <code>INADDR_ANY</code> is a global variable <code>in6addr_any</code> that is assigned into the <code>sin6_addr</code> field of your <code>struct sockaddr_in6</code>. (There is also a macro <code>IN6ADDR_ANY_INIT</code> that you can use in a variable initializer.)</p>
|
||
<p>Another thing to watch out for when calling <code>bind()</code>: don’t go underboard with your port numbers. All ports below 1024 are RESERVED (unless you’re the superuser)! You can have any port number above that, right up to 65535 (provided they aren’t already being used by another program).</p>
|
||
<p>Sometimes, you might notice, you try to rerun a server and <code>bind()</code> fails, claiming “Address already in use.” What does that mean? Well, a little bit of a socket that was connected is still hanging around in the kernel, and it’s hogging the port. You can either wait for it to clear (a minute or so), or add code to your program allowing it to reuse the port, like this:</p>
|
||
<p> </p>
|
||
<div class="sourceCode" id="cb30"><pre class="sourceCode numberSource c numberLines"><code class="sourceCode c"><span id="cb30-1"><a href="system-calls-or-bust.html#cb30-1"></a><span class="dt">int</span> yes<span class="op">=</span><span class="dv">1</span><span class="op">;</span></span>
|
||
<span id="cb30-2"><a href="system-calls-or-bust.html#cb30-2"></a><span class="co">//char yes='1'; // Solaris people use this</span></span>
|
||
<span id="cb30-3"><a href="system-calls-or-bust.html#cb30-3"></a></span>
|
||
<span id="cb30-4"><a href="system-calls-or-bust.html#cb30-4"></a><span class="co">// lose the pesky "Address already in use" error message</span></span>
|
||
<span id="cb30-5"><a href="system-calls-or-bust.html#cb30-5"></a><span class="cf">if</span> <span class="op">(</span>setsockopt<span class="op">(</span>listener<span class="op">,</span>SOL_SOCKET<span class="op">,</span>SO_REUSEADDR<span class="op">,&</span>yes<span class="op">,</span><span class="kw">sizeof</span> yes<span class="op">)</span> <span class="op">==</span> <span class="op">-</span><span class="dv">1</span><span class="op">)</span> <span class="op">{</span></span>
|
||
<span id="cb30-6"><a href="system-calls-or-bust.html#cb30-6"></a> perror<span class="op">(</span><span class="st">"setsockopt"</span><span class="op">);</span></span>
|
||
<span id="cb30-7"><a href="system-calls-or-bust.html#cb30-7"></a> exit<span class="op">(</span><span class="dv">1</span><span class="op">);</span></span>
|
||
<span id="cb30-8"><a href="system-calls-or-bust.html#cb30-8"></a><span class="op">}</span> </span></code></pre></div>
|
||
<p> One small extra final note about <code>bind()</code>: there are times when you won’t absolutely have to call it. If you are <code>connect()</code>ing to a remote machine and you don’t care what your local port is (as is the case with <code>telnet</code> where you only care about the remote port), you can simply call <code>connect()</code>, it’ll check to see if the socket is unbound, and will <code>bind()</code> it to an unused local port if necessary.</p>
|
||
<h2 data-number="5.4" id="connect"><span class="header-section-number">5.4</span> <code>connect()</code>—Hey, you!</h2>
|
||
<p> Let’s just pretend for a few minutes that you’re a telnet application. Your user commands you (just like in the movie <em>TRON</em>) to get a socket file descriptor. You comply and call <code>socket()</code>. Next, the user tells you to connect to “<code>10.12.110.57</code>” on port “<code>23</code>” (the standard telnet port). Yow! What do you do now?</p>
|
||
<p>Lucky for you, program, you’re now perusing the section on <code>connect()</code>—how to connect to a remote host. So read furiously onward! No time to lose!</p>
|
||
<p>The <code>connect()</code> call is as follows:</p>
|
||
<div class="sourceCode" id="cb31"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb31-1"><a href="system-calls-or-bust.html#cb31-1" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im"><sys/types.h></span></span>
|
||
<span id="cb31-2"><a href="system-calls-or-bust.html#cb31-2" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im"><sys/socket.h></span></span>
|
||
<span id="cb31-3"><a href="system-calls-or-bust.html#cb31-3" aria-hidden="true" tabindex="-1"></a></span>
|
||
<span id="cb31-4"><a href="system-calls-or-bust.html#cb31-4" aria-hidden="true" tabindex="-1"></a><span class="dt">int</span> connect<span class="op">(</span><span class="dt">int</span> sockfd<span class="op">,</span> <span class="kw">struct</span> sockaddr <span class="op">*</span>serv_addr<span class="op">,</span> <span class="dt">int</span> addrlen<span class="op">);</span> </span></code></pre></div>
|
||
<p><code>sockfd</code> is our friendly neighborhood socket file descriptor, as returned by the <code>socket()</code> call, <code>serv_addr</code> is a <code>struct sockaddr</code> containing the destination port and IP address, and <code>addrlen</code> is the length in bytes of the server address structure.</p>
|
||
<p>All of this information can be gleaned from the results of the <code>getaddrinfo()</code> call, which rocks.</p>
|
||
<p>Is this starting to make more sense? I can’t hear you from here, so I’ll just have to hope that it is. Let’s have an example where we make a socket connection to “<code>www.example.com</code>”, port <code>3490</code>:</p>
|
||
<div class="sourceCode" id="cb32"><pre class="sourceCode numberSource c numberLines"><code class="sourceCode c"><span id="cb32-1"><a href="system-calls-or-bust.html#cb32-1"></a><span class="kw">struct</span> addrinfo hints<span class="op">,</span> <span class="op">*</span>res<span class="op">;</span></span>
|
||
<span id="cb32-2"><a href="system-calls-or-bust.html#cb32-2"></a><span class="dt">int</span> sockfd<span class="op">;</span></span>
|
||
<span id="cb32-3"><a href="system-calls-or-bust.html#cb32-3"></a></span>
|
||
<span id="cb32-4"><a href="system-calls-or-bust.html#cb32-4"></a><span class="co">// first, load up address structs with getaddrinfo():</span></span>
|
||
<span id="cb32-5"><a href="system-calls-or-bust.html#cb32-5"></a></span>
|
||
<span id="cb32-6"><a href="system-calls-or-bust.html#cb32-6"></a>memset<span class="op">(&</span>hints<span class="op">,</span> <span class="dv">0</span><span class="op">,</span> <span class="kw">sizeof</span> hints<span class="op">);</span></span>
|
||
<span id="cb32-7"><a href="system-calls-or-bust.html#cb32-7"></a>hints<span class="op">.</span>ai_family <span class="op">=</span> AF_UNSPEC<span class="op">;</span></span>
|
||
<span id="cb32-8"><a href="system-calls-or-bust.html#cb32-8"></a>hints<span class="op">.</span>ai_socktype <span class="op">=</span> SOCK_STREAM<span class="op">;</span></span>
|
||
<span id="cb32-9"><a href="system-calls-or-bust.html#cb32-9"></a></span>
|
||
<span id="cb32-10"><a href="system-calls-or-bust.html#cb32-10"></a>getaddrinfo<span class="op">(</span><span class="st">"www.example.com"</span><span class="op">,</span> <span class="st">"3490"</span><span class="op">,</span> <span class="op">&</span>hints<span class="op">,</span> <span class="op">&</span>res<span class="op">);</span></span>
|
||
<span id="cb32-11"><a href="system-calls-or-bust.html#cb32-11"></a></span>
|
||
<span id="cb32-12"><a href="system-calls-or-bust.html#cb32-12"></a><span class="co">// make a socket:</span></span>
|
||
<span id="cb32-13"><a href="system-calls-or-bust.html#cb32-13"></a></span>
|
||
<span id="cb32-14"><a href="system-calls-or-bust.html#cb32-14"></a>sockfd <span class="op">=</span> socket<span class="op">(</span>res<span class="op">-></span>ai_family<span class="op">,</span> res<span class="op">-></span>ai_socktype<span class="op">,</span> res<span class="op">-></span>ai_protocol<span class="op">);</span></span>
|
||
<span id="cb32-15"><a href="system-calls-or-bust.html#cb32-15"></a></span>
|
||
<span id="cb32-16"><a href="system-calls-or-bust.html#cb32-16"></a><span class="co">// connect!</span></span>
|
||
<span id="cb32-17"><a href="system-calls-or-bust.html#cb32-17"></a></span>
|
||
<span id="cb32-18"><a href="system-calls-or-bust.html#cb32-18"></a>connect<span class="op">(</span>sockfd<span class="op">,</span> res<span class="op">-></span>ai_addr<span class="op">,</span> res<span class="op">-></span>ai_addrlen<span class="op">);</span></span></code></pre></div>
|
||
<p>Again, old-school programs filled out their own <code>struct sockaddr_in</code>s to pass to <code>connect()</code>. You can do that if you want to. See the similar note in the <a href="system-calls-or-bust.html#bind"><code>bind()</code> section</a>, above.</p>
|
||
<p>Be sure to check the return value from <code>connect()</code>—it’ll return <code>-1</code> on error and set the variable <code>errno</code>.</p>
|
||
<p></p>
|
||
<p>Also, notice that we didn’t call <code>bind()</code>. Basically, we don’t care about our local port number; we only care where we’re going (the remote port). The kernel will choose a local port for us, and the site we connect to will automatically get this information from us. No worries.</p>
|
||
<h2 data-number="5.5" id="listen"><span class="header-section-number">5.5</span> <code>listen()</code>—Will somebody please call me?</h2>
|
||
<p> OK, time for a change of pace. What if you don’t want to connect 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 you <code>listen()</code>, then you <code>accept()</code> (see below).</p>
|
||
<p>The <code>listen()</code> call is fairly simple, but requires a bit of explanation:</p>
|
||
<div class="sourceCode" id="cb33"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb33-1"><a href="system-calls-or-bust.html#cb33-1" aria-hidden="true" tabindex="-1"></a><span class="dt">int</span> listen<span class="op">(</span><span class="dt">int</span> sockfd<span class="op">,</span> <span class="dt">int</span> backlog<span class="op">);</span> </span></code></pre></div>
|
||
<p><code>sockfd</code> is the usual socket file descriptor from the <code>socket()</code> system call. <code>backlog</code> is the number of connections allowed on the incoming queue. What does that mean? Well, incoming connections are going to wait in this queue until you <code>accept()</code> them (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 setting it to <code>5</code> or <code>10</code>.</p>
|
||
<p>Again, as per usual, <code>listen()</code> returns <code>-1</code> and sets <code>errno</code> on error.</p>
|
||
<p>Well, as you can probably imagine, we need to call <code>bind()</code> before we call <code>listen()</code> so that the server is running on a specific port. (You have to be able to tell your buddies which port to connect to!) So if you’re going to be listening for incoming connections, the sequence of system calls you’ll make is:</p>
|
||
<div class="sourceCode" id="cb34"><pre class="sourceCode numberSource c numberLines"><code class="sourceCode c"><span id="cb34-1"><a href="system-calls-or-bust.html#cb34-1"></a>getaddrinfo<span class="op">();</span></span>
|
||
<span id="cb34-2"><a href="system-calls-or-bust.html#cb34-2"></a>socket<span class="op">();</span></span>
|
||
<span id="cb34-3"><a href="system-calls-or-bust.html#cb34-3"></a>bind<span class="op">();</span></span>
|
||
<span id="cb34-4"><a href="system-calls-or-bust.html#cb34-4"></a>listen<span class="op">();</span></span>
|
||
<span id="cb34-5"><a href="system-calls-or-bust.html#cb34-5"></a><span class="co">/* accept() goes here */</span> </span></code></pre></div>
|
||
<p>I’ll just leave that in the place of sample code, since it’s fairly self-explanatory. (The code in the <code>accept()</code> section, below, is more complete.) The really tricky part of this whole sha-bang is the call to <code>accept()</code>.</p>
|
||
<h2 data-number="5.6" id="acceptthank-you-for-calling-port-3490."><span class="header-section-number">5.6</span> <code>accept()</code>—“Thank you for calling port 3490.”</h2>
|
||
<p> Get ready—the <code>accept()</code> call is kinda weird! What’s going to happen is this: someone far far away will try to <code>connect()</code> to your machine on a port that you are <code>listen()</code>ing on. Their connection will be queued up waiting to be <code>accept()</code>ed. You call <code>accept()</code> and you tell it to get the pending connection. It’ll return to you a <em>brand new socket file descriptor</em> to use for this single connection! That’s right, suddenly you have <em>two socket file descriptors</em> for the price of one! The original one is still listening for more new connections, and the newly created one is finally ready to <code>send()</code> and <code>recv()</code>. We’re there!</p>
|
||
<p>The call is as follows:</p>
|
||
<div class="sourceCode" id="cb35"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb35-1"><a href="system-calls-or-bust.html#cb35-1" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im"><sys/types.h></span></span>
|
||
<span id="cb35-2"><a href="system-calls-or-bust.html#cb35-2" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im"><sys/socket.h></span></span>
|
||
<span id="cb35-3"><a href="system-calls-or-bust.html#cb35-3" aria-hidden="true" tabindex="-1"></a></span>
|
||
<span id="cb35-4"><a href="system-calls-or-bust.html#cb35-4" aria-hidden="true" tabindex="-1"></a><span class="dt">int</span> accept<span class="op">(</span><span class="dt">int</span> sockfd<span class="op">,</span> <span class="kw">struct</span> sockaddr <span class="op">*</span>addr<span class="op">,</span> socklen_t <span class="op">*</span>addrlen<span class="op">);</span> </span></code></pre></div>
|
||
<p><code>sockfd</code> is the <code>listen()</code>ing socket descriptor. Easy enough. <code>addr</code> will usually be a pointer to a local <code>struct sockaddr_storage</code>. This is where the information about the incoming connection will go (and with it you can determine which host is calling you from which port). <code>addrlen</code> is a local integer variable that should be set to <code>sizeof(struct sockaddr_storage)</code> before its address is passed to <code>accept()</code>. <code>accept()</code> will not put more than that many bytes into <code>addr</code>. If it puts fewer in, it’ll change the value of <code>addrlen</code> to reflect that.</p>
|
||
<p>Guess what? <code>accept()</code> returns <code>-1</code> and sets <code>errno</code> if an error occurs. Betcha didn’t figure that.</p>
|
||
<p>Like before, this is a bunch to absorb in one chunk, so here’s a sample code fragment for your perusal:</p>
|
||
<div class="sourceCode" id="cb36"><pre class="sourceCode numberSource c numberLines"><code class="sourceCode c"><span id="cb36-1"><a href="system-calls-or-bust.html#cb36-1"></a><span class="pp">#include </span><span class="im"><string.h></span></span>
|
||
<span id="cb36-2"><a href="system-calls-or-bust.html#cb36-2"></a><span class="pp">#include </span><span class="im"><sys/types.h></span></span>
|
||
<span id="cb36-3"><a href="system-calls-or-bust.html#cb36-3"></a><span class="pp">#include </span><span class="im"><sys/socket.h></span></span>
|
||
<span id="cb36-4"><a href="system-calls-or-bust.html#cb36-4"></a><span class="pp">#include </span><span class="im"><netdb.h></span></span>
|
||
<span id="cb36-5"><a href="system-calls-or-bust.html#cb36-5"></a></span>
|
||
<span id="cb36-6"><a href="system-calls-or-bust.html#cb36-6"></a><span class="pp">#define MYPORT </span><span class="st">"3490"</span><span class="pp"> </span><span class="co">// the port users will be connecting to</span></span>
|
||
<span id="cb36-7"><a href="system-calls-or-bust.html#cb36-7"></a><span class="pp">#define BACKLOG </span><span class="dv">10</span><span class="pp"> </span><span class="co">// how many pending connections queue will hold</span></span>
|
||
<span id="cb36-8"><a href="system-calls-or-bust.html#cb36-8"></a></span>
|
||
<span id="cb36-9"><a href="system-calls-or-bust.html#cb36-9"></a><span class="dt">int</span> main<span class="op">(</span><span class="dt">void</span><span class="op">)</span></span>
|
||
<span id="cb36-10"><a href="system-calls-or-bust.html#cb36-10"></a><span class="op">{</span></span>
|
||
<span id="cb36-11"><a href="system-calls-or-bust.html#cb36-11"></a> <span class="kw">struct</span> sockaddr_storage their_addr<span class="op">;</span></span>
|
||
<span id="cb36-12"><a href="system-calls-or-bust.html#cb36-12"></a> socklen_t addr_size<span class="op">;</span></span>
|
||
<span id="cb36-13"><a href="system-calls-or-bust.html#cb36-13"></a> <span class="kw">struct</span> addrinfo hints<span class="op">,</span> <span class="op">*</span>res<span class="op">;</span></span>
|
||
<span id="cb36-14"><a href="system-calls-or-bust.html#cb36-14"></a> <span class="dt">int</span> sockfd<span class="op">,</span> new_fd<span class="op">;</span></span>
|
||
<span id="cb36-15"><a href="system-calls-or-bust.html#cb36-15"></a></span>
|
||
<span id="cb36-16"><a href="system-calls-or-bust.html#cb36-16"></a> <span class="co">// !! don't forget your error checking for these calls !!</span></span>
|
||
<span id="cb36-17"><a href="system-calls-or-bust.html#cb36-17"></a></span>
|
||
<span id="cb36-18"><a href="system-calls-or-bust.html#cb36-18"></a> <span class="co">// first, load up address structs with getaddrinfo():</span></span>
|
||
<span id="cb36-19"><a href="system-calls-or-bust.html#cb36-19"></a></span>
|
||
<span id="cb36-20"><a href="system-calls-or-bust.html#cb36-20"></a> memset<span class="op">(&</span>hints<span class="op">,</span> <span class="dv">0</span><span class="op">,</span> <span class="kw">sizeof</span> hints<span class="op">);</span></span>
|
||
<span id="cb36-21"><a href="system-calls-or-bust.html#cb36-21"></a> hints<span class="op">.</span>ai_family <span class="op">=</span> AF_UNSPEC<span class="op">;</span> <span class="co">// use IPv4 or IPv6, whichever</span></span>
|
||
<span id="cb36-22"><a href="system-calls-or-bust.html#cb36-22"></a> hints<span class="op">.</span>ai_socktype <span class="op">=</span> SOCK_STREAM<span class="op">;</span></span>
|
||
<span id="cb36-23"><a href="system-calls-or-bust.html#cb36-23"></a> hints<span class="op">.</span>ai_flags <span class="op">=</span> AI_PASSIVE<span class="op">;</span> <span class="co">// fill in my IP for me</span></span>
|
||
<span id="cb36-24"><a href="system-calls-or-bust.html#cb36-24"></a></span>
|
||
<span id="cb36-25"><a href="system-calls-or-bust.html#cb36-25"></a> getaddrinfo<span class="op">(</span>NULL<span class="op">,</span> MYPORT<span class="op">,</span> <span class="op">&</span>hints<span class="op">,</span> <span class="op">&</span>res<span class="op">);</span></span>
|
||
<span id="cb36-26"><a href="system-calls-or-bust.html#cb36-26"></a></span>
|
||
<span id="cb36-27"><a href="system-calls-or-bust.html#cb36-27"></a> <span class="co">// make a socket, bind it, and listen on it:</span></span>
|
||
<span id="cb36-28"><a href="system-calls-or-bust.html#cb36-28"></a></span>
|
||
<span id="cb36-29"><a href="system-calls-or-bust.html#cb36-29"></a> sockfd <span class="op">=</span> socket<span class="op">(</span>res<span class="op">-></span>ai_family<span class="op">,</span> res<span class="op">-></span>ai_socktype<span class="op">,</span> res<span class="op">-></span>ai_protocol<span class="op">);</span></span>
|
||
<span id="cb36-30"><a href="system-calls-or-bust.html#cb36-30"></a> bind<span class="op">(</span>sockfd<span class="op">,</span> res<span class="op">-></span>ai_addr<span class="op">,</span> res<span class="op">-></span>ai_addrlen<span class="op">);</span></span>
|
||
<span id="cb36-31"><a href="system-calls-or-bust.html#cb36-31"></a> listen<span class="op">(</span>sockfd<span class="op">,</span> BACKLOG<span class="op">);</span></span>
|
||
<span id="cb36-32"><a href="system-calls-or-bust.html#cb36-32"></a></span>
|
||
<span id="cb36-33"><a href="system-calls-or-bust.html#cb36-33"></a> <span class="co">// now accept an incoming connection:</span></span>
|
||
<span id="cb36-34"><a href="system-calls-or-bust.html#cb36-34"></a></span>
|
||
<span id="cb36-35"><a href="system-calls-or-bust.html#cb36-35"></a> addr_size <span class="op">=</span> <span class="kw">sizeof</span> their_addr<span class="op">;</span></span>
|
||
<span id="cb36-36"><a href="system-calls-or-bust.html#cb36-36"></a> new_fd <span class="op">=</span> accept<span class="op">(</span>sockfd<span class="op">,</span> <span class="op">(</span><span class="kw">struct</span> sockaddr <span class="op">*)&</span>their_addr<span class="op">,</span> <span class="op">&</span>addr_size<span class="op">);</span></span>
|
||
<span id="cb36-37"><a href="system-calls-or-bust.html#cb36-37"></a></span>
|
||
<span id="cb36-38"><a href="system-calls-or-bust.html#cb36-38"></a> <span class="co">// ready to communicate on socket descriptor new_fd!</span></span>
|
||
<span id="cb36-39"><a href="system-calls-or-bust.html#cb36-39"></a> <span class="op">.</span></span>
|
||
<span id="cb36-40"><a href="system-calls-or-bust.html#cb36-40"></a> <span class="op">.</span></span>
|
||
<span id="cb36-41"><a href="system-calls-or-bust.html#cb36-41"></a> <span class="op">.</span></span></code></pre></div>
|
||
<p>Again, note that we will use the socket descriptor <code>new_fd</code> for all <code>send()</code> and <code>recv()</code> calls. If you’re only getting one single connection ever, you can <code>close()</code> the listening <code>sockfd</code> in order to prevent more incoming connections on the same port, if you so desire.</p>
|
||
<h2 data-number="5.7" id="sendrecv"><span class="header-section-number">5.7</span> <code>send()</code> and <code>recv()</code>—Talk to me, baby!</h2>
|
||
<p>These two functions are for communicating over stream sockets or connected datagram sockets. If you want to use regular unconnected datagram sockets, you’ll need to see the section on <a href="system-calls-or-bust.html#sendtorecv"><code>sendto()</code> and <code>recvfrom()</code></a>, below.</p>
|
||
<p> The <code>send()</code> call:</p>
|
||
<div class="sourceCode" id="cb37"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb37-1"><a href="system-calls-or-bust.html#cb37-1" aria-hidden="true" tabindex="-1"></a><span class="dt">int</span> send<span class="op">(</span><span class="dt">int</span> sockfd<span class="op">,</span> <span class="dt">const</span> <span class="dt">void</span> <span class="op">*</span>msg<span class="op">,</span> <span class="dt">int</span> len<span class="op">,</span> <span class="dt">int</span> flags<span class="op">);</span> </span></code></pre></div>
|
||
<p><code>sockfd</code> is the socket descriptor you want to send data to (whether it’s the one returned by <code>socket()</code> or the one you got with <code>accept()</code>). <code>msg</code> is a pointer to the data you want to send, and <code>len</code> is the length of that data in bytes. Just set <code>flags</code> to <code>0</code>. (See the <code>send()</code> man page for more information concerning flags.)</p>
|
||
<p>Some sample code might be:</p>
|
||
<div class="sourceCode" id="cb38"><pre class="sourceCode numberSource c numberLines"><code class="sourceCode c"><span id="cb38-1"><a href="system-calls-or-bust.html#cb38-1"></a><span class="dt">char</span> <span class="op">*</span>msg <span class="op">=</span> <span class="st">"Beej was here!"</span><span class="op">;</span></span>
|
||
<span id="cb38-2"><a href="system-calls-or-bust.html#cb38-2"></a><span class="dt">int</span> len<span class="op">,</span> bytes_sent<span class="op">;</span></span>
|
||
<span id="cb38-3"><a href="system-calls-or-bust.html#cb38-3"></a><span class="op">.</span></span>
|
||
<span id="cb38-4"><a href="system-calls-or-bust.html#cb38-4"></a><span class="op">.</span></span>
|
||
<span id="cb38-5"><a href="system-calls-or-bust.html#cb38-5"></a><span class="op">.</span></span>
|
||
<span id="cb38-6"><a href="system-calls-or-bust.html#cb38-6"></a>len <span class="op">=</span> strlen<span class="op">(</span>msg<span class="op">);</span></span>
|
||
<span id="cb38-7"><a href="system-calls-or-bust.html#cb38-7"></a>bytes_sent <span class="op">=</span> send<span class="op">(</span>sockfd<span class="op">,</span> msg<span class="op">,</span> len<span class="op">,</span> <span class="dv">0</span><span class="op">);</span></span>
|
||
<span id="cb38-8"><a href="system-calls-or-bust.html#cb38-8"></a><span class="op">.</span></span>
|
||
<span id="cb38-9"><a href="system-calls-or-bust.html#cb38-9"></a><span class="op">.</span></span>
|
||
<span id="cb38-10"><a href="system-calls-or-bust.html#cb38-10"></a><span class="op">.</span> </span></code></pre></div>
|
||
<p><code>send()</code> returns the number of bytes actually sent out—<em>this might be less than the number you told it to send!</em> See, sometimes you tell it to send a whole gob of data and it just can’t handle it. It’ll fire off as much of the data as it can, and trust you to send the rest later. Remember, if the value returned by <code>send()</code> doesn’t match the value in <code>len</code>, it’s up to you to send the rest of the string. The good news is this: if the packet is small (less than 1K or so) it will <em>probably</em> manage to send the whole thing all in one go. Again, <code>-1</code> is returned on error, and <code>errno</code> is set to the error number.</p>
|
||
<p> The <code>recv()</code> call is similar in many respects:</p>
|
||
<div class="sourceCode" id="cb39"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb39-1"><a href="system-calls-or-bust.html#cb39-1" aria-hidden="true" tabindex="-1"></a><span class="dt">int</span> recv<span class="op">(</span><span class="dt">int</span> sockfd<span class="op">,</span> <span class="dt">void</span> <span class="op">*</span>buf<span class="op">,</span> <span class="dt">int</span> len<span class="op">,</span> <span class="dt">int</span> flags<span class="op">);</span></span></code></pre></div>
|
||
<p><code>sockfd</code> is the socket descriptor to read from, <code>buf</code> is the buffer to read the information into, <code>len</code> is the maximum length of the buffer, and <code>flags</code> can again be set to <code>0</code>. (See the <code>recv()</code> man page for flag information.)</p>
|
||
<p><code>recv()</code> returns the number of bytes actually read into the buffer, or <code>-1</code> on error (with <code>errno</code> set, accordingly).</p>
|
||
<p>Wait! <code>recv()</code> can return <code>0</code>. This can mean only one thing: the remote side has closed the connection on you! A return value of <code>0</code> is <code>recv()</code>’s way of letting you know this has occurred.</p>
|
||
<p>There, that was easy, wasn’t it? You can now pass data back and forth on stream sockets! Whee! You’re a Unix Network Programmer!</p>
|
||
<h2 data-number="5.8" id="sendtorecv"><span class="header-section-number">5.8</span> <code>sendto()</code> and <code>recvfrom()</code>—Talk to me, DGRAM-style</h2>
|
||
<p> “This is all fine and dandy,” I hear you saying, “but where does this leave me with unconnected datagram sockets?” No problemo, amigo. We have just the thing.</p>
|
||
<p>Since datagram sockets aren’t connected to a remote host, guess which piece of information we need to give before we send a packet? That’s right! The destination address! Here’s the scoop:</p>
|
||
<div class="sourceCode" id="cb40"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb40-1"><a href="system-calls-or-bust.html#cb40-1" aria-hidden="true" tabindex="-1"></a><span class="dt">int</span> sendto<span class="op">(</span><span class="dt">int</span> sockfd<span class="op">,</span> <span class="dt">const</span> <span class="dt">void</span> <span class="op">*</span>msg<span class="op">,</span> <span class="dt">int</span> len<span class="op">,</span> <span class="dt">unsigned</span> <span class="dt">int</span> flags<span class="op">,</span></span>
|
||
<span id="cb40-2"><a href="system-calls-or-bust.html#cb40-2" aria-hidden="true" tabindex="-1"></a> <span class="dt">const</span> <span class="kw">struct</span> sockaddr <span class="op">*</span>to<span class="op">,</span> socklen_t tolen<span class="op">);</span> </span></code></pre></div>
|
||
<p>As you can see, this call is basically the same as the call to <code>send()</code> with the addition of two other pieces of information. <code>to</code> is a pointer to a <code>struct sockaddr</code> (which will probably be another <code>struct sockaddr_in</code> or <code>struct sockaddr_in6</code> or <code>struct sockaddr_storage</code> that you cast at the last minute) which contains the destination IP address and port. <code>tolen</code>, an <code>int</code> deep-down, can simply be set to <code>sizeof *to</code> or <code>sizeof(struct sockaddr_storage)</code>.</p>
|
||
<p>To get your hands on the destination address structure, you’ll probably either get it from <code>getaddrinfo()</code>, or from <code>recvfrom()</code>, below, or you’ll fill it out by hand.</p>
|
||
<p>Just like with <code>send()</code>, <code>sendto()</code> returns the number of bytes actually sent (which, again, might be less than the number of bytes you told it to send!), or <code>-1</code> on error.</p>
|
||
<p>Equally similar are <code>recv()</code> and <code>recvfrom()</code>. The synopsis of <code>recvfrom()</code> is:</p>
|
||
<div class="sourceCode" id="cb41"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb41-1"><a href="system-calls-or-bust.html#cb41-1" aria-hidden="true" tabindex="-1"></a><span class="dt">int</span> recvfrom<span class="op">(</span><span class="dt">int</span> sockfd<span class="op">,</span> <span class="dt">void</span> <span class="op">*</span>buf<span class="op">,</span> <span class="dt">int</span> len<span class="op">,</span> <span class="dt">unsigned</span> <span class="dt">int</span> flags<span class="op">,</span></span>
|
||
<span id="cb41-2"><a href="system-calls-or-bust.html#cb41-2" aria-hidden="true" tabindex="-1"></a> <span class="kw">struct</span> sockaddr <span class="op">*</span>from<span class="op">,</span> <span class="dt">int</span> <span class="op">*</span>fromlen<span class="op">);</span> </span></code></pre></div>
|
||
<p>Again, this is just like <code>recv()</code> with the addition of a couple fields. <code>from</code> is a pointer to a local <code>struct sockaddr_storage</code> that will be filled with the IP address and port of the originating machine. <code>fromlen</code> is a pointer to a local <code>int</code> that should be initialized to <code>sizeof *from</code> or <code>sizeof(struct sockaddr_storage)</code>. When the function returns, <code>fromlen</code> will contain the length of the address actually stored in <code>from</code>.</p>
|
||
<p><code>recvfrom()</code> returns the number of bytes received, or <code>-1</code> on error (with <code>errno</code> set accordingly).</p>
|
||
<p>So, here’s a question: why do we use <code>struct sockaddr_storage</code> as the socket type? Why not <code>struct sockaddr_in</code>? Because, you see, we want to not tie ourselves down to IPv4 or IPv6. So we use the generic <code>struct sockaddr_storage</code> which we know will be big enough for either.</p>
|
||
<p>(So… here’s another question: why isn’t <code>struct sockaddr</code> itself big enough for any address? We even cast the general-purpose <code>struct sockaddr_storage</code> to the general-purpose <code>struct sockaddr</code>! Seems extraneous and redundant, huh. The answer is, it just isn’t big enough, and I’d guess that changing it at this point would be Problematic. So they made a new one.)</p>
|
||
<p>Remember, if you <code>connect()</code> a datagram socket, you can then simply use <code>send()</code> and <code>recv()</code> for all your transactions. The socket itself is still a datagram socket and the packets still use UDP, but the socket interface will automatically add the destination and source information for you.</p>
|
||
<h2 data-number="5.9" id="close-and-shutdownget-outta-my-face"><span class="header-section-number">5.9</span> <code>close()</code> and <code>shutdown()</code>—Get outta my face!</h2>
|
||
<p>Whew! You’ve been <code>send()</code>ing and <code>recv()</code>ing data all day long, and you’ve had it. You’re ready to close the connection on your socket descriptor. This is easy. You can just use the regular Unix file descriptor <code>close()</code> function:</p>
|
||
<div class="sourceCode" id="cb42"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb42-1"><a href="system-calls-or-bust.html#cb42-1" aria-hidden="true" tabindex="-1"></a>close<span class="op">(</span>sockfd<span class="op">);</span> </span></code></pre></div>
|
||
<p>This will prevent any more reads and writes to the socket. Anyone attempting to read or write the socket on the remote end will receive an error.</p>
|
||
<p>Just in case you want a little more control over how the socket closes, you can use the <code>shutdown()</code> function. It allows you to cut off communication in a certain direction, or both ways (just like <code>close()</code> does). Synopsis:</p>
|
||
<div class="sourceCode" id="cb43"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb43-1"><a href="system-calls-or-bust.html#cb43-1" aria-hidden="true" tabindex="-1"></a><span class="dt">int</span> shutdown<span class="op">(</span><span class="dt">int</span> sockfd<span class="op">,</span> <span class="dt">int</span> how<span class="op">);</span> </span></code></pre></div>
|
||
<p><code>sockfd</code> is the socket file descriptor you want to shutdown, and <code>how</code> is one of the following:</p>
|
||
<table>
|
||
<thead>
|
||
<tr class="header">
|
||
<th style="text-align: center;"><code>how</code></th>
|
||
<th>Effect</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
<tr class="odd">
|
||
<td style="text-align: center;"><code>0</code></td>
|
||
<td>Further receives are disallowed</td>
|
||
</tr>
|
||
<tr class="even">
|
||
<td style="text-align: center;"><code>1</code></td>
|
||
<td>Further sends are disallowed</td>
|
||
</tr>
|
||
<tr class="odd">
|
||
<td style="text-align: center;"><code>2</code></td>
|
||
<td>Further sends and receives are disallowed (like <code>close()</code>)</td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
<p><code>shutdown()</code> returns <code>0</code> on success, and <code>-1</code> on error (with <code>errno</code> set accordingly).</p>
|
||
<p>If you deign to use <code>shutdown()</code> on unconnected datagram sockets, it will simply make the socket unavailable for further <code>send()</code> and <code>recv()</code> calls (remember that you can use these if you <code>connect()</code> your datagram socket).</p>
|
||
<p>It’s important to note that <code>shutdown()</code> doesn’t actually close the file descriptor—it just changes its usability. To free a socket descriptor, you need to use <code>close()</code>.</p>
|
||
<p>Nothing to it.</p>
|
||
<p>(Except to remember that if you’re using Windows and Winsock that you should call <code>closesocket()</code> instead of <code>close()</code>.)</p>
|
||
<h2 data-number="5.10" id="getpeernamewho-are-you"><span class="header-section-number">5.10</span> <code>getpeername()</code>—Who are you?</h2>
|
||
<p> This function is so easy.</p>
|
||
<p>It’s so easy, I almost didn’t give it its own section. But here it is anyway.</p>
|
||
<p>The function <code>getpeername()</code> will tell you who is at the other end of a connected stream socket. The synopsis:</p>
|
||
<div class="sourceCode" id="cb44"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb44-1"><a href="system-calls-or-bust.html#cb44-1" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im"><sys/socket.h></span></span>
|
||
<span id="cb44-2"><a href="system-calls-or-bust.html#cb44-2" aria-hidden="true" tabindex="-1"></a></span>
|
||
<span id="cb44-3"><a href="system-calls-or-bust.html#cb44-3" aria-hidden="true" tabindex="-1"></a><span class="dt">int</span> getpeername<span class="op">(</span><span class="dt">int</span> sockfd<span class="op">,</span> <span class="kw">struct</span> sockaddr <span class="op">*</span>addr<span class="op">,</span> <span class="dt">int</span> <span class="op">*</span>addrlen<span class="op">);</span> </span></code></pre></div>
|
||
<p><code>sockfd</code> is the descriptor of the connected stream socket, <code>addr</code> is a pointer to a <code>struct sockaddr</code> (or a <code>struct sockaddr_in</code>) that will hold the information about the other side of the connection, and <code>addrlen</code> is a pointer to an <code>int</code>, that should be initialized to <code>sizeof *addr</code> or <code>sizeof(struct sockaddr)</code>.</p>
|
||
<p>The function returns <code>-1</code> on error and sets <code>errno</code> accordingly.</p>
|
||
<p>Once you have their address, you can use <code>inet_ntop()</code>, <code>getnameinfo()</code>, or <code>gethostbyaddr()</code> to print or get more information. No, you can’t get their login name. (Ok, ok. If the other computer is running an ident daemon, this is possible. This, however, is beyond the scope of this document. Check out <a href="https://tools.ietf.org/html/rfc1413">RFC 1413</a><a href="footnotes.html#fn22" class="footnote-ref" id="fnref22" role="doc-noteref"><sup>22</sup></a> for more info.)</p>
|
||
<h2 data-number="5.11" id="gethostnamewho-am-i"><span class="header-section-number">5.11</span> <code>gethostname()</code>—Who am I?</h2>
|
||
<p> Even easier than <code>getpeername()</code> is the function <code>gethostname()</code>. It returns the name of the computer that your program is running on. The name can then be used by <code>getaddrinfo()</code>, above, to determine the IP address of your local machine.</p>
|
||
<p>What could be more fun? I could think of a few things, but they don’t pertain to socket programming. Anyway, here’s the breakdown:</p>
|
||
<div class="sourceCode" id="cb45"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb45-1"><a href="system-calls-or-bust.html#cb45-1" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im"><unistd.h></span></span>
|
||
<span id="cb45-2"><a href="system-calls-or-bust.html#cb45-2" aria-hidden="true" tabindex="-1"></a></span>
|
||
<span id="cb45-3"><a href="system-calls-or-bust.html#cb45-3" aria-hidden="true" tabindex="-1"></a><span class="dt">int</span> gethostname<span class="op">(</span><span class="dt">char</span> <span class="op">*</span>hostname<span class="op">,</span> <span class="dt">size_t</span> size<span class="op">);</span> </span></code></pre></div>
|
||
<p>The arguments are simple: <code>hostname</code> is a pointer to an array of chars that will contain the hostname upon the function’s return, and <code>size</code> is the length in bytes of the <code>hostname</code> array.</p>
|
||
<p>The function returns <code>0</code> on successful completion, and <code>-1</code> on error, setting <code>errno</code> as usual.</p>
|
||
<hr><div style="text-align:center"><span><a href="jumping-from-ipv4-to-ipv6.html">Prev</a> | </span><a href="index.html">Contents</a><span> | <a href="client-server-background.html">Next</a></span></div></body>
|
||
</html>
|