Skip to content

Instantly share code, notes, and snippets.

@shiyuugohirao
Created December 8, 2018 03:14
Show Gist options
  • Save shiyuugohirao/338e4473a6af0242763f5369ae08e2ab to your computer and use it in GitHub Desktop.
Save shiyuugohirao/338e4473a6af0242763f5369ae08e2ab to your computer and use it in GitHub Desktop.
getIP() on Mac
#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