Skip to content

Commit 526317d

Browse files
committed
fix(udp_server): Add selection for bind IP
1 parent c24a1f1 commit 526317d

File tree

1 file changed

+92
-4
lines changed

1 file changed

+92
-4
lines changed

libraries/WiFi/examples/WiFiUDPClient/udp_server.py

Lines changed: 92 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,92 @@
22
# for messages from the ESP32 board and prints them
33
import socket
44
import sys
5+
import subprocess
6+
import platform
7+
8+
def get_interface_ips():
9+
"""Get all available interface IP addresses"""
10+
interface_ips = []
11+
12+
# Try using system commands to get interface IPs
13+
system = platform.system().lower()
14+
15+
try:
16+
if system == "darwin" or system == "linux":
17+
# Use 'ifconfig' on macOS/Linux
18+
result = subprocess.run(['ifconfig'], capture_output=True, text=True, timeout=5)
19+
if result.returncode == 0:
20+
lines = result.stdout.split('\n')
21+
for line in lines:
22+
if 'inet ' in line and '127.0.0.1' not in line:
23+
# Extract IP address from ifconfig output
24+
parts = line.strip().split()
25+
for i, part in enumerate(parts):
26+
if part == 'inet':
27+
if i + 1 < len(parts):
28+
ip = parts[i + 1]
29+
if ip not in interface_ips and ip != '127.0.0.1':
30+
interface_ips.append(ip)
31+
break
32+
elif system == "windows":
33+
# Use 'ipconfig' on Windows
34+
result = subprocess.run(['ipconfig'], capture_output=True, text=True, timeout=5)
35+
if result.returncode == 0:
36+
lines = result.stdout.split('\n')
37+
for line in lines:
38+
if 'IPv4 Address' in line and '127.0.0.1' not in line:
39+
# Extract IP address from ipconfig output
40+
if ':' in line:
41+
ip = line.split(':')[1].strip()
42+
if ip not in interface_ips and ip != '127.0.0.1':
43+
interface_ips.append(ip)
44+
except (subprocess.TimeoutExpired, subprocess.SubprocessError, FileNotFoundError):
45+
pass
46+
47+
# Fallback: try to get IPs using socket methods
48+
if not interface_ips:
49+
try:
50+
# Get all IP addresses associated with the hostname
51+
hostname = socket.gethostname()
52+
ip_list = socket.gethostbyname_ex(hostname)[2]
53+
for ip in ip_list:
54+
if ip not in interface_ips and ip != '127.0.0.1':
55+
interface_ips.append(ip)
56+
except socket.gaierror:
57+
pass
58+
59+
# Fail if no interfaces found
60+
if not interface_ips:
61+
print("Error: No network interfaces found. Please check your network configuration.")
62+
sys.exit(1)
63+
64+
return interface_ips
65+
66+
def select_interface(interface_ips):
67+
"""Ask user to select which interface to bind to"""
68+
if len(interface_ips) == 1:
69+
print(f"Using interface: {interface_ips[0]}")
70+
return interface_ips[0]
71+
72+
print("Multiple network interfaces detected:")
73+
for i, ip in enumerate(interface_ips, 1):
74+
print(f" {i}. {ip}")
75+
76+
while True:
77+
try:
78+
choice = input(f"Select interface (1-{len(interface_ips)}): ").strip()
79+
choice_idx = int(choice) - 1
80+
if 0 <= choice_idx < len(interface_ips):
81+
selected_ip = interface_ips[choice_idx]
82+
print(f"Selected interface: {selected_ip}")
83+
return selected_ip
84+
else:
85+
print(f"Please enter a number between 1 and {len(interface_ips)}")
86+
except ValueError:
87+
print("Please enter a valid number")
88+
except KeyboardInterrupt:
89+
print("\nExiting...")
90+
sys.exit(1)
591

692
try:
793
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
@@ -10,15 +96,17 @@
1096
print("Failed to create socket. Error Code : " + str(msg[0]) + " Message " + msg[1])
1197
sys.exit()
1298

99+
# Get available interfaces and let user choose
100+
interface_ips = get_interface_ips()
101+
selected_ip = select_interface(interface_ips)
102+
13103
try:
14-
s.bind(("", 3333))
104+
s.bind((selected_ip, 3333))
15105
except socket.error as msg:
16106
print("Bind failed. Error: " + str(msg[0]) + ": " + msg[1])
17107
sys.exit()
18108

19-
print("Server listening")
20-
21-
print("Server listening")
109+
print(f"Server listening on {selected_ip}:3333")
22110

23111
while 1:
24112
d = s.recvfrom(1024)

0 commit comments

Comments
 (0)