Code With Python
39.2K subscribers
886 photos
27 videos
22 files
769 links
This channel delivers clear, practical content for developers, covering Python, Django, Data Structures, Algorithms, and DSA – perfect for learning, coding, and mastering key programming skills.
Admin: @HusseinSheikho || @Hussein_Sheikho
Download Telegram
Topic: Python – Create IP Address Tracker GUI using Tkinter

---

### What You'll Build

A desktop app that allows the user to:

• Enter an IP address or domain
• Fetch geolocation data (country, city, ISP, etc.)
• Display it in a user-friendly Tkinter GUI

We'll use the requests library and a free API like ip-api.com.

---

### Step-by-Step Code

import tkinter as tk
from tkinter import messagebox
import requests

# Function to fetch IP information
def track_ip():
ip = entry.get().strip()
if not ip:
messagebox.showwarning("Input Error", "Please enter an IP or domain.")
return

try:
url = f"https://ip-api.com/json/{ip}"
response = requests.get(url)
data = response.json()

if data["status"] == "fail":
messagebox.showerror("Error", data["message"])
return

# Show info
result_text.set(
f"IP: {data['query']}\n"
f"Country: {data['country']}\n"
f"Region: {data['regionName']}\n"
f"City: {data['city']}\n"
f"ZIP: {data['zip']}\n"
f"ISP: {data['isp']}\n"
f"Timezone: {data['timezone']}\n"
f"Latitude: {data['lat']}\n"
f"Longitude: {data['lon']}"
)

except Exception as e:
messagebox.showerror("Error", str(e))

# GUI Setup
app = tk.Tk()
app.title("IP Tracker")
app.geometry("400x400")
app.resizable(False, False)

# Widgets
tk.Label(app, text="Enter IP Address or Domain:", font=("Arial", 12)).pack(pady=10)

entry = tk.Entry(app, width=40, font=("Arial", 12))
entry.pack()

tk.Button(app, text="Track IP", command=track_ip, font=("Arial", 12)).pack(pady=10)

result_text = tk.StringVar()
result_label = tk.Label(app, textvariable=result_text, justify="left", font=("Courier", 10))
result_label.pack(pady=10)

app.mainloop()


---

### Requirements

Install the requests library if not already installed:

pip install requests


---

### Exercise

• Enhance the app to export the result to a .txt or .csv file
• Add a map preview using a web view or link to Google Maps
• Add dark mode toggle for the GUI

---

#Python #Tkinter #IPTracker #Networking #GUI #DesktopApp

https://t.iss.one/DataScience4
5👍3
Code With Python
Photo
# 📚 PyQt5 Tutorial - Part 5/6: Networking, Multimedia & Internationalization
#PyQt5 #Networking #Multimedia #i18n #Deployment

Welcome to Part 5 of our PyQt5 series! This comprehensive lesson covers professional networking, multimedia handling, internationalization, and deployment strategies for production applications.

---

## 🔹 Networking with PyQt5
### 1. HTTP Requests with QNetworkAccessManager
from PyQt5.QtNetwork import QNetworkRequest, QNetworkAccessManager
from PyQt5.QtCore import QUrl

class ApiClient(QObject):
response_received = pyqtSignal(str)
error_occurred = pyqtSignal(str)

def __init__(self):
super().__init__()
self.manager = QNetworkAccessManager()
self.manager.finished.connect(self.handle_response)

def fetch_data(self, url):
request = QNetworkRequest(QUrl(url))
self.manager.get(request)

def handle_response(self, reply):
if reply.error():
self.error_occurred.emit(reply.errorString())
else:
data = reply.readAll().data().decode('utf-8')
self.response_received.emit(data)
reply.deleteLater()

# Usage
client = ApiClient()
client.response_received.connect(lambda data: print("Received:", data))
client.error_occurred.connect(lambda err: print("Error:", err))
client.fetch_data("https://api.example.com/data")


### 2. WebSocket Communication
from PyQt5.QtWebSockets import QWebSocket

class WebSocketClient(QObject):
message_received = pyqtSignal(str)
connected = pyqtSignal()
disconnected = pyqtSignal()

def __init__(self):
super().__init__()
self.socket = QWebSocket()
self.socket.textMessageReceived.connect(self.message_received)
self.socket.connected.connect(self.connected)
self.socket.disconnected.connect(self.disconnected)

