refactor: prepare ipv6

This commit is contained in:
Alex 2019-05-16 12:14:12 +02:00
parent f3c467cc46
commit 9c67150884

View File

@ -329,14 +329,22 @@ void waybar::modules::Network::getInterfaceAddress() {
netmask_.clear(); netmask_.clear();
cidr_ = 0; cidr_ = 0;
int success = getifaddrs(&ifaddr); int success = getifaddrs(&ifaddr);
if (success == 0) { if (success != 0) {
return;
}
ifa = ifaddr; ifa = ifaddr;
while (ifa != nullptr && ipaddr_.empty() && netmask_.empty()) { while (ifa != nullptr && ipaddr_.empty() && netmask_.empty()) {
if (ifa->ifa_addr != nullptr && ifa->ifa_addr->sa_family == family_) { if (ifa->ifa_addr != nullptr && ifa->ifa_addr->sa_family == family_ &&
if (strcmp(ifa->ifa_name, ifname_.c_str()) == 0) { ifa->ifa_name == ifname_) {
ipaddr_ = inet_ntoa(((struct sockaddr_in *)ifa->ifa_addr)->sin_addr); char ipaddr[INET6_ADDRSTRLEN];
netmask_ = inet_ntoa(((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr); ipaddr_ = inet_ntop(family_,
cidrRaw = ((struct sockaddr_in *)(ifa->ifa_netmask))->sin_addr.s_addr; &reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr)->sin_addr,
ipaddr,
INET6_ADDRSTRLEN);
char netmask[INET6_ADDRSTRLEN];
auto net_addr = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_netmask);
netmask_ = inet_ntop(family_, &net_addr->sin_addr, netmask, INET6_ADDRSTRLEN);
cidrRaw = net_addr->sin_addr.s_addr;
linked_ = ifa->ifa_flags & IFF_RUNNING; linked_ = ifa->ifa_flags & IFF_RUNNING;
unsigned int cidr = 0; unsigned int cidr = 0;
while (cidrRaw) { while (cidrRaw) {
@ -345,12 +353,10 @@ void waybar::modules::Network::getInterfaceAddress() {
} }
cidr_ = cidr; cidr_ = cidr;
} }
}
ifa = ifa->ifa_next; ifa = ifa->ifa_next;
} }
freeifaddrs(ifaddr); freeifaddrs(ifaddr);
} }
}
int waybar::modules::Network::netlinkRequest(void *req, uint32_t reqlen, uint32_t groups) { int waybar::modules::Network::netlinkRequest(void *req, uint32_t reqlen, uint32_t groups) {
struct sockaddr_nl sa = {}; struct sockaddr_nl sa = {};
@ -394,7 +400,7 @@ int waybar::modules::Network::getPreferredIface() {
ifname_ = config_["interface"].asString(); ifname_ = config_["interface"].asString();
return ifid_; return ifid_;
} else { } else {
// Try with regex // Try with wildcard
struct ifaddrs *ifaddr, *ifa; struct ifaddrs *ifaddr, *ifa;
int success = getifaddrs(&ifaddr); int success = getifaddrs(&ifaddr);
if (success != 0) { if (success != 0) {
@ -402,7 +408,7 @@ int waybar::modules::Network::getPreferredIface() {
} }
ifa = ifaddr; ifa = ifaddr;
ifid_ = -1; ifid_ = -1;
while (ifa != nullptr && ipaddr_.empty() && netmask_.empty()) { while (ifa != nullptr) {
if (wildcardMatch(config_["interface"].asString(), ifa->ifa_name)) { if (wildcardMatch(config_["interface"].asString(), ifa->ifa_name)) {
ifid_ = if_nametoindex(ifa->ifa_name); ifid_ = if_nametoindex(ifa->ifa_name);
break; break;