Python获取IP的三种方法

#!/usr/bin/env python
# coding: utf8

import socket, fcntl
import struct
import re, urllib2

# 获取本机IP地址
def get_ip(eth_name='eth0'):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s_str = fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', eth_name[:15]))
    ip_str = socket.inet_ntoa(s_str[20:24])
    print("ip: " + ip_str)      # ip: 100.10.166.23
    
# 获取本地ip列表    
def get_ip_2():
    hostname = socket.gethostname()
    local_ip = socket.gethostbyname(hostname)
    print("hostname: " + str(hostname) + "; ip: " + str(local_ip))      # hostname: ubuntu; ip: 127.0.1.1

    ip_list = socket.gethostbyname_ex(hostname)
    for ip in ip_list:
        print("hostname_ex: " + str(hostname) + "; ip: " + str(ip))     # hostname_ex: ubuntu; ip: ubuntu; hostname_ex: ubuntu; ip: []; hostname_ex: ubuntu; ip: ['127.0.1.1']

# 获取公网ip地址
def get_ip_3(url='https://blog.mimvp.com'):
    opener = urllib2.urlopen(url=url, timeout=30)
    if url == opener.geturl():
        ipStr = opener.read()
#     print("ipStr: " + str(ipStr))
    re_result = re.search('\d+\.\d+\.\d+\.\d+', ipStr)
    ip = re_result.group(0) if re_result  else 'None'
    print("ip: " + str(ip))


if __name__ == '__main__':
    get_ip("eth1")
    get_ip_2()
    get_ip_3()
    
    print("end.")

 

推荐用第一种