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

2016/09/1811:23:14 1

问:何为本地网卡通信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

  • 微信扫码赞助
  • weinxin
  • 支付宝赞助
  • weinxin

发表评论

您必须才能发表评论!

目前评论:1   其中:访客  0   博主  0

    • 聆听

      Python,啊哈。。