python 获取路由器中设备ip地址_Python中如何获取当前机器的IP地址

本文最后更新于2018年5月5日,已超过 1 年没有更新,如果文章内容失效,还请反馈给我,谢谢!

=Start=

缘由:

整理、记录

正文:

参考解答:

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('eth0') # '192.168.0.110'

&

import socket

socket.gethostbyname(socket.gethostname())

&

import socket

def get_ip():

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

try:

# doesn't even have to be reachable

s.connect(('10.255.255.255', 1))

IP = s.getsockname()[0]

except:

IP = '127.0.0.1'

finally:

s.close()

return IP

参考链接:

=END=

你可能感兴趣的:(python,获取路由器中设备ip地址)