Python实现获取IP代码

代码如下:

# -*- coding: utf-8 -*-
#!/usr/bin/env python 
# @Time    : 2018/5/30 11:05
# @Desc    : 获取ip
# @File    : iptools.py
# @Software: PyCharm

import socket
def get_host_ip():
    """
    查询本机ip地址
    return: ip
    """
    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())

 

 

posted @ 2018-08-05 16:36  代码帮  阅读(498)  评论(0编辑  收藏  举报