Finding network (external) IP addresses using Pyth

2019-04-04 01:59发布

问题:

I want to know my internet provider (external) IP address (broadband or something else) with Python.

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. How do I find my external IP address through Python?

Thanks in advance.

回答1:

Use this script :

import urllib, json

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

Without 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).

Example of lib for linux : ifparser.



回答2:

Secure option (with https support)

from requests import get

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

Complete JSON response

P.S. requests module is convenient for https support. You can try httplib though.



回答3:

You'll have to use an external source you trust. 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.

Non-python oneliner:

wget -q -O- icanhazip.com


回答4:

You can check out this answer:

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

TL;DR:

import ipgetter
ip=ipgetter.myip()


回答5:

In my opinion the simplest solution is

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

Thats all.



回答6:

my website http;//botliam.com/1.php outputs your ip so you only need these 3 lines to get your 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"

if you want your own server to return your external ip instead of relying on my site the code for it is below:

<?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";
?>