Created
December 8, 2018 03:14
-
-
Save shiyuugohirao/338e4473a6af0242763f5369ae08e2ab to your computer and use it in GitHub Desktop.
getIP() on Mac
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 <sys/ioctl.h> | |
#include <netinet/in.h> | |
#include <net/if.h> | |
#include <arpa/inet.h> | |
static string getIP(){ | |
int fd; | |
struct ifreq ifr; | |
fd = socket(AF_INET, SOCK_DGRAM, 0); | |
ifr.ifr_addr.sa_family = AF_INET; | |
strncpy(ifr.ifr_name, "en0", IFNAMSIZ-1); | |
ioctl(fd, SIOCGIFADDR, &ifr); | |
close(fd); | |
string ipAddress = inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr); | |
//[*] check good ipAddress | |
int pos = ipAddress.find_last_of("."); | |
string last = ipAddress.substr(pos+1); | |
if ((pos==string::npos )|| (last == "0")) ipAddress = ""; | |
return ipAddress; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment