|
|
 |
|
Title: get dhcp IP
Submitter: Vaibhav Bhatia
(other recipes)
Last Updated: 2006/10/20
Version no: 1.0
Category:
System
|
|
|
Description:
a small script which i use to get the DHCP ip of my laptop
Source: Text Source
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
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
|
|
|
|
|
 |
|