From 496aa3ef4f389fbb00616eeabbfedc93bb7bfd17 Mon Sep 17 00:00:00 2001 From: "chao.an" Date: Wed, 16 Jun 2021 16:11:34 +0800 Subject: [PATCH] netutils/dhcpd: bind socket to the interface Change-Id: Icf7cf8147ceca5e27b7b923d520e2189741d9882 Signed-off-by: chao.an --- netutils/dhcpd/dhcpd.c | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/netutils/dhcpd/dhcpd.c b/netutils/dhcpd/dhcpd.c index e883868f6..31e26904f 100644 --- a/netutils/dhcpd/dhcpd.c +++ b/netutils/dhcpd/dhcpd.c @@ -56,6 +56,7 @@ #include #include +#include #include #include "netutils/netlib.h" @@ -820,7 +821,7 @@ static int dhcp_addoption32p(uint8_t code, FAR uint8_t *value) * Name: dhcpd_socket ****************************************************************************/ -static inline int dhcpd_socket(void) +static inline int dhcpd_socket(FAR const char *interface) { int sockfd; #if defined(HAVE_SO_REUSEADDR) || defined(HAVE_SO_BROADCAST) @@ -863,6 +864,22 @@ static inline int dhcpd_socket(void) } #endif +#ifdef CONFIG_NET_UDP_BINDTODEVICE + /* Bind socket to interface, because UDP packets have to be sent to the + * broadcast address at a moment when it is not possible to decide the + * target network device using the local or remote address (which is, + * by definition and purpose of DHCP, undefined yet). + */ + + if (setsockopt(sockfd, IPPROTO_UDP, UDP_BINDTODEVICE, + interface, strlen(interface)) < 0) + { + ninfo("ERROR: setsockopt UDP_BINDTODEVICE failed: %d\n", errno); + close(sockfd); + return ERROR; + } +#endif + return sockfd; } @@ -1396,7 +1413,7 @@ static inline int dhcpd_openlistener(FAR const char *interface) /* Create a socket to listen for requests from DHCP clients */ - sockfd = dhcpd_socket(); + sockfd = dhcpd_socket(interface); if (sockfd < 0) { nerr("ERROR: socket failed: %d\n", errno);