Import the System framework:
#import <ifaddrs.h>
#import <arpa/inet.h>
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
Code:
Ip
-(NSString *) getipaddress {
nsstring *address = @ "error";
struct Ifaddrs *interfaces = NULL;
struct Ifaddrs *temp_addr = NULL;
int success = 0;
Retrieve the current Interfaces-returns 0 on success
Success = Getifaddrs (&interfaces);
if (success = = 0) {
Loop through linked list of interfaces
TEMP_ADDR = interfaces;
While (temp_addr! = NULL) {
if (temp_addr->ifa_addr->sa_family = = af_inet) {
Check if interface is En0 which are the WiFi connection on the IPhone
if ([[nsstring stringwithutf8string:temp_addr->ifa_name] isequaltostring:@ "En0"]) {
Get NSString from C String
address = [nsstring stringwithutf8string:inet_ntoa ((struct sockaddr_in *) temp_addr->IFA _ADDR,sin_addr)];
}
}
temp_addr = temp_addr->ifa_next;
}
}
Free memory
Freeifaddrs (interfaces);
return address;
}
Mac
-(NSString *) getmacaddress
{
int mib[6];
size_t Len;
Char *buf;
unsigned char *ptr;
struct if_msghdr *ifm;
struct sockaddr_dl *sdl;
mib[0] = ctl_net;
mib[1] = af_route;
mib[2] = 0;
mib[3] = af_link;
mib[4] = net_rt_iflist;
if ((mib[5] = If_nametoindex ("En0")) = = 0) {
printf("Error:if_nametoindex error/n");
return NULL;
}
if (sysctl (MIB, 6, null, &len, null, 0) < 0) {
printf("Error:sysctl, take 1/n");
return NULL;
}
if ((buf = malloc (len)) = = NULL) {
printf("Could not allocate memory. error!/n ");
return NULL;
}
if (sysctl (MIB, 6, buf, &len, NULL, 0) < 0) {
printf("Error:sysctl, take 2");
return NULL;
}
IFM = (struct if_msghdr *) buf;
SDL = (struct sockaddr_dl *) (IFM + 1);
ptr = (unsigned char *)lladdr (SDL);
nsstring *outstring = [nsstring stringWithFormat:@ "%02x:%02x:%02x:%02x:%02x:%02x", *ptr, * (ptr+1 ), * (ptr+2), * (ptr+3), * (ptr+4), * (ptr+5)];
Free (BUF);
return [outstring uppercasestring];
}
Get MAC Address