Skip to content

Commit

Permalink
Use bind() instead of setsockopt() for binding raw sockets on Lin…
Browse files Browse the repository at this point in the history
…ux (#1646)

* Update to `bind()`

* Remove the `struct` keyword

---------

Co-authored-by: Ege Çetin <64282645+egecetin@users.noreply.github.com>
  • Loading branch information
seladb and egecetin authored Dec 3, 2024
1 parent 6ae4d2d commit 04bde0d
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions Pcap++/src/RawSocketDevice.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,7 @@ namespace pcpp
int fd = socket(AF_PACKET, SOCK_RAW, htobe16(ETH_P_ALL));
if (fd < 0)
{
PCPP_LOG_ERROR("Failed to create raw socket. Error code was " << errno);
PCPP_LOG_ERROR("Failed to create raw socket. Error code was " << strerror(errno));
return false;
}

Expand Down Expand Up @@ -505,12 +505,15 @@ namespace pcpp
}

// bind raw socket to interface
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", ifaceName.c_str());
if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, (void*)&ifr, sizeof(ifr)) == -1)
sockaddr_ll saddr;
memset(&saddr, 0, sizeof(saddr));
saddr.sll_family = AF_PACKET;
saddr.sll_protocol = htons(ETH_P_ALL);
saddr.sll_ifindex = if_nametoindex(ifaceName.c_str());

if (bind(fd, reinterpret_cast<sockaddr*>(&saddr), sizeof(saddr)) < 0)
{
PCPP_LOG_ERROR("Cannot bind raw socket to interface '" << ifaceName << "'");
PCPP_LOG_ERROR("Cannot bind raw socket to interface '" << ifaceName << "': " << strerror(errno));
::close(fd);
return false;
}
Expand Down

0 comments on commit 04bde0d

Please sign in to comment.