From 10de6b3906e9260c5c63a96ba04a74d3ac1d48d0 Mon Sep 17 00:00:00 2001 From: ChuangMuLinze Date: Sat, 5 Dec 2026 17:29:29 +0800 Subject: [PATCH] feat(socketcan): name the channel when binding a socket fails bind_socket() re-raised the OSError from socket.bind() unchanged, so client code that catches it had no way to tell which bus failed when several were in use. Add the channel as a note on the exception, following the pattern used by candump for the same failure. --- can/interfaces/socketcan/socketcan.py | 6 +++++- doc/changelog.d/2104.added.rst | 1 + test/test_socketcan.py | 18 ++++++++++++++++++ 3 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 doc/changelog.d/2104.added.rst diff --git a/can/interfaces/socketcan/socketcan.py b/can/interfaces/socketcan/socketcan.py index 561991a90..52e5fa557 100644 --- a/can/interfaces/socketcan/socketcan.py +++ b/can/interfaces/socketcan/socketcan.py @@ -603,7 +603,11 @@ def bind_socket(sock: socket.socket, channel: str = "can0") -> None: If the specified interface isn't found. """ log.debug("Binding socket to channel=%s", channel) - sock.bind((channel,)) + try: + sock.bind((channel,)) + except OSError as exc: + exc.add_note(f"Failed to bind SocketCAN socket to channel {channel!r}.") + raise log.debug("Bound socket.") diff --git a/doc/changelog.d/2104.added.rst b/doc/changelog.d/2104.added.rst new file mode 100644 index 000000000..7a87eac45 --- /dev/null +++ b/doc/changelog.d/2104.added.rst @@ -0,0 +1 @@ +SocketCAN sockets now add the channel name to the `OSError` raised when binding fails, so it can be identified when several buses are in use. diff --git a/test/test_socketcan.py b/test/test_socketcan.py index a6de057d1..533dced11 100644 --- a/test/test_socketcan.py +++ b/test/test_socketcan.py @@ -31,6 +31,7 @@ BcmMsgHead, SocketcanBus, bcm_header_factory, + bind_socket, build_bcm_header, build_bcm_transmit_header, build_bcm_tx_delete_header, @@ -593,6 +594,23 @@ def test_capture_message_without_ancillary_data(self): self.assertIsNotNone(received) self.assertTrue(received.equals(expected), f"{received!r} != {expected!r}") + def test_bind_socket_adds_channel_to_oserror(self): + """bind_socket() keeps the original OSError and notes the channel""" + sock = Mock() + sock.bind.side_effect = OSError(errno.ENODEV, "No such device") + + with self.assertRaises(OSError) as ctx: + bind_socket(sock, "vcan42") + + sock.bind.assert_called_once_with(("vcan42",)) + # the error stays a plain OSError, so callers can still inspect it + self.assertEqual(ctx.exception.errno, errno.ENODEV) + self.assertEqual(ctx.exception.strerror, "No such device") + self.assertTrue( + any("vcan42" in note for note in ctx.exception.__notes__), + f"channel missing from {ctx.exception.__notes__!r}", + ) + if __name__ == "__main__": unittest.main()