1、https://www.jb51.net/article/62559.htm
第一种方法:通过socket.gethostbyname方法获得
1
2
3
|
import socket localIP = socket.gethostbyname(socket.gethostname()) #得到本地ip print "local ip:%s " % localIP |
返回结果如下:
'172.16.34.102'
第二种方法:通过socket.gethostbyname_ex方法获得本机主机名和ip地址列表
1
2
3
|
import socket ipList = socket.gethostbyname_ex(socket.gethostname()) print (ipList) |
返回结果如下:
('china-43226208c', [], ['192.168.5.196'])
以上两种方法在linux下也可以使用,linux下还以通过下面的代码获取本机ip地址
1
2
3
4
5
6
7
8
9
10
|
import socket import fcntl import struct def get_ip_address(ifname): 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 ]) |