python 获取本地ip地址 计算机名

import socket

ip_address = socket.gethostbyname_ex(socket.getfqdn(socket.gethostname()))
print(ip_address)

print("socket.gethostname()", socket.gethostname())

print("socket.getfqdn(socket.gethostname())", socket.getfqdn(socket.gethostname()))


# 在linux下可用 window无效
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].encode("utf-8"))
    )[20:24])

print(get_ip_address("lo"))

print(get_ip_address("ens33"))

以上是python3代码

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')
'127.0.0.1'
  
>>> get_ip_address('eth0')
'38.113.228.130'
发布了157 篇原创文章 · 获赞 85 · 访问量 34万+

猜你喜欢

转载自blog.csdn.net/Areigninhell/article/details/101293740
今日推荐