6-11. Conversion.
Create a program that will convert from an integer to an Internet Protocol (IP) address in the four-octet format of WWW.XXX.YYY.ZZZ.
Update your program to be able to do the vice versa of the above.
1
#!/usr/bin/env python
2
#-*- coding:utf-8 -*-
3
#$Id: p0611.py 139 2010-05-21 09:45:30Z xylz $
4
5
'''
6
This is a 'python' study plan for xylz.
7
Copyright (C)2010 xylz (www.imxylz.info)
8
'''
9
10
def convertIp2Str(ip):
11
return '.'.join( ( str((ip>>i) &0xFF) for i in (24,16,8,0)) )
12
13
def convertStr2Ip(s):
14
r=0
15
for i,v in enumerate(s.split('.')):
16
r |= ( int(v) << (24-i*8))
17
return r
18
19
20
if __name__ == '__main__':
21
'''
22
Convert ip from Integer number to string and do it versa.
23
'''
24
sip = '192.168.1.1'
25
ip = convertStr2Ip(sip)
26
sip2 = convertIp2Str(ip)
27
print sip,ip,sip2
很顯然這里沒有對IP有效性進行校驗,這里假設IP地址都是有效的。
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

在11行,首先構造一個4個數的迭代器,對于迭代器里面的每一項,將ip整數往右移一個字節,然后與0xFF,這樣就得到了每一項的值。然后同string.join(s)將一個迭代器或者列表連接起來,構成一個"xxx.xxx.xxx.xxx"格式的字符串。