Skip to content

Instantly share code, notes, and snippets.

@rafalw
Created November 8, 2019 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rafalw/6ec34d89b62a84640bcff075de4f716e to your computer and use it in GitHub Desktop.
Save rafalw/6ec34d89b62a84640bcff075de4f716e to your computer and use it in GitHub Desktop.
Pozyskiwanie zewnętrznego adresu IP
from pycurl import Curl
from pycurl import error
from io import BytesIO
# Pozyskiwanie zewnętrznego adresu IP
# Adres użyty jako parametr domyślny zwraca wiersz CSV – drugie pole to nasz zewnętrzny IP
def get_ip(url_api = 'http://ip4only.me/api/'):
my_ip = BytesIO()
c = Curl()
c.setopt(c.URL, url_api)
c.setopt(c.WRITEDATA, my_ip)
try:
c.perform()
except error as e:
print("Błąd: \"" + e.args[1] +"\"")
return None
else:
# Uwaga: poniższe wiersze są ściśle dostosowane do odpowiedzi
# zwracanej przez serwis o adresie umieszczonym jako domyślna wartość
# parametru url_api;
# w przypadku konieczności użycia innego serwisu/API należy oczywiście te wiersze zmienić!
ip_list = my_ip.getvalue().decode('UTF-8').split(',')
if len(ip_list) > 1:
ip_addr = ip_list[1] # drugie pole – adres IP
else:
ip_addr = None
c.close()
my_ip.close()
return ip_addr
if __name__ == "__main__":
address = get_ip()
if address:
print("Zewnętrzny adres IP: " + address)
else:
print("Sprawdź połączenie sieciowe.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment