Skip to content

Commit

Permalink
src: extract common sockaddr creation code
Browse files Browse the repository at this point in the history
This commit extracts code to create sockaddr which is shared by both
UDPWrap::DoBind and UDPWrap::DoSend.

PR-URL: #26070
Reviewed-By: Anna Henningsen <[email protected]>
Reviewed-By: James M Snell <[email protected]>
Reviewed-By: Richard Lau <[email protected]>
  • Loading branch information
danbev authored and MylesBorins committed May 16, 2019
1 parent bc5e04b commit 57469e6
Showing 1 changed file with 19 additions and 32 deletions.
51 changes: 19 additions & 32 deletions src/udp_wrap.cc
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,19 @@ void UDPWrap::GetFD(const FunctionCallbackInfo<Value>& args) {
args.GetReturnValue().Set(fd);
}

int sockaddr_for_family(int address_family,
const char* address,
const unsigned short port,
struct sockaddr_storage* addr) {
switch (address_family) {
case AF_INET:
return uv_ip4_addr(address, port, reinterpret_cast<sockaddr_in*>(addr));
case AF_INET6:
return uv_ip6_addr(address, port, reinterpret_cast<sockaddr_in6*>(addr));
default:
CHECK(0 && "unexpected address family");
}
}

void UDPWrap::DoBind(const FunctionCallbackInfo<Value>& args, int family) {
UDPWrap* wrap;
Expand All @@ -181,24 +194,11 @@ void UDPWrap::DoBind(const FunctionCallbackInfo<Value>& args, int family) {
if (!args[1]->Uint32Value(ctx).To(&port) ||
!args[2]->Uint32Value(ctx).To(&flags))
return;
char addr[sizeof(sockaddr_in6)];
int err;

switch (family) {
case AF_INET:
err = uv_ip4_addr(*address, port, reinterpret_cast<sockaddr_in*>(&addr));
break;
case AF_INET6:
err = uv_ip6_addr(*address, port, reinterpret_cast<sockaddr_in6*>(&addr));
break;
default:
CHECK(0 && "unexpected address family");
ABORT();
}

struct sockaddr_storage addr_storage;
int err = sockaddr_for_family(family, address.out(), port, &addr_storage);
if (err == 0) {
err = uv_udp_bind(&wrap->handle_,
reinterpret_cast<const sockaddr*>(&addr),
reinterpret_cast<const sockaddr*>(&addr_storage),
flags);
}

Expand Down Expand Up @@ -369,27 +369,14 @@ void UDPWrap::DoSend(const FunctionCallbackInfo<Value>& args, int family) {

req_wrap->msg_size = msg_size;

char addr[sizeof(sockaddr_in6)];
int err;

switch (family) {
case AF_INET:
err = uv_ip4_addr(*address, port, reinterpret_cast<sockaddr_in*>(&addr));
break;
case AF_INET6:
err = uv_ip6_addr(*address, port, reinterpret_cast<sockaddr_in6*>(&addr));
break;
default:
CHECK(0 && "unexpected address family");
ABORT();
}

struct sockaddr_storage addr_storage;
int err = sockaddr_for_family(family, address.out(), port, &addr_storage);
if (err == 0) {
err = req_wrap->Dispatch(uv_udp_send,
&wrap->handle_,
*bufs,
count,
reinterpret_cast<const sockaddr*>(&addr),
reinterpret_cast<const sockaddr*>(&addr_storage),
OnSend);
}

Expand Down

0 comments on commit 57469e6

Please sign in to comment.