您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

python 获取本机ip地址的两个方法

2024/2/20 4:22:55发布40次查看
第一种:
代码如下:
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])
#get_ip_address('lo')环回地址
#get_ip_address('eth0')主机ip地址
第二种:
代码如下:
def get_local_ip(ifname):
import socket, fcntl, struct
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(eth0)
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product