From e8559479fb68c6648d5b7b6ba65fe17e551125e3 Mon Sep 17 00:00:00 2001 From: Oleksij Rempel Date: Fri, 26 Jul 2024 22:23:11 +0200 Subject: [PATCH] libj1939: Add function to connect a socket Introduce `libj1939_connect_socket` function to handle socket connections. Signed-off-by: Oleksij Rempel --- libj1939.c | 25 +++++++++++++++++++++++++ libj1939.h | 1 + 2 files changed, 26 insertions(+) diff --git a/libj1939.c b/libj1939.c index ed9a554..bb552c7 100644 --- a/libj1939.c +++ b/libj1939.c @@ -253,6 +253,31 @@ int libj1939_bind_socket(int sock, struct sockaddr_can *addr) return 0; } +/** + * libj1939_connect_socket - Connects a socket to a CAN address. + * @sock: The socket file descriptor. + * @addr: The CAN address to connect to. + * + * This function attempts to establish a connection between the given socket + * and the specified CAN address. If the connection fails, it logs an error + * message with the error code and a description of the error. + * + * Return: 0 on success, or a negative error code on failure. + */ +int libj1939_connect_socket(int sock, struct sockaddr_can *addr) +{ + int ret; + + ret = connect(sock, (void *)addr, sizeof(*addr)); + if (ret < 0) { + ret = -errno; + pr_err("failed to connect socket: %d (%s)", ret, strerror(ret)); + return ret; + } + + return 0; +} + /** * libj1939_socket_prio - Set the priority of a J1939 socket * @sock: The file descriptor of the socket diff --git a/libj1939.h b/libj1939.h index 7c19f43..62a2d84 100644 --- a/libj1939.h +++ b/libj1939.h @@ -43,6 +43,7 @@ void libj1939_init_sockaddr_can(struct sockaddr_can *sac, uint32_t pgn); int libj1939_open_socket(void); int libj1939_bind_socket(int sock, struct sockaddr_can *addr); +int libj1939_connect_socket(int sock, struct sockaddr_can *addr); int libj1939_socket_prio(int sock, int prio); int libj1939_set_broadcast(int sock); int libj1939_add_socket_to_epoll(int epoll_fd, int sock, uint32_t events);