Welcome, guest | Sign In | My Account | Store | Cart

a small script which i use to get the DHCP ip of my laptop

Python, 42 lines
 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
#!/usr/bin/env python2.4
from subprocess import *
import os

class myDHCPip:
    ip = None

    def __init__(self, interface='wlan0'):
        if os.name == 'posix':
            self.cmd = "/sbin/ip -f inet addr"
            self.searchstr = 'global ' + interface
        elif os.name == 'nt':
            self.cmd = "c:\WINDOWS\system32\ipconfig.exe"
            self.searchstr = 'IP Address'
        self.search4ip()

    def getdata(self):
        """get data about dhcp ip"""

        p = Popen(self.cmd.split() ,stdout=PIPE)
        return p.communicate()[0]

    def search4ip(self):
        """parse data to get ip"""

        ipstr = [line.strip()
                for line in self.data.split('\n')
                if line.find(self.searchstr) >0 ][0]
        if os.name == 'nt':
            self.ip = ipstr.split(':')[1]
        elif os.name == 'posix':
            self.ip = ipstr.split()[1].split('/')[0]

    def getip(self):
        return self.ip

    ip = property(fget = getip)
    data = property(fget = getdata)

if __name__ == '__main__':
    print myDHCPip('eth1').ip
    #print myDHCPip('eth1').data

This recipe is a simple script which i use to get DHCP ip of my machine. Useful for those scripts which require your dhcp ip address as an input.

Note: input of interface (eth1 here) is required only for posix

1 comment

Moe Goldberg 16 years, 9 months ago  # | flag

use the socket module. you can acheive the same thing in one line of code, using the socket module (okay, 2 if you include the import statment):

import socket
print socket.gethostbyname(socket.gethostname())