From 74b5534fd3ff4731dc9ba90d44b1119f048ec2c1 Mon Sep 17 00:00:00 2001 From: youdie006 Date: Thu, 27 Aug 2026 20:11:27 +0900 Subject: [PATCH] Close the udp socket in close(), not just drop the reference. ModbusUdpClient.close() documents that it closes the underlying socket connection but only cleared the attribute, so the socket was left open. ModbusTcpClient.close() and ModbusSerialClient.close() both close it first. --- pymodbus/client/udp.py | 2 ++ test/client/test_client_sync.py | 9 +++++++++ 2 files changed, 11 insertions(+) diff --git a/pymodbus/client/udp.py b/pymodbus/client/udp.py index 9f70bbba1..5b50a22cf 100644 --- a/pymodbus/client/udp.py +++ b/pymodbus/client/udp.py @@ -204,6 +204,8 @@ def close(self): :meta private: """ + if self.socket: + self.socket.close() self.socket = None def send(self, request: bytes, addr: tuple | None = None) -> int: diff --git a/test/client/test_client_sync.py b/test/client/test_client_sync.py index da36b8a77..891b04100 100755 --- a/test/client/test_client_sync.py +++ b/test/client/test_client_sync.py @@ -61,6 +61,15 @@ def test_udp_client_is_socket_open(self): client = ModbusUdpClient("127.0.0.1") assert client.is_socket_open() + def test_udp_client_close_releases_socket(self): + """Test the udp client close method releases the socket.""" + client = ModbusUdpClient("127.0.0.1") + assert client.connect() + sock = client.socket + client.close() + assert sock.fileno() == -1 + assert not client.connected + def test_udp_client_send(self): """Test the udp client send method.""" client = ModbusUdpClient("127.0.0.1")