From: Michal Luczaj Date: Wed, 11 Jun 2025 19:56:50 +0000 (+0200) Subject: vsock/test: Introduce vsock_bind_try() helper X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=d56a8dbff8fea1c644183e52a39b165757f7b151;p=thirdparty%2Flinux.git vsock/test: Introduce vsock_bind_try() helper Create a socket and bind() it. If binding failed, gracefully return an error code while preserving `errno`. Base vsock_bind() on top of it. Suggested-by: Stefano Garzarella Reviewed-by: Stefano Garzarella Signed-off-by: Michal Luczaj Reviewed-by: Luigi Leonardi Link: https://patch.msgid.link/20250611-vsock-test-inc-cov-v3-1-5834060d9c20@rbox.co Signed-off-by: Jakub Kicinski --- diff --git a/tools/testing/vsock/util.c b/tools/testing/vsock/util.c index 0c7e9cbcbc85c..b7b3fb2221c16 100644 --- a/tools/testing/vsock/util.c +++ b/tools/testing/vsock/util.c @@ -121,15 +121,17 @@ bool vsock_wait_sent(int fd) return !ret; } -/* Create socket , bind to and return the file descriptor. */ -int vsock_bind(unsigned int cid, unsigned int port, int type) +/* Create socket , bind to . + * Return the file descriptor, or -1 on error. + */ +int vsock_bind_try(unsigned int cid, unsigned int port, int type) { struct sockaddr_vm sa = { .svm_family = AF_VSOCK, .svm_cid = cid, .svm_port = port, }; - int fd; + int fd, saved_errno; fd = socket(AF_VSOCK, type, 0); if (fd < 0) { @@ -138,6 +140,22 @@ int vsock_bind(unsigned int cid, unsigned int port, int type) } if (bind(fd, (struct sockaddr *)&sa, sizeof(sa))) { + saved_errno = errno; + close(fd); + errno = saved_errno; + fd = -1; + } + + return fd; +} + +/* Create socket , bind to and return the file descriptor. */ +int vsock_bind(unsigned int cid, unsigned int port, int type) +{ + int fd; + + fd = vsock_bind_try(cid, port, type); + if (fd < 0) { perror("bind"); exit(EXIT_FAILURE); } diff --git a/tools/testing/vsock/util.h b/tools/testing/vsock/util.h index 5e2db67072d50..0afe7cbae12e5 100644 --- a/tools/testing/vsock/util.h +++ b/tools/testing/vsock/util.h @@ -44,6 +44,7 @@ int vsock_connect(unsigned int cid, unsigned int port, int type); int vsock_accept(unsigned int cid, unsigned int port, struct sockaddr_vm *clientaddrp, int type); int vsock_stream_connect(unsigned int cid, unsigned int port); +int vsock_bind_try(unsigned int cid, unsigned int port, int type); int vsock_bind(unsigned int cid, unsigned int port, int type); int vsock_bind_connect(unsigned int cid, unsigned int port, unsigned int bind_port, int type);