feat(network): display ip address and subnetmask

This commit is contained in:
Robinhuett 2018-11-13 21:31:26 +01:00
parent 3dc0f7ccf9
commit 5c66b1a770
2 changed files with 41 additions and 1 deletions

View File

@ -1,6 +1,8 @@
#pragma once
#include <net/if.h>
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <netlink/netlink.h>
#include <netlink/genl/genl.h>
#include <netlink/genl/ctrl.h>
@ -24,6 +26,7 @@ class Network : public ALabel {
void disconnected();
void initNL80211();
int getExternalInterface();
void getInterfaceAddress();
void parseEssid(struct nlattr**);
void parseSignal(struct nlattr**);
bool associatedOrJoined(struct nlattr**);
@ -39,6 +42,9 @@ class Network : public ALabel {
std::string essid_;
std::string ifname_;
std::string ipaddr_;
std::string netmask_;
int cidr_;
int signal_strength_dbm_;
uint16_t signal_strength_;
};

View File

@ -26,6 +26,7 @@ waybar::modules::Network::Network(const Json::Value& config)
char ifname[IF_NAMESIZE];
if_indextoname(ifid_, ifname);
ifname_ = ifname;
getInterfaceAddress();
}
}
initNL80211();
@ -64,6 +65,7 @@ waybar::modules::Network::Network(const Json::Value& config)
char ifname[IF_NAMESIZE];
if_indextoname(ifid_, ifname);
ifname_ = ifname;
getInterfaceAddress();
need_update = true;
}
}
@ -101,7 +103,10 @@ auto waybar::modules::Network::update() -> void
fmt::arg("essid", essid_),
fmt::arg("signaldBm", signal_strength_dbm_),
fmt::arg("signalStrength", signal_strength_),
fmt::arg("ifname", ifname_)
fmt::arg("ifname", ifname_),
fmt::arg("netmask", netmask_),
fmt::arg("ipaddr", ipaddr_),
fmt::arg("cidr", cidr_)
));
}
@ -110,6 +115,9 @@ void waybar::modules::Network::disconnected()
essid_.clear();
signal_strength_dbm_ = 0;
signal_strength_ = 0;
ipaddr_.clear();
netmask_.clear();
cidr_ = 0;
ifname_.clear();
ifid_ = -1;
}
@ -255,6 +263,32 @@ out:
return ifidx;
}
void waybar::modules::Network::getInterfaceAddress() {
unsigned int cidrRaw;
struct ifaddrs *ifaddr, *ifa;
int success = getifaddrs(&ifaddr);
if (success == 0) {
ifa = ifaddr;
while(ifa != NULL && ipaddr_.empty() && netmask_.empty()) {
if(ifa->ifa_addr->sa_family == family_) {
if(strcmp(ifa->ifa_name, ifname_.c_str()) == 0){
ipaddr_=inet_ntoa(((struct sockaddr_in*)ifa->ifa_addr)->sin_addr);
netmask_=inet_ntoa(((struct sockaddr_in*)ifa->ifa_netmask)->sin_addr);
cidrRaw = ((struct sockaddr_in *)(ifa->ifa_netmask))->sin_addr.s_addr;
unsigned int cidr = 0;
while (cidrRaw) {
cidr += cidrRaw & 1;
cidrRaw >>= 1;
}
cidr_ = cidr;
}
}
ifa = ifa->ifa_next;
}
}
freeifaddrs(ifaddr);
}
int waybar::modules::Network::netlinkRequest(int fd, void *req,
uint32_t reqlen, uint32_t groups)
{