def connect_to_server(self, url):
self.socket.open(QUrl(url))

def send_message(self, message):
self.socket.sendTextMessage(message)

# Usage
ws_client = WebSocketClient()
ws_client.connect_to_server("ws://echo.websocket.org")
ws_client.iss.onessage_received.connect(print)


### 3. TCP Socket Server
from PyQt5.QtNetwork import QTcpServer, QTcpSocket

class TcpServer(QObject):
new_connection = pyqtSignal(QTcpSocket)

def __init__(self):
super().__init__()
self.server = QTcpServer()
self.server.newConnection.connect(self.handle_new_connection)

def start(self, port=12345):
if not self.server.listen(QHostAddress.Any, port):
print("Server error:", self.server.errorString())
return False
print(f"Server started on port {port}")
return True

def handle_new_connection(self):
client = self.server.nextPendingConnection()
client.readyRead.connect(lambda: self.read_data(client))
client.disconnected.connect(client.deleteLater)
self.new_connection.emit(client)

def read_data(self, client):
data = client.readAll().data().decode('utf-8')
print("Received:", data)
client.write(f"Echo: {data}".encode())


---
2
Code With Python
Photo
## 🔹 Practical Example: Weather App
class WeatherApp(QMainWindow):
def __init__(self):
super().__init__()
self.api_key = "YOUR_API_KEY"
self.setup_ui()
self.setup_network()

def setup_ui(self):
self.setWindowTitle(self.tr("Weather App"))

# Location Input
self.location_input = QLineEdit()
search_btn = QPushButton(self.tr("Search"))
search_btn.clicked.connect(self.fetch_weather)

# Weather Display
self.weather_icon = QLabel()
self.weather_icon.setAlignment(Qt.AlignCenter)

self.temp_label = QLabel()
self.temp_label.setAlignment(Qt.AlignCenter)
font = self.temp_label.font()
font.setPointSize(48)
self.temp_label.setFont(font)

self.details_label = QLabel()
self.details_label.setAlignment(Qt.AlignCenter)

# Layout
input_layout = QHBoxLayout()
input_layout.addWidget(self.location_input)
input_layout.addWidget(search_btn)

main_layout = QVBoxLayout()
main_layout.addLayout(input_layout)
main_layout.addWidget(self.weather_icon)
main_layout.addWidget(self.temp_label)
main_layout.addWidget(self.details_label)

container = QWidget()
container.setLayout(main_layout)
self.setCentralWidget(container)

def setup_network(self):
self.manager = QNetworkAccessManager()
self.manager.finished.connect(self.handle_weather_response)

self.icon_manager = QNetworkAccessManager()
self.icon_manager.finished.connect(self.handle_icon_response)

def fetch_weather(self):
location = self.location_input.text()
if not location:
return

url = f"https://api.openweathermap.org/data/2.5/weather?q={location}&appid={self.api_key}&units=metric"
self.manager.get(QNetworkRequest(QUrl(url)))

def handle_weather_response(self, reply):
if reply.error():
QMessageBox.warning(self, self.tr("Error"),
self.tr("Failed to fetch weather data"))
return

data = json.loads(reply.readAll().data().decode('utf-8'))

# Update UI
temp = data['main']['temp']
self.temp_label.setText(f"{temp}°C")

description = data['weather'][0]['description'].capitalize()
humidity = data['main']['humidity']
wind = data['wind']['speed']
self.details_label.setText(
self.tr(f"{description}\nHumidity: {humidity}%\nWind: {wind} m/s"))

# Fetch weather icon
icon_code = data['weather'][0]['icon']
icon_url = f"https://openweathermap.org/img/wn/{icon_code}@2x.png"
self.icon_manager.get(QNetworkRequest(QUrl(icon_url)))

def handle_icon_response(self, reply):
if not reply.error():
pixmap = QPixmap()
pixmap.loadFromData(reply.readAll())
self.weather_icon.setPixmap(pixmap.scaledToWidth(100))


---

## 🔹 Best Practices
1. Handle network errors gracefully - Always check reply.error()
2. Clean up resources - Call deleteLater() on network objects
3. Cache API responses - Reduce unnecessary network calls
4. Use QThread for intensive operations - Keep UI responsive
5. Test translations thoroughly - Verify all UI elements adapt

