python获取本地ip的方法

Python022

python获取本地ip的方法,第1张

方法一可能有的获取不到ip(比如没有正确设置up名称

方法

import socket

#获取计算机名称

hostname=socket.gethostname()

#获取本机IP

ip=socket.gethostbyname(hostname)

print(ip)

方法二

import socket

def get_host_ip():

    """

    查询本机ip地址

    :return:

    """

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

        s.connect(('8.8.8.8',80))

        ip=s.getsockname()[0]

    finally:

        s.close()

    return ip

if __name__ == '__main__':

    print(get_host_ip())

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', 0))

        IP = s.getsockname()[0]

    except:

        IP = '127.0.0.1'

    finally:

        s.close()

    return IP

linux、windows均测试通过