-
-
Save finscn/9545465 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <stdlib.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <sys/ioctl.h> | |
#include <arpa/inet.h> | |
#include <net/if.h> | |
void ip_for_interface(const char *interface_name, char *ip, const int length) { | |
*ip = NULL; | |
int sockfd = socket(AF_INET, SOCK_DGRAM, 0); | |
if( sockfd < 0 ) { | |
return; | |
} | |
struct ifconf ifc; | |
ifc.ifc_len = 1024; | |
ifc.ifc_buf = malloc(ifc.ifc_len); | |
if( ioctl(sockfd, SIOCGIFCONF, &ifc ) < 0 ) { | |
free(ifc.ifc_buf); | |
return; | |
} | |
for( char *current = ifc.ifc_buf; current < ifc.ifc_buf + ifc.ifc_len; ) { | |
struct ifreq *request = (struct ifreq *)current; | |
current += sizeof(request->ifr_name) + | |
(sizeof(struct sockaddr) > request->ifr_addr.sa_len | |
? sizeof(struct sockaddr) | |
: request->ifr_addr.sa_len); | |
if( request->ifr_addr.sa_family == AF_INET && strcmp(request->ifr_name, interface_name) == 0 ) { | |
struct sockaddr_in *sin = (struct sockaddr_in *)&request->ifr_addr; | |
strncpy(ip, inet_ntoa(sin->sin_addr), length); | |
break; | |
} | |
} | |
close(sockfd); | |
free(ifc.ifc_buf); | |
} | |
-(NSString *)getIPAddress { | |
char addr[32]; | |
ip_for_interface("en0", addr, 32); // public: "pdp_ip0", local: "lo0" | |
return addr ? [NSString stringWithUTF8String:addr] : @"error"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment