From 5b5904b7cc38a063995912c950abb22ae68c600a Mon Sep 17 00:00:00 2001 From: Simon Tatham Date: Sat, 8 Jan 2022 15:28:34 +0000 Subject: [PATCH] windows/network.c: refactor switch in sk_newlistener. The code that diverges based on the address family is now in the form of a switch statement, rather than an unwieldy series of chained ifs. And the final call to bind() has all its arguments worked out in the previous switch, rather than computing them at the last minute with an equally unwieldy set of ?: operators that repeat the previous test. This will make it easier to add more cases, and also, to keep each case under its own ifdef without losing too much legibility. --- windows/network.c | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/windows/network.c b/windows/network.c index 7e9dda28..3d524d85 100644 --- a/windows/network.c +++ b/windows/network.c @@ -1131,6 +1131,8 @@ Socket *sk_newlistener(const char *srcaddr, int port, Plug *plug, SOCKADDR_IN6 a6; #endif SOCKADDR_IN a; + struct sockaddr *bindaddr; + unsigned bindsize; DWORD err; const char *errstr; @@ -1198,8 +1200,9 @@ Socket *sk_newlistener(const char *srcaddr, int port, Plug *plug, (const char *)&on, sizeof(on)); } + switch (address_family) { #ifndef NO_IPV6 - if (address_family == AF_INET6) { + case AF_INET6: { memset(&a6, 0, sizeof(a6)); a6.sin6_family = AF_INET6; if (local_host_only) @@ -1226,9 +1229,12 @@ Socket *sk_newlistener(const char *srcaddr, int port, Plug *plug, } } a6.sin6_port = p_htons(port); - } else + bindaddr = (struct sockaddr *)&a6; + bindsize = sizeof(a6); + break; + } #endif - { + case AF_INET: { bool got_addr = false; a.sin_family = AF_INET; @@ -1256,16 +1262,15 @@ Socket *sk_newlistener(const char *srcaddr, int port, Plug *plug, } a.sin_port = p_htons((short)port); + bindaddr = (struct sockaddr *)&a; + bindsize = sizeof(a); + break; + } + default: + unreachable("bad address family in sk_newlistener_internal"); } -#ifndef NO_IPV6 - retcode = p_bind(s, (address_family == AF_INET6 ? - (struct sockaddr *) &a6 : - (struct sockaddr *) &a), - (address_family == - AF_INET6 ? sizeof(a6) : sizeof(a))); -#else - retcode = p_bind(s, (struct sockaddr *) &a, sizeof(a)); -#endif + + retcode = p_bind(s, bindaddr, bindsize); if (retcode != SOCKET_ERROR) { err = 0; } else {