-
Notifications
You must be signed in to change notification settings - Fork 0
/
ipv4-ipv6-subnetting-in-python.html
323 lines (272 loc) · 16 KB
/
ipv4-ipv6-subnetting-in-python.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
<!DOCTYPE html>
<html lang="ru"
>
<head>
<title>IPv4, IPv6 subnetting in Python - Oleg Mykolaichenko</title>
<!-- Using the latest rendering mode for IE -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="canonical" href="https://mykolaichenko.github.io/ipv4-ipv6-subnetting-in-python.html">
<meta name="author" content="Oleg Mykolaichenko" />
<meta name="description" content="Неочевидные манипуляции с IP адресами, используя нативный Python." />
<meta property="og:site_name" content="Oleg Mykolaichenko" />
<meta property="og:type" content="article"/>
<meta property="og:title" content="IPv4, IPv6 subnetting in Python"/>
<meta property="og:url" content="https://mykolaichenko.github.io/ipv4-ipv6-subnetting-in-python.html"/>
<meta property="og:description" content="Неочевидные манипуляции с IP адресами, используя нативный Python."/>
<meta property="article:published_time" content="2016-07-20" />
<meta property="article:section" content="DevOps" />
<meta property="article:author" content="Oleg Mykolaichenko" />
<!-- Bootstrap -->
<link rel="stylesheet" href="https://mykolaichenko.github.io/theme/css/bootstrap.min.css" type="text/css"/>
<link href="https://mykolaichenko.github.io/theme/css/font-awesome.min.css" rel="stylesheet">
<link href="https://mykolaichenko.github.io/theme/css/pygments/native.css" rel="stylesheet">
<link rel="stylesheet" href="https://mykolaichenko.github.io/theme/css/style.css" type="text/css"/>
<link href="https://mykolaichenko.github.io/feeds/all.atom.xml" type="application/atom+xml" rel="alternate"
title="Oleg Mykolaichenko ATOM Feed"/>
<link href="https://mykolaichenko.github.io/feeds/all.rss.xml" type="application/rss+xml" rel="alternate"
title="Oleg Mykolaichenko RSS Feed"/>
</head>
<body>
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="https://mykolaichenko.github.io/" class="navbar-brand">
Oleg Mykolaichenko </a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li><a href="https://mykolaichenko.github.io/pages/kak-my-redis-cluster-gotovili.html">
Как мы Redis Cluster готовили
</a></li>
<li class="active">
<a href="https://mykolaichenko.github.io/category/devops.html">Devops</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="https://mykolaichenko.github.io/archives.html"><i class="fa fa-th-list"></i><span class="icon-label">Archives</span></a></li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
</div> <!-- /.navbar -->
<!-- Banner -->
<!-- End Banner -->
<div class="container">
<div class="row">
<div class="col-sm-9">
<section id="content">
<article>
<header class="page-header">
<h1>
<a href="https://mykolaichenko.github.io/ipv4-ipv6-subnetting-in-python.html"
rel="bookmark"
title="Permalink to IPv4, IPv6 subnetting in Python">
IPv4, IPv6 subnetting in Python
</a>
</h1>
</header>
<div class="entry-content">
<div class="panel">
<div class="panel-body">
<footer class="post-info">
<span class="label label-default">Date</span>
<span class="published">
<i class="fa fa-calendar"></i><time datetime="2016-07-20T18:00:00+03:00"> Wed 20 July 2016</time>
</span>
</footer><!-- /.post-info --> </div>
</div>
<p><img alt="манипуляции с IP адресами" src="/images/ipv6.png" title="манипуляции с IP адресами" /></p>
<h1>Python</h1>
<p>Почему Python? Напишу об этом отдельную заметку. В двух словах - он "скриптовый", он "динамически типизирован", он нативен в любой линухе. Этого достаточно? </p>
<h1>IPython</h1>
<p>Нет, Стив Джобс не имеет никакого отношения к ipython. IPython - это очень крутая натюненная интерактивная консолька для пайтона, которая умеет автокомплитить, смотреть внутрь метода, нативные линуксовые команды (ls, pwd, grep), та и вообще только для крутых пацанов. Работать будем в ней консольно, она отлично для этого подходит. Еще есть браузерный вариант, но он больше для демонстраций графичков для научных сотрудников и всего такого. </p>
<p>Давайте решим первую задачку. </p>
<h2>List all IP from subnet</h2>
<p>В данном случае все очевидно, тут можно отлично закостылить, но мы не будем. Вместо этого запустим <code>ipython</code> и импортируем <code>netaddr</code>:</p>
<p><code>from netaddr import *</code></p>
<p>Крутяк. Теперь можем юзать, все что там внутри. </p>
<p>У нас задача - сделать список всех адресов в нужной подсети. Этим грешат абсолютно все онлайн штуки, которые показывают range - от и до. Нам это не интересно) </p>
<p><code>ip = IPNetwork('172.16.35.0/22')</code></p>
<p>В данном случае - наша маска это <em>/22</em>. Совсем не очевидно как считать это на листочке, тем более что это находится между октетов. Маска в десятичной системе будет выглядеть как <em>255.255.252.000</em> и вмещает она в себя аж целых 1024 адреса. Не плохо.</p>
<p>Предлагаю узнать побольше информации о этой сети, которую netaddr может нам любезно предоставить.</p>
<div class="highlight"><pre><span></span> In [12]: ip.network
Out[12]: IPAddress('172.16.32.0') # адрес нашей сети
</pre></div>
<div class="highlight"><pre><span></span> In [12]: ip.broadcast
Out[12]: IPAddress('172.16.35.255') # адрес широковещательного адреса нашей сети
</pre></div>
<div class="highlight"><pre><span></span> In [14]: ip.hostmask
Out[14]: IPAddress('0.0.3.255') # инвертированная маска сети
</pre></div>
<div class="highlight"><pre><span></span> In [15]: ip.size
Out[15]: 1024 # количество узлов в сети
</pre></div>
<p>У всех этих методов есть подметод bits, например:</p>
<div class="highlight"><pre><span></span> In [16]: ip.broadcast.bits()
Out[16]: '10101100.00010000.00100011.11111111' # мажорство
</pre></div>
<p>Вернемся к задачке, вот ее решение: </p>
<div class="highlight"><pre><span></span>In [17]: for ip in IPNetwork('172.16.35.0/22'):
....: print '%s' % ip
</pre></div>
<p>Так выглядит вывод команды: </p>
<div class="highlight"><pre><span></span> 172.16.32.0
172.16.32.1
172.16.32.2
172.16.32.3
172.16.32.4
172.16.32.5
172.16.32.6
...
...
...
172.16.35.251
172.16.35.252
172.16.35.253
172.16.35.254
172.16.35.255
</pre></div>
<p>Кто не верит, что netaddr посчитал правильно - без проблем, садитесь за калькулятор, и пересчитывайте. Удачи, бро!</p>
<p>Кстати, это все абсолютно так же работает и с IPv6 (и это афигительно просто):</p>
<div class="highlight"><pre><span></span>In [18]: for ip in IPNetwork('2001:19f0:5001:1d::1/126'):
....: print '%s' % ip
....:
2001:19f0:5001:1d::
2001:19f0:5001:1d::1
2001:19f0:5001:1d::2
2001:19f0:5001:1d::3
</pre></div>
<p>На самом деле хостер мне выдал /64, но их я генерировать не буду, потому что их 18446744073709552000 - а это, между прочим, многовато.</p>
<p>Вообще, /64 выдавать должны всем: </p>
<blockquote>
<p>/64: the basic size of a single subnet: LAN, WAN, block of addresses for web virtual hosts, etc... "Normal" subnets are > never expected to be any smaller (longer prefix) than /64. No subnets are ever expected to be larger (shorter prefix) > than /64 since a /64's worth of host addresses is way more than we can imagine needing.</p>
</blockquote>
<p>Невзначай скажу, что эту информацию можно успешно использовать для хороших и не очень хороших вещей)</p>
<p>Например, вот так: </p>
<div class="highlight"><pre><span></span> In [19]: for ip in IPNetwork('2001:19f0:5001:1d::1/124'):
....: print 'ip -6 addr add %s/128 dev eth0' % ip
....:
ip -6 addr add 2001:19f0:5001:1d::/128 dev eth0
ip -6 addr add 2001:19f0:5001:1d::1/128 dev eth0
ip -6 addr add 2001:19f0:5001:1d::2/128 dev eth0
ip -6 addr add 2001:19f0:5001:1d::3/128 dev eth0
ip -6 addr add 2001:19f0:5001:1d::4/128 dev eth0
ip -6 addr add 2001:19f0:5001:1d::5/128 dev eth0
ip -6 addr add 2001:19f0:5001:1d::6/128 dev eth0
ip -6 addr add 2001:19f0:5001:1d::7/128 dev eth0
ip -6 addr add 2001:19f0:5001:1d::8/128 dev eth0
ip -6 addr add 2001:19f0:5001:1d::9/128 dev eth0
ip -6 addr add 2001:19f0:5001:1d::a/128 dev eth0
ip -6 addr add 2001:19f0:5001:1d::b/128 dev eth0
ip -6 addr add 2001:19f0:5001:1d::c/128 dev eth0
ip -6 addr add 2001:19f0:5001:1d::d/128 dev eth0
ip -6 addr add 2001:19f0:5001:1d::e/128 dev eth0
ip -6 addr add 2001:19f0:5001:1d::f/128 dev eth0
</pre></div>
<p>Это можно копипасить прямо в консоль. И, кстати, любой апп, который работает с сетью, умеет биндиться на интерфейс, или IP адрес. К примеру: </p>
<p><code>curl --interface '2001:19f0:5001:1d::f/128' http://www.google.com/search?q=mykolaichenko.github.io</code></p>
<h1>Самое важное</h1>
<p>В умелых руках и палка топор. </p>
</div>
<!-- /.entry-content -->
<hr/>
<section class="comments" id="comments">
<h2>Comments</h2>
<div id="disqus_thread"></div>
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = 'mykolaichenkogithubio'; // required: replace example with your forum shortname
var disqus_identifier = 'ipv4-ipv6-subnetting-in-python';
var disqus_url = 'https://mykolaichenko.github.io/ipv4-ipv6-subnetting-in-python.html';
var disqus_config = function () {
this.language = "ru";
};
/* * * DON'T EDIT BELOW THIS LINE * * */
(function () {
var dsq = document.createElement('script');
dsq.type = 'text/javascript';
dsq.async = true;
dsq.src = 'https://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by
Disqus.</a></noscript>
<a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
</section>
</article>
</section>
</div>
<div class="col-sm-3" id="sidebar">
<aside>
<section class="well well-sm">
<ul class="list-group list-group-flush">
<li class="list-group-item"><h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Social</span></h4>
<ul class="list-group" id="social">
<li class="list-group-item"><a href="https://ua.linkedin.com/in/oleg-mykolaichenko-763ab699"><i class="fa fa-linkedin-square fa-lg"></i> linkedin</a></li>
<li class="list-group-item"><a href="https://github.com/Mykolaichenko"><i class="fa fa-github-square fa-lg"></i> github</a></li>
</ul>
</li>
<li class="list-group-item"><a href="https://mykolaichenko.github.io/"><h4><i class="fa fa-tags fa-lg"></i><span class="icon-label">Tags</span></h4></a>
<ul class="list-group " id="tags">
</ul>
</li>
</ul>
</section>
</aside>
</div>
</div>
</div>
<footer>
<div class="container">
<hr>
<div class="row">
<div class="col-xs-10">© 2017 Oleg Mykolaichenko </div>
<div class="col-xs-2"><p class="pull-right"><i class="fa fa-arrow-up"></i> <a href="#">Back to top</a></p></div>
</div>
</div>
</footer>
<script src="https://mykolaichenko.github.io/theme/js/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="https://mykolaichenko.github.io/theme/js/bootstrap.min.js"></script>
<!-- Enable responsive features in IE8 with Respond.js (https://github.com/scottjehl/Respond) -->
<script src="https://mykolaichenko.github.io/theme/js/respond.min.js"></script>
<!-- Disqus -->
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = 'mykolaichenkogithubio'; // required: replace example with your forum shortname
/* * * DON'T EDIT BELOW THIS LINE * * */
(function () {
var s = document.createElement('script');
s.async = true;
s.type = 'text/javascript';
s.src = '//' + disqus_shortname + '.disqus.com/count.js';
(document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
}());
</script>
<!-- End Disqus Code -->
<!-- Google Analytics -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-77921747-1']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
<!-- End Google Analytics Code -->
</body>
</html>