Last active
July 18, 2019 09:33
-
-
Save pgp/517b16811e716a7070cae3d537b6f985 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
#include <string> | |
#include <cstring> | |
#include <cstdint> | |
#include <arpa/inet.h> | |
#include <sys/socket.h> | |
#include <ifaddrs.h> | |
#include <netinet/in.h> | |
int main() { | |
struct ifaddrs *ifap, *ifa; | |
struct sockaddr_in *sa,*sb; | |
char *addr; | |
// only IPv4 | |
struct in_addr ips; | |
struct in_addr bas; | |
struct in_addr nms; | |
struct in_addr computed_bas; | |
//~ uint32_t* ips1 = (uint32_t*)(&ips); | |
//~ uint32_t* nms1 = (uint32_t*)(&nms); | |
//~ uint32_t* computed_bas1 = (uint32_t*)(&computed_bas); | |
getifaddrs (&ifap); | |
for (ifa = ifap; ifa; ifa = ifa->ifa_next) { | |
if (ifa->ifa_addr->sa_family==AF_INET) { | |
sa = (struct sockaddr_in *) ifa->ifa_addr; | |
memcpy(&ips,&(sa->sin_addr),sizeof(struct in_addr)); | |
addr = inet_ntoa(sa->sin_addr); | |
std::string ipAddr(addr); | |
// if(ipAddr == "127.0.0.1") continue; | |
memcpy(&computed_bas,&(sa->sin_addr),sizeof(struct in_addr)); // copy ip to bcast_ip, will be updated later | |
sa = (struct sockaddr_in *) ifa->ifa_broadaddr; | |
memcpy(&bas,&(sa->sin_addr),sizeof(struct in_addr)); | |
addr = inet_ntoa(sa->sin_addr); | |
std::string bAddr(addr); | |
sa = (struct sockaddr_in *) ifa->ifa_netmask; | |
memcpy(&nms,&(sa->sin_addr),sizeof(struct in_addr)); | |
addr = inet_ntoa(sa->sin_addr); | |
std::string netmask(addr); | |
// *computed_bas1 = *ips1 | (~(*nms1)); | |
computed_bas.s_addr = ips.s_addr | (~(nms.s_addr)); | |
printf("Memcmp result: %d\n",!memcmp(&computed_bas,&bas,sizeof(struct in_addr))); // BEWARE OF ALIGNMENT!!! | |
printf("Struct member comparison result: %d\n",computed_bas.s_addr == bas.s_addr); | |
addr = inet_ntoa(computed_bas); | |
std::string computed(addr); | |
printf("Interface: %s\nIP address: %s\nBroadcast address: %s\nNetmask: %s\nComputed broadcast address: %s\n\n", ifa->ifa_name, ipAddr.c_str(), bAddr.c_str(), netmask.c_str(), computed.c_str()); | |
} | |
} | |
freeifaddrs(ifap); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment