ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: get dhcp IP
Submitter: Vaibhav Bhatia (other recipes)
Last Updated: 2006/10/20
Version no: 1.0
Category: System

 

Not Rated yet


Description:

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

Source: Text Source

#!/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

Discussion:

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



Add comment

Number of comments: 1

use the socket module, Moe Goldberg, 2007/07/26
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())

Add comment



Highest rated recipes:

1. A simple XML-RPC server

2. Web service accessible ...

3. IPy Notify

4. Treat the Win32 Registry ...

5. a friendly mkdir()

6. Wrapping template engine ...

7. Assignment in expression

8. Changing return value ...

9. Implementation of sets ...

10. bag collection class




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.