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 <anna@addaleax.net>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Richard Lau <riclau@uk.ibm.com>
  • Loading branch information
danbev authored and rvagg committed Feb 28, 2019
1 parent 2335bcd commit f44f335
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 @@ -175,6 +175,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 @@ -191,24 +204,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 @@ -392,27 +392,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 f44f335

Please sign in to comment.