python脚本获取内网,公网ip

获取内网ip: get_inner_ipaddr.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(('8.8.8.8', 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

 获取公网ip:get_public_ipaddr.py

#!/usr/bin/env python
import re,urllib2
class Get_public_ip:
  def getip(self):
    try:
      myip = self.visit("http://ip.chinaz.com/getip.aspx")
    except:
      try:
        myip = self.visit("http://ipv4.icanhazip.com/")
      except:
        myip = "So sorry!!!"
    return myip
  def visit(self,url):
    opener = urllib2.urlopen(url)
    if url == opener.geturl():
      str = opener.read()
    return re.search('\d+\.\d+\.\d+\.\d+',str).group(0)

if __name__ == "__main__":
  getmyip = Get_public_ip()
  print getmyip.getip()

 

转载于:https://my.oschina.net/yiyuanxi/blog/1632197

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值