简体   繁体   English

使用Python查找网络(外部)IP地址

[英]Finding network (external) IP addresses using Python

I want to know my internet provider (external) IP address (broadband or something else) with Python. 我想通过Python了解我的互联网提供商(外部)IP地址(宽带或其他)。

There are multiple machines are connected to that network. 有多台机器连接到该网络。 I tried in different way's but I got only the local and public IP my machine. 我尝试了不同的方式,但我只获得本地和公共IP我的机器。 How do I find my external IP address through Python? 如何通过Python找到我的外部IP地址?

Thanks in advance. 提前致谢。

Use this script : 使用此脚本:

import urllib, json

data = json.loads(urllib.urlopen("http://ip.jsontest.com/").read())
print data["ip"]

Without json : 没有json:

import urllib, re

data = re.search('"([0-9.]*)"', urllib.urlopen("http://ip.jsontest.com/").read()).group(1)
print data

Other way it was to parse ifconfig (= linux) or ipconfig (= windows) command but take care with translated Windows System (ipconfig was translated). 其他方式是解析ifconfig(= linux)或ipconfig(= windows)命令,但要注意翻译的Windows系统(ipconfig已翻译)。

Example of lib for linux : ifparser . lib for linux的例子: ifparser

Secure option (with https support) 安全选项(支持https

from requests import get

get('https://ipapi.co/ip/').text

Complete JSON response 完成JSON响应

PS requests module is convenient for https support. PS requests模块便于https支持。 You can try httplib though. 你可以试试httplib

You'll have to use an external source you trust. 您必须使用您信任的外部来源。 Python2.x: Python2.x:

from urllib import urlopen
import json
url = 'http://api.hostip.info/get_json.php'
info = json.loads(urlopen(url).read())
print(info['ip'])

If you want more info, you can print more values from info . 如果您想要更多信息,可以从info打印更多值。

Non-python oneliner: 非python oneliner:

wget -q -O- icanhazip.com

You can check out this answer: 你可以看看这个答案:

https://stackoverflow.com/a/22157882/5687894 https://stackoverflow.com/a/22157882/5687894

TL;DR: TL; DR:

import ipgetter
ip=ipgetter.myip()

In my opinion the simplest solution is 在我看来,最简单的解决方案是

f = requests.request('GET', 'http://myip.dnsomatic.com')
ip = f.text

Thats all. 就这样。

my website http;//botliam.com/1.php outputs your ip so you only need these 3 lines to get your ip. 我的网站http:// botliam.com/1.php输出你的ip所以你只需要这3行来获取你的IP。

import requests
page = requests.get('http://botliam.com/1.php')
ip = page.text

what its doing is: 它的作用是:

  • opens my webpage and calls it "page" 打开我的网页并将其称为“页面”
  • sets "ip" to the contents of the "page" 将“ip”设置为“页面”的内容

if you want your own server to return your external ip instead of relying on my site the code for it is below: 如果你想让你自己的服务器返回你的外部IP而不是依赖我的网站,它的代码如下:

<?php
$ip = getenv('HTTP_CLIENT_IP')?:
getenv('HTTP_X_FORWARDED_FOR')?:
getenv('HTTP_X_FORWARDED')?:
getenv('HTTP_FORWARDED_FOR')?:
getenv('HTTP_FORWARDED')?:
getenv('REMOTE_ADDR');
echo "$ip";
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM