Newer
Older
NetAddr-IP / tutorial.htm
  1. <HTML>
  2. <HEAD>
  3. <TITLE>A tutorial for NetAddr::IP</TITLE>
  4. </HEAD><BODY>
  5.  
  6. <tt>$Id: tutorial.htm,v 1.2 2002/10/31 04:30:23 lem Exp $</tt>
  7.  
  8. <a name="about"><h2>What this tutorial is all about...</h2></a>
  9.  
  10. <p>Some of us, monks who love Perl, also have to deal with the
  11. complexities of IP addresses, subnets and such. A while ago, I wrote <a
  12. href="http://search.cpan.org/search?mode=module&query=NetAddr%3A%3AIP">NetAddr::IP</a>
  13. to help me work out tedious tasks such as finding out which addresses
  14. fell within a certain subnet or allocating IP space to network
  15. devices.
  16.  
  17. <p>This tutorial discusses many common tasks along with solutions
  18. using <a
  19. href="http://search.cpan.org/search?mode=module&query=NetAddr%3A%3AIP">NetAddr::IP</a>.
  20. Since Perl lacks a native type to represent either an IP address or an
  21. IP subnet, I feel this module has been quite helpful for fellow monks
  22. who like me, need to work in this area.
  23.  
  24. <p>Note however that neither the module itself nor this tutorials are
  25. intended as replacements to your knowledge about how to work with
  26. chunks of IP space. The module was written as a tool to help with the
  27. boring tasks (after all, we're plentiful with good laziness, aren't
  28. we?) and this tutorial, was written to help answer the most common
  29. questions I get. Both the module and this tutorial expect you to be
  30. fluent in basic networking and somewhat fluent in Perl. You should not
  31. writing Perl code to manage your subnetting otherwise.
  32.  
  33. <hr>
  34.  
  35. <a name="new"><h2>Specifying an IP Address or a subnet</h2></a>
  36.  
  37. <p>A <a
  38. href="http://search.cpan.org/search?mode=module&query=NetAddr%3A%3AIP">NetAddr::IP</a>
  39. object represents a subnet. This involves storing an IP address
  40. <b>within</b> the subnet along with the subnet's netmask. Of course,
  41. using a host netmask (/32 or in decimal notation, 255.255.255.255)
  42. allows for the specification of a single IP address.
  43.  
  44. <p>You can create a <a
  45. href="http://search.cpan.org/search?mode=module&query=NetAddr%3A%3AIP">NetAddr::IP</a>
  46. object with an incantation like the following:
  47.  
  48. <PRE>
  49. use NetAddr::IP;
  50. my $ip = new NetAddr::IP '127.0.0.1';
  51. </PRE>
  52.  
  53. <p>which will create an object representing the 'address'
  54. <tt>127.0.0.1</tt> or the 'subnet' <tt>127.0.0.1/32</tt>.
  55.  
  56. <p>Creating a subnet is equally easy. Just specify the address and
  57. netmask in almost any common notation, as in the following examples:
  58.  
  59. <PRE>
  60. use NetAddr::IP;
  61. my $loopback = new NetAddr::IP '127.0.0.1', '255.0.0.0';
  62. my $rfc1918 = new NetAddr::IP '10.0.0.0/8';
  63. my $another = new NetAddr::IP '1.2.0.0/255.255.0.0';
  64. my $loopback2 = new NetAddr::IP 'loopback';
  65. </PRE>
  66.  
  67. <p>The following is a list of the acceptable arguments to
  68. <tt>->new()</tt> and their meanings:
  69.  
  70. <ul>
  71. <li><tt>->new('broadcast')</tt>
  72.  
  73. <p>Equivalent to the address <tt>255.255.255.255/32</tt> which is often
  74. used to denote a broadcast address.
  75.  
  76. <li><tt>->new('default')</tt>
  77.  
  78. <p>Synonim to the address <tt>0.0.0.0/0</tt> which is universally used
  79. to represent a default route. This subnet is guaranteed to
  80. <tt>->contains()</tt> any other subnet. More on that later.
  81.  
  82. <p>For the benefit of many Cisco users out there, <tt>any</tt> is
  83. considered a synonim of <tt>default</tt>.
  84.  
  85. <li><tt>->new('loopback')</tt>
  86.  
  87. <p>The same as the address <tt>127.0.0.1/8</tt> which is the standard
  88. <tt>loopback</tt> address.
  89.  
  90. <li><tt>->new('10.10.10.10')</tt> or <tt>->new('foo.bar.com')</tt>
  91.  
  92. <p>This represents a single host. When no netmask is supplied, a netmask
  93. of <tt>/32</tt> is assumed. When supplying a name, the host name will
  94. be looked up using <a
  95. href="http://www.perldoc.com/perl5.6.1/pod/perlfunc.html">gethostbyname()</a>,
  96. which will in turn use whatever name resolution is configured in your
  97. system to obtain the IP address associated with the supplied name.
  98.  
  99. <li><tt>->new('10.10.1')</tt>
  100.  
  101. <p>An ancient notation that allows the <em>middle zeroes</em> to be
  102. skipped. The example is equivalent to <tt>->new('10.10.0.1')</tt>.
  103.  
  104. <li><tt>->new('10.10.1.')</tt>
  105.  
  106. <p>Note the trailing dot. This format allows the omission of the
  107. netmask for classful subnets. The example is equivalent to
  108. <tt>->new('10.10.1.0/24')</tt>.
  109.  
  110. <li><tt>->new('10.10.10.0 - 10.10.10.255')</tt>
  111.  
  112. <p>This is also known as <em>range notation</em>. Both ends of an
  113. address range are specified. Note that this notation is only supported
  114. if the specified subnet can be represented in valid CIDR notation.
  115.  
  116. <li><tt>->new('10.10.10.0-255')</tt>
  117.  
  118. <p>This notation is a shorthand for the <em>range notation</em>
  119. discussed above. It provides for the specification of an address range
  120. where both of its ends share the first octets. This notation is only
  121. supported when the specified range of hosts defined a proper CIDR
  122. subnet.
  123.  
  124. <li><tt>->new(1024)</tt>
  125.  
  126. <p>Whenever the address is specified as a numeric value greater than
  127. 255, it is assumed to contain an IP address encoded as an unsigned int.
  128.  
  129.  
  130. <li><tt>->new()</tt> with two arguments
  131.  
  132. <p>Whenever two arguments are specified to <tt>->new()</tt>, the first
  133. is always going to be interpreted as the IP address and the second
  134. will always be the netmask, in any of the formats discussed so far.
  135.  
  136. <p>Netmasks can be specified in dotted-quad notation, as the number of
  137. one-bits or as the equivalent unsigned int. Also, special keywords
  138. such as <tt>broadcast</tt>, <tt>default</tt> or <tt>host</tt> can be
  139. used as netmasks.
  140.  
  141. </ul>
  142.  
  143. <p>The semantics and notations depicted above, are supposed to comply
  144. strictly with the DWIM approach which is so popular with Perl. The
  145. general idea is that you should be able to stick almost anything
  146. resembling an IP address or a subnet specification into the
  147. <tt>->new()</tt> method to get an equivalent object. However, if you
  148. can find another notation that is not included in the above list,
  149. please by all means let me know.
  150.  
  151. <hr>
  152.  
  153. <a name="overloading"><h2>Simple operations with subnets</h2></a>
  154.  
  155. <P>There is a number of operations that have been simplified along the
  156. different versions of the module. The current version, as of this
  157. writing, provides support for the following operations:
  158.  
  159. <ul>
  160. <li>Scalarization
  161.  
  162. <p>A <a
  163. href="http://search.cpan.org/search?mode=module&query=NetAddr%3A%3AIP">NetAddr::IP</a>
  164. object will become its CIDR representation whenever a scalar
  165. representation for it is required. For instance, you can very well do
  166. something like <tt>print "My object contains $ip\n";</tt>.
  167.  
  168. <li>Numerical comparison
  169.  
  170. <p>Two objects can be compared using any of the numerical comparison
  171. operators. Only the address part of the subnet is compared. The
  172. netmask is ignored in the comparison.
  173.  
  174. <li>Increments and decrements
  175.  
  176. <p>Adding or substracting a scalar from an object will change the
  177. address in the subnet, but always keeping it within the subnet. This
  178. is very useful to write loops, like the following:
  179.  
  180. <PRE>
  181. use NetAddr::IP;
  182. my $ip = new NetAddr::IP('10.0.0.0/30');
  183. while ($ip < $ip->broadcast) {
  184. print "ip = $ip\n";
  185. $ip ++;
  186. }
  187. </PRE>
  188.  
  189. <p>which will produce the following output:
  190.  
  191. <PRE>
  192. ip = 10.0.0.0/30
  193. ip = 10.0.0.1/30
  194. ip = 10.0.0.2/30
  195. </PRE>
  196.  
  197. <li>List expansion
  198.  
  199. <p>When required, a <a
  200. href="http://search.cpan.org/search?mode=module&query=NetAddr%3A%3AIP">NetAddr::IP</a>
  201. will expand automatically to a list containing all the addresses
  202. within a subnet, conveniently leaving the subnet and the broadcast
  203. addresses out. The following code shows this:
  204.  
  205. <PRE>
  206. use NetAddr::IP;
  207. my $ip = new NetAddr::IP('10.0.0.0/30');
  208. print join(' ', @$ip), "\n";
  209. </PRE>
  210.  
  211. <p>And the output would be
  212.  
  213. <PRE>
  214. 10.0.0.1/32 10.0.0.2/32
  215. </PRE>
  216.  
  217. </ul>
  218.  
  219. <hr>
  220.  
  221. <a name="common"><h2>Common (and not so common) tasks</h2></a>
  222.  
  223. <p>Below I will try to provide an example for each major feature of <a
  224. href="http://search.cpan.org/search?mode=module&query=NetAddr%3A%3AIP">NetAddr::IP</a>,
  225. along with a description of what is being done, where appropiate.
  226.  
  227. <a name="compact"><h3>Optimising the address space</h3></a>
  228.  
  229. <p>This is one of the reason for writing <a
  230. href="http://search.cpan.org/search?mode=module&query=NetAddr%3A%3AIP">NetAddr::IP</a>
  231. in the first place. Let's say you have a few chunks of IP space and
  232. you want to find the <em>optimum</em> CIDR representation for
  233. them. By optimum, I mean the least amount of CIDR subnets that exactly
  234. represent the given IP address space. The code below is an example of
  235. this:
  236.  
  237. <PRE>
  238. use NetAddr::IP;
  239.  
  240. push @addresses, NetAddr::IP->new($_) for &lt;DATA>;
  241. print join(", ", NetAddr::IP::compact(@addresses)), "\n";
  242. __DATA__
  243. 10.0.0.0/18
  244. 10.0.64.0/18
  245. 10.0.192.0/18
  246. 10.0.160.0/19
  247. </PRE>
  248.  
  249. <p>Which will, of course, output <tt>10.0.0.0/17, 10.0.160.0/19,
  250. 10.0.192.0/18</tt>. Let's see how this is done...
  251.  
  252. <p>First, the line starting with <tt>push ...</tt> creates a list of
  253. objects representing all the subnets read in via the
  254. <tt>&lt;DATA&gt;</tt> filehandle. There should be no surprises here.
  255.  
  256. <p>Then, we call <tt>NetAddr::IP::compact</tt> with the list of
  257. subnets build earlier. This function accepts a list of subnets as its
  258. input (actually, an array of objects). It processes them internally
  259. and outputs another array of objects, as summarized as possible.
  260.  
  261. <p>Using <tt>compact()</tt> as in the example is fine when you're
  262. dealing with a few subnets or are writing a throw-away one-liner. If
  263. you think your script will be handling more than a few tens of
  264. subnets, you might find <tt>compactref()</tt> useful. It works exactly
  265. as shown before, but takes (and returns) references to arrays. I've
  266. seen 10x speed improvements when working with huge lists of subnets.
  267.  
  268. <p>Something that gets asked quite frequently is <em>"why not
  269. <tt>@EXPORT</tt> or at least, <tt>@EXPORT_OK</tt> methods such as
  270. <tt>compact()</tt>?"</em>. The answer is that I believe
  271. <tt>compact()</tt> to be a very generic name, for an operation that
  272. is not always used. I think fully qualifying it, adds to the mnemonics
  273. of what's being done while not polluting the namespace innecesarilly.
  274.  
  275. <hr>
  276.  
  277. <a name="split"><h3>Assigning address space</h3></a>
  278.  
  279. <p>This problem can be tought as the complement to the prior
  280. one. Let's say a couple of network segments need to be connected to
  281. your network. You can carve slices out of your address space easily,
  282. such as in the following code:
  283.  
  284. <PRE>
  285. use NetAddr::IP;
  286.  
  287. print "My address space contains the following /24s:\n",
  288. join("\n", NetAddr::IP->new('10.0.0.0/22')->split(24)), "\n";
  289. </PRE>
  290.  
  291. <p>Which will divide your precious address space (the one specified in
  292. the <tt>NetAddr::IP->new()</tt>) in subnets with a netmask of 24
  293. bytes. This magic is accomplished by the <tt>->split()</tt> method,
  294. which takes the number of bits in the mask as its only parameter. It
  295. returns a list of subnets contained in the original object.
  296.  
  297. <p>Again, in situations where the split might return a large number of
  298. subnets, you might prefer the use of <tt>->splitref()</tt>, which
  299. returns a reference to an array instead.
  300.  
  301. <p>Returning to our example, you might assign a /24 to each new
  302. subnet. Ok, perhaps assigning a /24 is not that good an example, as
  303. this falls on an octet boundary but trust me, when you have to split a
  304. /16 in /20s, to be allocated in chunks of /22s in a network spanning
  305. the whole country, it's nice to know your subnetting is well done.
  306.  
  307. <hr>
  308.  
  309. <a name="wildcard"><h3>Cisco's wildcard notation (and other dialects)</h3></a>
  310.  
  311. <p>Those of you who have had to write an ACL in a Cisco router, know
  312. about the joys of this peculiar format in which the netmask works the
  313. opposite of what custom says.
  314.  
  315. <p>An easy way to convert between traditional notation and Cisco's
  316. wildcard notation, is to use the eloquently named
  317. <tt>->wildcard()</tt> method, as this example shows:
  318.  
  319. <PRE>
  320. use NetAddr::IP;
  321.  
  322. print join(' ', NetAddr::IP->new('10.0.0.0/25')->wildcard());
  323. </PRE>
  324.  
  325. <p>As you might have guessed, <tt>->wildcard()</tt> returns an array
  326. whose first element is the address and its second element is the
  327. netmask, in wildcard notation. If scalar context is forced using
  328. <tt>scalar</tt>, only the netmask will be returned, as this is most
  329. likely what you want.
  330.  
  331. <p>In case you wonder, the example outputs <tt>10.0.0.0
  332. 0.0.0.127</tt>.
  333.  
  334. <p>Just for the record, below is a number of outputs from different
  335. methods for the above example:
  336.  
  337. <ul>
  338. <li>Range (The <tt>->range()</tt> method)
  339.  
  340. <p>Outputs <tt>10.0.0.0 - 10.0.0.127</tt>. Note that this range goes
  341. from the <em>network address</em> to the <em>broadcast
  342. address</em>.
  343.  
  344. <li>CIDR notation (The <tt>->cidr()</tt> method)
  345.  
  346. <p>As expected, it outputs <tt>10.0.0.0/25</tt>.
  347.  
  348. <li>Prefix notation (The <tt>->prefix()</tt> method)
  349.  
  350. <p>Similar to <tt>->range()</tt>, this method produces
  351. <tt>10.0.0.1-127</tt>. However, note that the first address is
  352. <b>not</b> the network address but the first host address.
  353.  
  354. <li><em>n</em>-Prefix notation (The <tt>->nprefix()</tt> method)
  355.  
  356. <p>Produces <tt>10.0.0.1-126</tt>. Note how the broadcast address is
  357. not within the range.
  358.  
  359. <li>Numeric (The <tt>->numeric()</tt> method)
  360.  
  361. <p>In scalar context, produces and unsigned int that represents the
  362. address in the subnet. In array context, both the address and netmask
  363. are returned. For the example, the array output is <tt>(167772160,
  364. 4294967168)</tt>. This is very useful when serializing the object for
  365. storage. You can pass those two numbers back to <tt>->new()</tt> and
  366. get your object back.
  367.  
  368. <li>Just the IP address (The <tt>->addr()</tt> method)
  369.  
  370. <li>Just the netmask as a dotted quad (The <tt>->mask()</tt> method)
  371.  
  372. <li>The length in bits of the netmask (The <tt>->masklen()</tt> method)
  373.  
  374. </ul>
  375. <hr>
  376.  
  377. <a name="contains"><h3>Matching against your address space</h3></a>
  378.  
  379. <p>Let's say you have a log full of IP addresses and you want to know
  380. which ones belong to your IP space. A simple way to achieve this is
  381. shown below:
  382.  
  383. <PRE>
  384. use NetAddr::IP;
  385.  
  386. my $space = new NetAddr::IP->new('10.128.0.0/17');
  387.  
  388. for my $ip (map { new NetAddr::IP->new($_) } &lt;DATA>)
  389. {
  390. print $ip, "\n"
  391. if $space->contains($ip);
  392. }
  393.  
  394. __DATA__
  395. 172.16.1.1
  396. 172.16.1.5
  397. 172.16.1.11
  398. 172.16.1.10
  399. 172.16.1.9
  400. 172.16.1.3
  401. 172.16.1.2
  402. 172.16.1.7
  403. 172.16.1.4
  404. 172.16.1.1
  405. 10.128.0.1
  406. 10.128.0.12
  407. 10.128.0.13
  408. 10.128.0.41
  409. 10.128.0.17
  410. 10.128.0.19
  411. </PRE>
  412.  
  413. <p>This code will output only the addresses belonging to your address
  414. space, represented by <tt>$space</tt>. The only interesting thing here
  415. is the use of the <tt>->contains()</tt> method. As used in our
  416. example, it returns a true value if <tt>$ip</tt> is completely contained within
  417. the <tt>$space</tt> subnet.
  418.  
  419. <p>Alternatively, the condition could have been written as
  420. <tt>$ip->within($space)</tt>. Remember that TIMTOWTDI.
  421.  
  422. <hr>
  423.  
  424. <a name="iteration"><h3>Walking through the network without leaving
  425. the office</h3></a>
  426.  
  427. <p>Some of the nicest features of <a
  428. href="http://search.cpan.org/search?mode=module&query=NetAddr%3A%3AIP">NetAddr::IP</a>
  429. can be better put to use when you want to perform actions with your
  430. address space. Some of them are discussed below.
  431.  
  432. <p>One of the most efficient ways to walk your address space is
  433. building a <tt>for</tt> loop, as this example shows:
  434.  
  435. <PRE>
  436. use NetAddr::IP;
  437.  
  438. push @space, new NetAddr::IP->new($_) for &lt;DATA>;
  439.  
  440. for my $netblock (NetAddr::IP::compact @space)
  441. {
  442. for (my $ip = $netblock->first;
  443. $ip <= $netblock->last;
  444. $ip++)
  445. {
  446. # Do something with $ip
  447. }
  448. }
  449. __DATA__
  450. 10.0.0.0/16
  451. 172.16.0.0/24
  452. </PRE>
  453.  
  454. <p>The nicest thing about this way of walking your IP space, is that
  455. even if you are lucky enough to have lots of it, you won't eat all
  456. your memory by generating a huge list of objects. In this example,
  457. only one object is created in every iteration of the loop.
  458.  
  459. <p>Everything up to the inner loop should be pretty clear by now, so
  460. we just ignore it. Since a couple of new friends were introduced in
  461. the inner loop of our example, an explanation is in order.
  462.  
  463. <p>This C-like <tt>for</tt> loop uses the <tt>->first()</tt> function to
  464. find the first subnet address. The first subnet address is defined as
  465. that having all of its <em>host bits</em> but the rightmost set to
  466. zero and the rightmost, set to one.
  467.  
  468. <p>We then use the numerical comparison discussed earlier to see if
  469. the value of <tt>$ip</tt> is less than or equal to whatever
  470. <tt>->last()</tt> returns. <tt>->last()</tt> returns an address with
  471. all of its host bits set to one but the rightmost. If this condition
  472. holds, we execute the loop and post-increment <tt>$ip</tt> to get the
  473. next IP address in the subnet.
  474.  
  475. <p>I started the discussion on this topic with the approach that
  476. insures less wasted resources. However, in the purest Perl tradition,
  477. this is not the only way to do it. There's another way, reserved for
  478. the true lazy (or those with memory to burn, but we all know you never
  479. have enough memory, right?).
  480.  
  481. <p>This other way is invoked with the <tt>->hostenum()</tt> or the
  482. <tt>->hostenumref()</tt> methods. They return either an array or a
  483. reference to an array respectively, containing one object for each
  484. <em>host</em> address in the subnet. Note that only valid host
  485. addresses will be returned (as objects) since the network and
  486. broadcast addresses are seldom useful.
  487.  
  488. <p>With no further preamble, I introduce an example that kids
  489. shouldn't attempt at home, or at least in production code. (If you
  490. find this warning superfluous, try adding <tt>64.0.0.0/8</tt> to the
  491. <tt>__DATA__</tt> section and see if your machine chews through it
  492. all).
  493.  
  494. <PRE>
  495. use NetAddr::IP;
  496.  
  497. push @space, new NetAddr::IP->new($_) for &lt;DATA>;
  498.  
  499. for my $ip (map { $_->hostenum } NetAddr::IP::compact @space)
  500. {
  501. # Do something with $ip
  502. }
  503. __DATA__
  504. 10.0.0.0/16
  505. 172.16.0.0/24
  506. </PRE>
  507.  
  508. <p>If you really have enough memory, you'll see that each host address
  509. in your IP space is generated into a huge array. This is much more
  510. costly (read, slow) than the approach presented earlier, but provides
  511. for more compact one-liners or quickies.
  512.  
  513. <hr>
  514.  
  515. <a name="num"><h3>Finding out how big is your network</h3></a>
  516.  
  517. <p>Have you wondered just how many IP addresses can you use in your
  518. current subnet plan? If the answer to this (or to a similar question)
  519. is <em>yes</em>, then read on.
  520.  
  521. <p>There is a method called <tt>->num()</tt> that will tell you
  522. exactly how many addresses can you use in a given subnet. For the
  523. quick observers out there, you can also use something like <tt>scalar
  524. $subnet->hostenum</tt> but this is a really expensive way of doing it.
  525.  
  526. <p>A more conservative (in resources) approach is depicted below:
  527.  
  528. <PRE>
  529. use NetAddr::IP;
  530.  
  531. my $hosts = 0;
  532. push @space, new NetAddr::IP->new($_) for &lt;DATA>;
  533. $hosts += $_->num for @space;
  534. print "You have $hosts\n";
  535. __DATA__
  536. 10.0.0.0/16
  537. 172.16.0.0/24
  538. </PRE>
  539.  
  540. <p>Sometimes, you will be surprised at how many addresses are lost by
  541. subnetting, but we'll leave that discussion to other tutorials.
  542.  
  543. <hr>
  544. </BODY></HTML>