how to get the client's IP address

本文介绍了两种获取当前设备IP地址的方法:一是通过shell命令结合Python处理;二是利用Python的re模块解析ifconfig命令的输出。第一种方法适用于多种平台,第二种方法在某些环境下可能无法返回预期结果。

有时候总会有这种需求,今天我先起个头,汇总一下可以获取当前设备IP address的办法:

1. shell 正则 + python

    DATAIP = "ifconfig -a|awk \'/(cast)/ {print $2}\'|cut -f1-2 -d."
    data= subprocess.Popen(DATAIP,stdout=subprocess.PIPE,shell=True)
    tmp = data.stdout.read()
    _Real_IP = tmp.strip()

 2. python 本身的re 模块,但是这个我在生产中遇到过一个问题,在chrom OS 的command 下面 return的列表是空的,但是在 ubuntu的note book 上面run 是可以正常return的

import subprocess
import re

def _GetLine():
  ipstr = '([0-9]{1,3}\.){1}[0-9]{1,3}'
  ipconfig_process = subprocess.Popen("ifconfig", stdout=subprocess.PIPE)
  output = ipconfig_process.stdout.read()
    ip_pattern = re.compile('(inet addr:%s)' % ipstr)
  pattern = re.compile(ipstr)
  iplist = []
  for ipaddr in re.finditer(ip_pattern, str(output)):
      print type(ipaddr)
      ip = pattern.search(ipaddr.group())
      if ip.group() != "127.0":
          iplist.append(ip.group())

  return iplist

方法而也是在网上看到的,但是实际使用时却发现这个方法不work, 始终只能返回空的列表,后来才临时改成了方法1;方法二原始的博文还有判定platform的功能,可以自如的在windows 和 linux上面使用,但是链接没有记录,而且我只用到了他的一部分;

转载于:https://www.cnblogs.com/winditsway/p/5590869.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值