Home > Backend Development > Python Tutorial > python在windows和linux下获得本机本地ip地址方法小结

python在windows和linux下获得本机本地ip地址方法小结

WBOY
Release: 2016-06-06 11:22:17
Original
1330 people have browsed it

本文实例总结了python在windows和linux下获得本机本地ip地址方法。分享给大家供大家参考。具体分析如下:

python的socket包含了丰富的函数和方法可以获得本机的ip地址信息,socket对象的gethostbyname方法可以根据主机名获得本机ip地址,socket对象的gethostbyname_ex方法可以获得本机所有ip地址列表

第一种方法:通过socket.gethostbyname方法获得

import socket
localIP = socket.gethostbyname(socket.gethostname())#得到本地ip
print "local ip:%s "%localIP
Copy after login

返回结果如下:

'172.16.34.102'

第二种方法:通过socket.gethostbyname_ex方法获得本机主机名和ip地址列表

import socket
ipList = socket.gethostbyname_ex(socket.gethostname())
print(ipList)
Copy after login

返回结果如下:

('china-43226208c', [], ['192.168.5.196'])

以上两种方法在linux下也可以使用,linux下还以通过下面的代码获取本机ip地址

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])
Copy after login

希望本文所述对大家的Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template