python3 寫法
#!/usr/bin/env python
#-- coding:utf-8 --python
import socket
import fcntl,struct
import timesocket
def getHardware(outip,inip):
sk = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
##1.獲取主機名
hostname = socket.gethostname()
print ('主機名*****',hostname)ide
##獲取ip, OutIp = socket.inet_ntoa(fcntl.ioctl(sk.fileno(), 0x8915, struct.pack('256s', bytes(outip[:15],'utf-8')))[20:24]) InIp = socket.inet_ntoa(fcntl.ioctl(sk.fileno(), 0x8915, struct.pack('256s', bytes(inip[:15],'utf-8')))[20:24]) print ('外網網卡爲*************************',OutIp) print ('內網網卡爲*************************',InIp)
#填寫網卡名稱,我這裏沒有外網ip,用lo測試
getHardware('eth0','eth1')測試
python2 方法
#!/usr/bin/env python
#-- coding:utf-8 --code
import socket
import fcntl,struct
import timeip
def getHardware(outip,inip):
sk = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
##1.獲取主機名
hostname = socket.gethostname()
print '主機名*****',hostnameutf-8
##獲取ip, OutIp = socket.inet_ntoa(fcntl.ioctl(sk.fileno(), 0x8915, struct.pack('256s', outip[:15]))[20:24]) InIp = socket.inet_ntoa(fcntl.ioctl(sk.fileno(), 0x8915, struct.pack('256s', inip[:15]))[20:24]) print '外網網卡爲*************************',OutIp print '內網網卡爲*************************',InIp
#填寫網卡名稱,我這裏沒有外網ip,用lo測試
getHardware('lo','eth0')get