---

### 📌 What's Next?
In Final Part 6, we'll cover:
➡️ Advanced Architecture Patterns
➡️ Plugin Systems
➡️ Performance Optimization
➡️ Cross-Platform Considerations

#PyQt5 #Networking #Multimedia #Deployment 🚀

Practice Exercise:
1. Build a podcast player with download capability
2. Create a multilingual chat application
3. Implement an auto-updating stock ticker
2
Top 30 Cyber Security Commands & Tools

#CyberSecurity #Reconnaissance #InfoGathering

#1. ping
Tests reachability of a host on an IP network and measures round-trip time.

ping -c 4 google.com

PING google.com (142.250.72.14) 56(84) bytes of data.
64 bytes from lhr48s23-in-f14.1e100.net (142.250.72.14): icmp_seq=1 ttl=118 time=8.53 ms
...
--- google.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3005ms


#2. whois
Retrieves registration information for a domain name or IP address.

whois google.com

Domain Name: GOOGLE.COM
Registry Domain ID: 2138514_DOMAIN_COM-VRSN
Registrar WHOIS Server: whois.markmonitor.com
...
Registrant Organization: Google LLC
Registrant State/Province: CA
Registrant Country: US


#3. dig
(Domain Information Groper) A tool for querying DNS servers.

dig google.com

; <<>> DiG 9.18.1-1-Debian <<>> google.com
;; ANSWER SECTION:
google.com. 156 IN A 142.250.187.238
...
;; Query time: 12 msec
;; SERVER: 8.8.8.8#53(8.8.8.8)


#4. nmap
Network Mapper. A powerful tool for network discovery, port scanning, and security auditing.

nmap -sV -p 80,443 scanme.nmap.org

Starting Nmap 7.92 ( https://nmap.org ) at ...
Nmap scan report for scanme.nmap.org (45.33.32.156)
Host is up (0.16s latency).

PORT STATE SERVICE VERSION
80/tcp open http Apache httpd 2.4.7 ((Ubuntu))
443/tcp open ssl/http Apache httpd 2.4.7 ((Ubuntu))


#5. netcat (nc)
The "Swiss army knife" of networking. Can be used for port scanning, file transfer, and creating backdoors.

nc -zv scanme.nmap.org 80

Connection to scanme.nmap.org (45.33.32.156) 80 port [tcp/http] succeeded!

---
#CyberSecurity #Networking #Analysis

#6. netstat
Displays active network connections, routing tables, and interface statistics.

netstat -tulpn

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 127.0.0.1:5432 0.0.0.0:* LISTEN 675/postgres
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 789/sshd
udp 0 0 0.0.0.0:68 0.0.0.0:* 654/dhclient


#7. traceroute
Traces the network path (hops) to a remote host.

traceroute 8.8.8.8

traceroute to 8.8.8.8 (8.8.8.8), 30 hops max, 60 byte packets
1 gateway (192.168.1.1) 1.234 ms 1.567 ms 1.890 ms
2 isp-router.net (10.0.0.1) 5.432 ms 5.678 ms 5.901 ms
...
10 142.251.52.221 (142.251.52.221) 10.112 ms 10.345 ms 10.578 ms
11 dns.google (8.8.8.8) 10.801 ms 10.923 ms 11.045 ms


#8. tcpdump
A powerful command-line packet analyzer that allows you to capture and display network traffic.

sudo tcpdump -i eth0 -c 5 port 80

tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth0, link-type EN10MB (Ethernet), capture size 262144 bytes
14:30:01.123456 IP my-pc.54321 > example.com.80: Flags [S], seq 123456789, win 64240, options [mss 1460,sackOK,TS val 10,ecr 0], length 0
... (4 more packets) ...
5 packets captured


#9. arp
Displays and modifies the Address Resolution Protocol (ARP) cache, which maps IP addresses to MAC addresses.

arp -a

? (192.168.1.1) at 00:1a:2b:3c:4d:5e [ether] on eth0
? (192.168.1.105) at 98:76:54:32:10:fe [ether] on eth0


#10. ip
A modern tool to show and manipulate routing, devices, policy routing, and tunnels. (Replaces ifconfig).

ip addr show
1