Skip to content

Instantly share code, notes, and snippets.

@anecdata
Last active May 18, 2024 14:16
Show Gist options
  • Save anecdata/b959170c069cd8936b16bb0be55d4ed2 to your computer and use it in GitHub Desktop.
Save anecdata/b959170c069cd8936b16bb0be55d4ed2 to your computer and use it in GitHub Desktop.
CircuitPython Static IP WIZnet TCP Server & Client
import time
import traceback
import board
import digitalio
import adafruit_connection_manager
from adafruit_wiznet5k.adafruit_wiznet5k import WIZNET5K
time.sleep(3) # wait for serial
# WIZnet W5500-EVB-Pico
spi = board.SPI()
cs = digitalio.DigitalInOut(board.GP17)
rst = digitalio.DigitalInOut(board.GP20)
radio = WIZNET5K(spi, cs, reset=rst, mac='de:ad:be:ef:fe:dd', is_dhcp=False, debug=False)
ipv4_address = radio.pretty_ip(radio.ip_address)
pool = adafruit_connection_manager.get_radio_socketpool(radio)
ip_address: str = "172.16.1.5"
subnet_mask: str = "255.255.255.0"
gateway_address: str = "10.0.0.1" # does not exist
dns_server: str = "10.0.0.1" # does not exist
radio.ifconfig = tuple(pool.inet_aton(num) for num in (ip_address, subnet_mask, gateway_address, dns_server))
HOST = ""
PORT = 5000
TIMEOUT = None
MAXBUF = 256
print("Create TCP Server Socket")
with pool.socket(pool.AF_INET, pool.SOCK_STREAM) as s:
s.settimeout(TIMEOUT)
s.bind((HOST, PORT))
s.listen()
print(f"Listening on {HOST}, {PORT}")
buf = bytearray(MAXBUF)
while True:
print("Accepting connections")
try:
conn, addr = s.accept()
conn.settimeout(TIMEOUT)
print("Accepted from", addr)
size = conn.recv_into(buf, MAXBUF)
print("Received", buf[:size], size, "bytes")
conn.send(buf[:size])
print("Sent", buf[:size], size, "bytes")
conn.close()
except Exception as ex:
traceback.print_exception(ex, ex, ex.__traceback__)
@anecdata
Copy link
Author

Server output:

code.py output:
Create TCP Server Socket
Listening on , 5000
Accepting connections
Accepted from ('0.0.0.0', 0)
Received bytearray(b'Hello, world') 12 bytes
Sent bytearray(b'Hello, world') 12 bytes
Accepting connections
Accepted from ('0.0.0.0', 0)
Received bytearray(b'Hello, world') 12 bytes
Sent bytearray(b'Hello, world') 12 bytes
Accepting connections
Accepted from ('172.16.1.1', 60413)
Received bytearray(b'Hello, world') 12 bytes
Sent bytearray(b'Hello, world') 12 bytes
Accepting connections
Accepted from ('172.16.1.1', 60414)
Received bytearray(b'Hello, world') 12 bytes
Sent bytearray(b'Hello, world') 12 bytes
Accepting connections

Client output:

Create TCP Client Socket
Connecting
Sent 12 bytes to 172.16.1.5:5000
Received b'Hello, world'
Connecting
Sent 12 bytes to 172.16.1.5:5000
Traceback (most recent call last):
  File "/Users/g/Desktop/tcp_client.py", line 25, in <module>
    buf = s.recv(MAXBUF)
socket.timeout: timed out
Connecting
Sent 12 bytes to 172.16.1.5:5000
Received b'Hello, world'
Connecting
Sent 12 bytes to 172.16.1.5:5000
Received b'Hello, world'
Connecting

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment