Skip to content

Commit

Permalink
Merge pull request #6011 from cladmi/uhcpd_bind_to_device
Browse files Browse the repository at this point in the history
dist/tools/uhcpd: add an option to bind to device
  • Loading branch information
aabadie authored Nov 10, 2016
2 parents 9ce5a5b + 778d47c commit 04c23f3
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion dist/tools/uhcpd/uhcpd.c
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@
char _prefix[16];
unsigned _prefix_len;

static const char *BIND_OPTION = "--bind-to-device";
static void bind_to_device(int sock, const char *interface);

int ipv6_addr_split(char *addr_str, char seperator, int _default)
{
char *sep = addr_str;
Expand All @@ -39,9 +42,11 @@ int ipv6_addr_split(char *addr_str, char seperator, int _default)
int main(int argc, char *argv[])
{
static unsigned ifindex;
static unsigned _bind_to_device = 0;

if (argc < 3) {
fprintf(stderr, "usage: uhcpd <interface> <prefix/prefix_length>\n");
fprintf(stderr, "usage: uhcpd <interface> <prefix/prefix_length> [%s]\n",
BIND_OPTION);
exit(1);
}

Expand All @@ -57,6 +62,14 @@ int main(int argc, char *argv[])
exit(1);
}

if (argc == 4) {
if (strcmp(BIND_OPTION, argv[3])) {
fprintf(stderr, "error: unkwown option\n");
exit(1);
}
_bind_to_device = 1;
}

char *addr_str = UHCP_MCAST_ADDR;

struct addrinfo hint;
Expand All @@ -81,6 +94,10 @@ int main(int argc, char *argv[])
exit(1);
}

if (_bind_to_device) {
bind_to_device(sock, argv[1]);
}

if (bind(sock, mcast_addr->ai_addr, mcast_addr->ai_addrlen) < 0) {
perror("bind() failed");
exit(1);
Expand Down Expand Up @@ -144,3 +161,13 @@ int udp_sendto(uint8_t *buf, size_t len, uint8_t *dst, uint16_t dst_port, uhcp_i

return res;
}

/* Requires to be 'root', I didn't find another solution for the moment */
static void bind_to_device(int sock, const char *interface)
{
if (setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE,
interface, IF_NAMESIZE) < 0 ) {
perror("setsockopt(SO_BINDTODEVICE) failed");
exit(1);
}
}

0 comments on commit 04c23f3

Please sign in to comment.