Python has several methods to obtain the host's IP address, Python socket contains rich functions and methods to obtain the IP address information, socket object GetHostByName method can be based on the host name to obtain the local IP address, The GETHOSTBYNAME_EX method of the socket object can obtain a list of all IP addresses on this machine
One of my common uses is to use Socket.socket (). Inet_ntoa (), which is very convenient, but there is a limit to this method is to pass the network card name (such as eth0) as a parameter. So add a condition to judge, if found above method obtains IP throws an exception, that uses to adjust the shell command (ifconfig) and pipeline, the IP that wants to filter out.
[Python]
Import socket
Import Fcntl
Import struct
"""
Get host IP Address
PARAMETER ifname: The IP address of the host obtained via ' Lo ' for loopback address, via ' eth0 '
"""
def get_ip_address (ifname= ' eth0 '):
Try
s = socket.socket (socket.af_inet, socket. SOCK_DGRAM)
Return Socket.inet_ntoa (Fcntl.ioctl (
S.fileno (),
0x8915, # SIOCGIFADDR
Struct.pack (' 256s ', ifname[:15])
) [20:24])
Except
IPS = Os.popen ("Lang=c ifconfig | grep "inet addr" | Grep-v "127.0.0.1" | Awk-f ":" ' {print $} ' | awk ' {print '} ' "). ReadLines ()
If Len (IPs) > 0:
return Ips[0]
Return ""
Python obtains information such as domain IP and local IP host name
#coding: GBK
Import socket
Socket.gethostbyname (' www.cr173.com ') #获取域名对应的IP
Socket.gethostbyname (Socket.gethostname ()) #获取主机名
SOCKET.GETHOSTBYNAME_EX (Socket.gethostname ()) #根据主机名判断出IP
How to obtain an IP address under Windows
Method One
The use of dial-up Internet, there are generally a local IP and an extranet IP, using Python can easily get these two IP using gethostbyname and GETHOSTBYNAME_EX two functions can be implemented
Import socket
Localip = Socket.gethostbyname (Socket.gethostname ()) #得到本地ip
Print "Local ip:%s"%localip
IPList = SOCKET.GETHOSTBYNAME_EX (Socket.gethostname ())
For I in IPList:
If I!= localip:
print "External ip:%s"%i
Method Two
Import socket
MyName = Socket.getfqdn (Socket.gethostname ())
Myaddr = Socket.gethostbyname (my
Name