在linux下获得ip地址可以使用ifconfig指令
[root@zhu ~]# ifconfig eth0 |grep 'inet addr' | awk -F '[: ]+' '{print $4}' 192.168.56.101
[root@zhu ~]# ifconfig eth0 |grep 'inet addr' | cut -d: -f2 | cut -d' ' -f1 192.168.56.101
[root@zhu ~]# ifconfig eth0 |grep 'inet addr' | cut -d: -f2 | awk '{print $1}' 192.168.56.101
在python中获得ip地址的方法如下
[root@zhu ~]# python zhu.py 192.168.56.101 10.0.3.15 [root@zhu ~]# cat zhu.py #!/usr/bin/python import socket,fcntl,struct def get_local_ip(ifname = 'eth0'): s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) inet = fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15])) ret = socket.inet_ntoa(inet[20:24]) return ret print get_local_ip() print get_local_ip('eth1')
[root@zhu ~]# python zhu.py 192.168.56.101 [root@zhu ~]# cat zhu.py #!/usr/bin/python import subprocess import re regu = re.compile('\\d+\.\\d+\.\\d+\.\\d+') p = subprocess.Popen('ifconfig eth0',shell=True,stdout=subprocess.PIPE) print regu.findall(p.stdout.read())[0]