Skip to content

Instantly share code, notes, and snippets.

@sananguliyev
Created January 5, 2025 19:35
Show Gist options
  • Save sananguliyev/79759295f8db1155f78ecb00c544ee5d to your computer and use it in GitHub Desktop.
Save sananguliyev/79759295f8db1155f78ecb00c544ee5d to your computer and use it in GitHub Desktop.
import cyberpi
import socket
import json
import network
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to network...')
wlan.connect('ssid', 'pass')
while not wlan.isconnected():
pass
# Server details
host = 'api.ipify.org'
port = 80
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
# Send HTTP GET request
request = "GET /?format=json HTTP/1.1\r\n"
request += "Host: " + host + "\r\n"
request += "Connection: close\r\n\r\n"
s.sendall(request.encode())
# Receive the response
response = b""
while True:
data = s.recv(1024)
if not data:
break
response += data
# Close the socket after use
s.close()
# Decode the response and extract the IP address
response_str = response.decode('utf-8')
# Split headers and body
header_end = response_str.find("\r\n\r\n")
if header_end != -1:
body = response_str[header_end + 4:] # The body starts after the headers
else:
body = response_str # If no headers found, the whole response is the body
try:
ip_data = json.loads(body)
ip_address = ip_data.get('ip', 'IP not found')
cyberpi.display.show_label(ip_address, 16, "center", index= 0)
except json.JSONDecodeError:
cyberpi.display.show_label("ERROR decoding JSON", 16, "center", index= 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment