商务合作加Q:411239339

python–获取本地网卡通信IP地址

浏览:491次阅读
一条评论

共计 790 个字符,预计需要花费 2 分钟才能阅读完成。

问:何为本地网卡通信 IP 地址?

答:就是你当前使用的是哪个 IP 地址与互联网进行通讯。

通过 DNS 服务商获取本地网卡通信 IP 地址,新建文件名为 get_local_ip.py,内容如下:

#!/usr/bin/env python
import socket
def Get_local_ip():
    """
    Returns the actual ip of the local machine.
    This code figures out what source address would be used if some traffic
    were to be sent out to some well known address on the Internet. In this
    case, a Google DNS server is used, but the specific address does not
    matter much.  No traffic is actually sent.
    """
    try:
        csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        csock.connect(('114.114.114.114', 80))
        (addr, port) = csock.getsockname()
        csock.close()
        return addr
    except socket.error:
        return "127.0.0.1"
if __name__ == "__main__":
    IPADDR = Get_local_ip()
    print IPADDR

正文完
扫码赞助
post-qrcode
 0
果子
版权声明:本站原创文章,由 果子 于2016-09-18发表,共计790字。
转载说明:除特殊说明外本站文章皆由果较瘦原创发布,转载请注明出处。
评论(一条评论)
2016-09-18 11:29:48 回复

Python,啊哈。。

 Windows  Chrome  中国广西桂林市电信