Skip to content

Commit 6cadc41

Browse files
mmhalNipaLocal
authored andcommitted
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 <[email protected]> Reviewed-by: Stefano Garzarella <[email protected]> Signed-off-by: Michal Luczaj <[email protected]> Reviewed-by: Luigi Leonardi <[email protected]> Signed-off-by: NipaLocal <nipa@local>
1 parent 443296c commit 6cadc41

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

tools/testing/vsock/util.c

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -121,15 +121,17 @@ bool vsock_wait_sent(int fd)
121121
return !ret;
122122
}
123123

124-
/* Create socket <type>, bind to <cid, port> and return the file descriptor. */
125-
int vsock_bind(unsigned int cid, unsigned int port, int type)
124+
/* Create socket <type>, bind to <cid, port>.
125+
* Return the file descriptor, or -1 on error.
126+
*/
127+
int vsock_bind_try(unsigned int cid, unsigned int port, int type)
126128
{
127129
struct sockaddr_vm sa = {
128130
.svm_family = AF_VSOCK,
129131
.svm_cid = cid,
130132
.svm_port = port,
131133
};
132-
int fd;
134+
int fd, saved_errno;
133135

134136
fd = socket(AF_VSOCK, type, 0);
135137
if (fd < 0) {
@@ -138,6 +140,22 @@ int vsock_bind(unsigned int cid, unsigned int port, int type)
138140
}
139141

140142
if (bind(fd, (struct sockaddr *)&sa, sizeof(sa))) {
143+
saved_errno = errno;
144+
close(fd);
145+
errno = saved_errno;
146+
fd = -1;
147+
}
148+
149+
return fd;
150+
}
151+
152+
/* Create socket <type>, bind to <cid, port> and return the file descriptor. */
153+
int vsock_bind(unsigned int cid, unsigned int port, int type)
154+
{
155+
int fd;
156+
157+
fd = vsock_bind_try(cid, port, type);
158+
if (fd < 0) {
141159
perror("bind");
142160
exit(EXIT_FAILURE);
143161
}

tools/testing/vsock/util.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ int vsock_connect(unsigned int cid, unsigned int port, int type);
4444
int vsock_accept(unsigned int cid, unsigned int port,
4545
struct sockaddr_vm *clientaddrp, int type);
4646
int vsock_stream_connect(unsigned int cid, unsigned int port);
47+
int vsock_bind_try(unsigned int cid, unsigned int port, int type);
4748
int vsock_bind(unsigned int cid, unsigned int port, int type);
4849
int vsock_bind_connect(unsigned int cid, unsigned int port,
4950
unsigned int bind_port, int type);

0 commit comments

Comments
 (0)