1
2
3
4 """
5 Networking tools.
6 """
7
8 import os, socket, struct, sys
9 from time import *
10 from contextlib import contextmanager
13
15 """
16 Simply parses the output of C{ifconfig} or C{ipconfig} to estimate
17 this machine's IP address. This is not at all reliable, but tends
18 to work "well enough" for my own purposes.
19
20 From U{http://mail.python.org/pipermail/python-list/2005-December/357300.html}.
21
22 @copyright: Frank Millman
23
24 Note that U{http://libdnet.sf.net/} provides this functionality and much
25 more.
26 """
27 mac = None
28 if sys.platform == 'win32':
29 for line in os.popen("ipconfig /all"):
30 if line.lstrip().startswith('Physical Address'):
31 mac = line.split(':')[1].strip().replace('-',':')
32 break
33 else:
34 for line in os.popen("/sbin/ifconfig"):
35 if line.find('Ether') > -1:
36 mac = line.split()[4]
37 break
38 if mac is None:
39 raise no_mac_addr_exception
40 return mac
41
43 """
44 Repeatedly invoke L{func} until it succeeds (returns non-None), with
45 exponentially growing backoff delay between each try.
46
47 @param initial_backoff: The initial backoff.
48 @type initial_backoff: float
49
50 @param multiplier: The amount by which the backoff is multiplied on each
51 failure.
52 @type multiplier: float
53
54 @param func: The zero-argument function to be invoked that returns True on
55 success and False on failure.
56 @type func: function
57
58 @return: The result of the function
59 """
60 backoff = initial_backoff
61 while True:
62 res = func()
63 if res is not None: return res
64 print 'backing off for', backoff
65 sleep(backoff)
66 backoff = multiplier * backoff
67
68 @contextmanager
69 -def logout(x):
70 "A context manager for calling the C{logout()} method of an object."
71 try: yield x
72 finally: x.logout()
73
75 "Convert an IPv4 address from an int in network byte order to a string."
76 return socket.inet_ntoa(struct.pack('>L', x))
77
79 "Convert an IPv4 address from an int in host byte order to a string."
80 return socket.inet_ntoa(struct.pack('L', x))
81