Trying to find USB device on iphone with IOKit.framework - iphone

I'm working on a project were I need the USB port to communicate with an external device. I have been looking for examples on the net (Apple and /developer/IOKit/usb exemple) and trying some others, but I can't even find the device.
In my code, I'm blocking at the place where the function looks for a next iterator (pointer in fact) with the function getNextIterator; but it never returns a good value, so the code is blocking. By the way, I am using toolchain and added IOKit.framework in my project. All I want right now is to communicate or do like a ping to someone on the USB bus! I'm blocking in FindDevice... I can't manage to enter in the while loop because the variable usbDevice is always = to 0... I have tested my code in a small mac program and it works...
Here is my code :
IOReturn ConfigureDevice(IOUSBDeviceInterface **dev) {
UInt8 numConfig;
IOReturn result;
IOUSBConfigurationDescriptorPtr configDesc;
//Get the number of configurations
result = (*dev)->GetNumberOfConfigurations(dev, &numConfig);
if (!numConfig) {
return -1;
}
// Get the configuration descriptor
result = (*dev)->GetConfigurationDescriptorPtr(dev, 0, &configDesc);
if (result) {
NSLog(#"Couldn't get configuration descriptior for index %d (err=%08x)\n", 0, result);
return -1;
}
#ifdef OSX_DEBUG
NSLog(#"Number of Configurations: %d\n", numConfig);
#endif
// Configure the device
result = (*dev)->SetConfiguration(dev, configDesc->bConfigurationValue);
if (result)
{
NSLog(#"Unable to set configuration to value %d (err=%08x)\n", 0, result);
return -1;
}
return kIOReturnSuccess;
}
IOReturn FindInterfaces(IOUSBDeviceInterface **dev, IOUSBInterfaceInterface ***itf) {
IOReturn kr;
IOUSBFindInterfaceRequest request;
io_iterator_t iterator;
io_service_t usbInterface;
IOUSBInterfaceInterface **intf = NULL;
IOCFPlugInInterface **plugInInterface = NULL;
HRESULT res;
SInt32 score;
UInt8 intfClass;
UInt8 intfSubClass;
UInt8 intfNumEndpoints;
int pipeRef;
CFRunLoopSourceRef runLoopSource;
NSLog(#"Debut FindInterfaces \n");
request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
kr = (*dev)->CreateInterfaceIterator(dev, &request, &iterator);
usbInterface = IOIteratorNext(iterator);
IOObjectRelease(iterator);
NSLog(#"Interface found.\n");
kr = IOCreatePlugInInterfaceForService(usbInterface, kIOUSBInterfaceUserClientTypeID, kIOCFPlugInInterfaceID, &plugInInterface, &score);
kr = IOObjectRelease(usbInterface); // done with the usbInterface object now that I have the plugin
if ((kIOReturnSuccess != kr) || !plugInInterface)
{
NSLog(#"unable to create a plugin (%08x)\n", kr);
return -1;
}
// I have the interface plugin. I need the interface interface
res = (*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID), (LPVOID*) &intf);
(*plugInInterface)->Release(plugInInterface); // done with this
if (res || !intf)
{
NSLog(#"couldn't create an IOUSBInterfaceInterface (%08x)\n", (int) res);
return -1;
}
// Now open the interface. This will cause the pipes to be instantiated that are
// associated with the endpoints defined in the interface descriptor.
kr = (*intf)->USBInterfaceOpen(intf);
if (kIOReturnSuccess != kr)
{
NSLog(#"unable to open interface (%08x)\n", kr);
(void) (*intf)->Release(intf);
return -1;
}
kr = (*intf)->CreateInterfaceAsyncEventSource(intf, &runLoopSource);
if (kIOReturnSuccess != kr)
{
NSLog(#"unable to create async event source (%08x)\n", kr);
(void) (*intf)->USBInterfaceClose(intf);
(void) (*intf)->Release(intf);
return -1;
}
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode);
if (!intf)
{
NSLog(#"Interface is NULL!\n");
} else
{
*itf = intf;
}
NSLog(#"End of FindInterface \n \n");
return kr;
}
unsigned int FindDevice(void *refCon, io_iterator_t iterator) {
kern_return_t kr;
io_service_t usbDevice;
IOCFPlugInInterface **plugInInterface = NULL;
HRESULT result;
SInt32 score;
UInt16 vendor;
UInt16 product;
UInt16 release;
unsigned int count = 0;
NSLog(#"Searching Device....\n");
while (usbDevice = IOIteratorNext(iterator))
{
// create intermediate plug-in
NSLog(#"Found a device!\n");
kr = IOCreatePlugInInterfaceForService(usbDevice,
kIOUSBDeviceUserClientTypeID,
kIOCFPlugInInterfaceID,
&plugInInterface, &score);
kr = IOObjectRelease(usbDevice);
if ((kIOReturnSuccess != kr) || !plugInInterface) {
NSLog(#"Unable to create a plug-in (%08x)\n", kr);
continue;
}
// Now create the device interface
result = (*plugInInterface)->QueryInterface(plugInInterface,
CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID),
(LPVOID)&dev);
// Don't need intermediate Plug-In Interface
(*plugInInterface)->Release(plugInInterface);
if (result || !dev) {
NSLog(#"Couldn't create a device interface (%08x)\n",
(int)result);
continue;
}
// check these values for confirmation
kr = (*dev)->GetDeviceVendor(dev, &vendor);
kr = (*dev)->GetDeviceProduct(dev, &product);
//kr = (*dev)->GetDeviceReleaseNumber(dev, &release);
//if ((vendor != LegoUSBVendorID) || (product != LegoUSBProductID) || (release != LegoUSBRelease)) {
if ((vendor != LegoUSBVendorID) || (product != LegoUSBProductID))
{
NSLog(#"Found unwanted device (vendor = %d != %d, product = %d != %d, release = %d)\n",
vendor, kUSBVendorID, product, LegoUSBProductID, release);
(void) (*dev)->Release(dev);
continue;
}
// Open the device to change its state
kr = (*dev)->USBDeviceOpen(dev);
if (kr == kIOReturnSuccess) {
count++;
} else {
NSLog(#"Unable to open device: %08x\n", kr);
(void) (*dev)->Release(dev);
continue;
}
// Configure device
kr = ConfigureDevice(dev);
if (kr != kIOReturnSuccess) {
NSLog(#"Unable to configure device: %08x\n", kr);
(void) (*dev)->USBDeviceClose(dev);
(void) (*dev)->Release(dev);
continue;
}
break;
}
return count;
}
// USB rcx Init
IOUSBInterfaceInterface** osx_usb_rcx_init (void)
{
CFMutableDictionaryRef matchingDict;
kern_return_t result;
IOUSBInterfaceInterface **intf = NULL;
unsigned int device_count = 0;
// Create master handler
result = IOMasterPort(MACH_PORT_NULL, &gMasterPort);
if (result || !gMasterPort)
{
NSLog(#"ERR: Couldn't create master I/O Kit port(%08x)\n", result);
return NULL;
}
else {
NSLog(#"Created Master Port.\n");
NSLog(#"Master port 0x:08X \n \n", gMasterPort);
}
// Set up the matching dictionary for class IOUSBDevice and its subclasses
matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
if (!matchingDict) {
NSLog(#"Couldn't create a USB matching dictionary \n");
mach_port_deallocate(mach_task_self(), gMasterPort);
return NULL;
}
else {
NSLog(#"USB matching dictionary : %08X \n", matchingDict);
}
CFDictionarySetValue(matchingDict, CFSTR(kUSBVendorID),
CFNumberCreate(kCFAllocatorDefault, kCFNumberShortType, &LegoUSBVendorID));
CFDictionarySetValue(matchingDict, CFSTR(kUSBProductID),
CFNumberCreate(kCFAllocatorDefault, kCFNumberShortType, &LegoUSBProductID));
result = IOServiceGetMatchingServices(gMasterPort, matchingDict, &gRawAddedIter);
matchingDict = 0; // this was consumed by the above call
// Iterate over matching devices to access already present devices
NSLog(#"RawAddedIter : 0x:%08X \n", &gRawAddedIter);
device_count = FindDevice(NULL, gRawAddedIter);
if (device_count == 1)
{
result = FindInterfaces(dev, &intf);
if (kIOReturnSuccess != result)
{
NSLog(#"unable to find interfaces on device: %08x\n", result);
(*dev)->USBDeviceClose(dev);
(*dev)->Release(dev);
return NULL;
}
// osx_usb_rcx_wakeup(intf);
return intf;
}
else if (device_count > 1)
{
NSLog(#"too many matching devices (%d) !\n", device_count);
}
else
{
NSLog(#"no matching devices found\n");
}
return NULL;
}
int main(int argc, char *argv[])
{
int returnCode;
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSLog(#"Debut du programme \n \n");
osx_usb_rcx_init();
NSLog(#"Fin du programme \n \n");
return 0;
// returnCode = UIApplicationMain(argc, argv, #"Untitled1App", #"Untitled1App");
// [pool release];
// return returnCode;
}

IOKit is not available for iPhone applications. If you need to connect with external devices from the iPhone you need to sign up for the MFi Program which will provide you with the needed API's and documentation.

besides the appstore rules i dont think u can even touch iokit on iOS without violating the sdk's agreement.

Related

How to display a PBFrame in iOS

I am currently working on an app which uses a live stream from an IP camera(PnP IP/Network camera manufactured by V Star). When connected using the Api provided I get the frame o/p as PBFrames. I am having trouble displaying them. anybody who have been through it please help. Thanks in advance
void *thread_ReceiveVideo(void *arg)
{
NSLog(#"[thread_ReceiveVideo] Starting...");
int avIndex = *(int *)arg;
char *buf = malloc(VIDEO_BUF_SIZE);
unsigned int frmNo;
int ret;
FRAMEINFO_t frameInfo;
while (1)
{
ret = avRecvFrameData(avIndex, buf, VIDEO_BUF_SIZE, (char *)&frameInfo, sizeof(FRAMEINFO_t), &frmNo);
if(ret == AV_ER_DATA_NOREADY)
{
usleep(30000);
continue;
}
else if(ret == AV_ER_LOSED_THIS_FRAME)
{
NSLog(#"Lost video frame NO[%d]", frmNo);
continue;
}
else if(ret == AV_ER_INCOMPLETE_FRAME)
{
NSLog(#"Incomplete video frame NO[%d]", frmNo);
NSLog(#" the biffer is : %lu",sizeof(buf));
continue;
}
else if(ret == AV_ER_SESSION_CLOSE_BY_REMOTE)
{
NSLog(#"[thread_ReceiveVideo] AV_ER_SESSION_CLOSE_BY_REMOTE");
break;
}
else if(ret == AV_ER_REMOTE_TIMEOUT_DISCONNECT)
{
NSLog(#"[thread_ReceiveVideo] AV_ER_REMOTE_TIMEOUT_DISCONNECT");
break;
}
else if(ret == IOTC_ER_INVALID_SID)
{
NSLog(#"[thread_ReceiveVideo] Session cant be used anymore");
break;
}
NSLog(#"FRAM INFO FLAG :%hhu ",frameInfo.flags);
if(frameInfo.flags == IPC_FRAME_FLAG_PBFRAME)
{
// got an PBFrame, draw it.
NSLog(#"got a video iframe to display");
// NSString *iFramestring = [NSString stringWithUTF8String:buf];
printf("correclty recieved frame is %s",buf);
//
}
}
free(buf);
NSLog(#"[thread_ReceiveVideo] thread exit");
return 0;
}

ZLib in iPhone unable to decompress data

I am trying to decompress data using the ZLib in iPhone, but it always through error of "Invalid header Check".
To compress the data I am using the following in Java
Implementation: Standard Java implementation for Zlib
Deflator : java.util.zip.Deflater
version 1.45, 04/07/06
Compression level: BEST_COMPRESSION
In iPhone the following is the code for decompressing:
- (NSData *)zlibInflate
{
if ([self length] == 0) return self;
unsigned full_length = [self length];
unsigned half_length = [self length] / 2;
NSMutableData *decompressed = [NSMutableData dataWithLength: full_length + half_length];
BOOL done = NO;
int status;
z_stream strm;
strm.next_in = (Bytef *)[self bytes];
strm.avail_in = [self length];
strm.total_out = 0;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
if (inflateInit (&strm) != Z_OK) return nil;
while (!done)
{
// Make sure we have enough room and reset the lengths.
if (strm.total_out >= [decompressed length])
[decompressed increaseLengthBy: half_length];
strm.next_out = [decompressed mutableBytes] + strm.total_out;
strm.avail_out = [decompressed length] - strm.total_out;
// Inflate another chunk.
status = inflate (&strm, Z_SYNC_FLUSH);
if (status == Z_STREAM_END) done = YES;
else if (status != Z_OK) {
NSLog(#"%s", strm.msg);
break;
}
}
if (inflateEnd (&strm) != Z_OK) return nil;
// Set real length.
if (done)
{
[decompressed setLength: strm.total_out];
return [NSData dataWithData: decompressed];
}
else return nil;
}
Following is a sample compressed string:
xÚÝUko²Jþ~?­ó?¥¾?¤?©?´ÚjCMX,Òµ?ª?µßVX¹È­?¿.øë_?¯¶ZÏ%íùxHH&Ã<ÏÌ3ÌÎ
#2.ðE?ºqþpéEzÏ09IoÒ?ª? ?®?£àÌönì$brÛ#fl95?¿»a//Tçáò?¢?¿½
µ©ÊÃÉPÔ¼:8y¦ý.äÎ?µ?¥?¼y?©ã¯9ö?¥½?¢±ÝûwÛ?§ãga?©á8?¨?­m\Õ?»6,'Îe?¬}(L}7ÆÅ6#gJ(¥7´s?¬d.ó,Ë°¦prßýÕÖ? 
Below is the function for compresser:
public static byte[] compress(String s) {
Deflater comp = new Deflater();
//comp.setLevel(Deflater.BEST_COMPRESSION);
comp.setInput(s.getBytes());
comp.finish();
ByteArrayOutputStream bos = new ByteArrayOutputStream(s.length());
// Compress the data
byte[] buf = new byte[1024];
try {
while (!comp.finished()) {
int count = comp.deflate(buf);
bos.write(buf, 0, count);
}
bos.close();
} catch (Exception e) {
//Log.d(TAG, e.getMessage());
e.printStackTrace();
}
// Get the compressed data
byte[] compressedData = bos.toByteArray();
// put in this fix for Symbol scanners
byte[] compressedDataForSymbol = mungeForSymbol(compressedData);
/*
* byte[] decompressedDataForSymbol =
* decompressedDataAfterSymbol(compressedDataForSymbol); // check they
* are the same for(int i=0;i<compressedData.length;i++) { if
* (compressedData[i] != decompressedDataForSymbol[i]) {
* //System.out.println("Error at " + i); } }
*/
return compressedDataForSymbol;
// return s.getBytes();
}
Using Java Deflater with default compression level creates output encoded data with header with first two bytes 0x78 0x9c. These are not used in IOS. Just remove the first two bytes and try the Inflate ie decompression in IOS. It should work.
I had faced the same issue, But i wanted data from IOS(compressed) to android(decompressed).

How to retrieve the WiFi Mac address of a device -- IOS [duplicate]

How to programmatically get an iPhone's MAC address and IP address?
NOTE As of iOS7, you can no longer retrieve device MAC addresses. A fixed value will be returned rather than the actual MAC
Somthing I stumbled across a while ago. Originally from here I modified it a bit and cleaned things up.
IPAddress.h
IPAddress.c
And to use it
InitAddresses();
GetIPAddresses();
GetHWAddresses();
int i;
NSString *deviceIP = nil;
for (i=0; i<MAXADDRS; ++i)
{
static unsigned long localHost = 0x7F000001; // 127.0.0.1
unsigned long theAddr;
theAddr = ip_addrs[i];
if (theAddr == 0) break;
if (theAddr == localHost) continue;
NSLog(#"Name: %s MAC: %s IP: %s\n", if_names[i], hw_addrs[i], ip_names[i]);
//decided what adapter you want details for
if (strncmp(if_names[i], "en", 2) == 0)
{
NSLog(#"Adapter en has a IP of %s", ip_names[i]);
}
}
Adapter names vary depending on the simulator/device as well as wifi or cell on the device.
Update: this will not work on iOS 7. You should use ASIdentifierManager.
More clean solution on MobileDeveloperTips website:
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
...
- (NSString *)getMacAddress
{
int mgmtInfoBase[6];
char *msgBuffer = NULL;
size_t length;
unsigned char macAddress[6];
struct if_msghdr *interfaceMsgStruct;
struct sockaddr_dl *socketStruct;
NSString *errorFlag = NULL;
// Setup the management Information Base (mib)
mgmtInfoBase[0] = CTL_NET; // Request network subsystem
mgmtInfoBase[1] = AF_ROUTE; // Routing table info
mgmtInfoBase[2] = 0;
mgmtInfoBase[3] = AF_LINK; // Request link layer information
mgmtInfoBase[4] = NET_RT_IFLIST; // Request all configured interfaces
// With all configured interfaces requested, get handle index
if ((mgmtInfoBase[5] = if_nametoindex("en0")) == 0)
errorFlag = #"if_nametoindex failure";
else
{
// Get the size of the data available (store in len)
if (sysctl(mgmtInfoBase, 6, NULL, &length, NULL, 0) < 0)
errorFlag = #"sysctl mgmtInfoBase failure";
else
{
// Alloc memory based on above call
if ((msgBuffer = malloc(length)) == NULL)
errorFlag = #"buffer allocation failure";
else
{
// Get system information, store in buffer
if (sysctl(mgmtInfoBase, 6, msgBuffer, &length, NULL, 0) < 0)
errorFlag = #"sysctl msgBuffer failure";
}
}
}
// Befor going any further...
if (errorFlag != NULL)
{
NSLog(#"Error: %#", errorFlag);
return errorFlag;
}
// Map msgbuffer to interface message structure
interfaceMsgStruct = (struct if_msghdr *) msgBuffer;
// Map to link-level socket structure
socketStruct = (struct sockaddr_dl *) (interfaceMsgStruct + 1);
// Copy link layer address data in socket structure to an array
memcpy(&macAddress, socketStruct->sdl_data + socketStruct->sdl_nlen, 6);
// Read from char array into a string object, into traditional Mac address format
NSString *macAddressString = [NSString stringWithFormat:#"%02X:%02X:%02X:%02X:%02X:%02X",
macAddress[0], macAddress[1], macAddress[2],
macAddress[3], macAddress[4], macAddress[5]];
NSLog(#"Mac Address: %#", macAddressString);
// Release the buffer memory
free(msgBuffer);
return macAddressString;
}
I wanted something to return the address regardless of whether or not wifi was enabled, so the chosen solution didn't work for me. I used another call I found on some forum after some tweaking. I ended up with the following (excuse my rusty C ) :
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <net/if_dl.h>
#include <ifaddrs.h>
char* getMacAddress(char* macAddress, char* ifName) {
int success;
struct ifaddrs * addrs;
struct ifaddrs * cursor;
const struct sockaddr_dl * dlAddr;
const unsigned char* base;
int i;
success = getifaddrs(&addrs) == 0;
if (success) {
cursor = addrs;
while (cursor != 0) {
if ( (cursor->ifa_addr->sa_family == AF_LINK)
&& (((const struct sockaddr_dl *) cursor->ifa_addr)->sdl_type == IFT_ETHER) && strcmp(ifName, cursor->ifa_name)==0 ) {
dlAddr = (const struct sockaddr_dl *) cursor->ifa_addr;
base = (const unsigned char*) &dlAddr->sdl_data[dlAddr->sdl_nlen];
strcpy(macAddress, "");
for (i = 0; i < dlAddr->sdl_alen; i++) {
if (i != 0) {
strcat(macAddress, ":");
}
char partialAddr[3];
sprintf(partialAddr, "%02X", base[i]);
strcat(macAddress, partialAddr);
}
}
cursor = cursor->ifa_next;
}
freeifaddrs(addrs);
}
return macAddress;
}
And then I would call it asking for en0, as follows:
char* macAddressString= (char*)malloc(18);
NSString* macAddress= [[NSString alloc] initWithCString:getMacAddress(macAddressString, "en0")
encoding:NSMacOSRomanStringEncoding];
free(macAddressString);
Starting from iOS 7, the system always returns the value 02:00:00:00:00:00 when you ask for the MAC address on any device.
In iOS 7 and later, if you ask for the MAC address of an iOS device, the system returns the value 02:00:00:00:00:00. If you need to identify the device, use the identifierForVendor property of UIDevice instead. (Apps that need an identifier for their own advertising purposes should consider using the advertisingIdentifier property of ASIdentifierManager instead.)"
Reference: releasenotes
There are vary solutions about this, but I couldn't find a whole thing.
So I made my own solution for :
nicinfo
How to use :
NICInfoSummary* summary = [[[NICInfoSummary alloc] init] autorelease];
// en0 is for WiFi
NICInfo* wifi_info = [summary findNICInfo:#"en0"];
// you can get mac address in 'XX-XX-XX-XX-XX-XX' form
NSString* mac_address = [wifi_info getMacAddressWithSeparator:#"-"];
// ip can be multiple
if(wifi_info.nicIPInfos.count > 0)
{
NICIPInfo* ip_info = [wifi_info.nicIPInfos objectAtIndex:0];
NSString* ip = ip_info.ip;
NSString* netmask = ip_info.netmask;
NSString* broadcast_ip = ip_info.broadcastIP;
}
else
{
NSLog(#"WiFi not connected!");
}
This looks like a pretty clean solution: UIDevice BIdentifier
// Return the local MAC addy
// Courtesy of FreeBSD hackers email list
// Accidentally munged during previous update. Fixed thanks to erica sadun & mlamb.
- (NSString *) macaddress{
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");
free(buf);
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;
}
Now iOS 7 devices – are always returning a MAC address of 02:00:00:00:00:00.
So better use [UIDevice identifierForVendor].
so better to call this method to get app specific unique key
Category will more suitable
import "UIDevice+Identifier.h"
- (NSString *) identifierForVendor1
{
if ([[UIDevice currentDevice] respondsToSelector:#selector(identifierForVendor)]) {
return [[[UIDevice currentDevice] identifierForVendor] UUIDString];
}
return #"";
}
Now call above method to get unique address
NSString *like_UDID=[NSString stringWithFormat:#"%#",
[[UIDevice currentDevice] identifierForVendor1]];
NSLog(#"%#",like_UDID);
#Grantland
This "pretty clean solution" looks similar to my own improvement over iPhoneDeveloperTips solution.
You can see my step here:
https://gist.github.com/1409855/
/* Original source code courtesy John from iOSDeveloperTips.com */
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
+ (NSString *)getMacAddress
{
int mgmtInfoBase[6];
char *msgBuffer = NULL;
NSString *errorFlag = NULL;
size_t length;
// Setup the management Information Base (mib)
mgmtInfoBase[0] = CTL_NET; // Request network subsystem
mgmtInfoBase[1] = AF_ROUTE; // Routing table info
mgmtInfoBase[2] = 0;
mgmtInfoBase[3] = AF_LINK; // Request link layer information
mgmtInfoBase[4] = NET_RT_IFLIST; // Request all configured interfaces
// With all configured interfaces requested, get handle index
if ((mgmtInfoBase[5] = if_nametoindex("en0")) == 0)
errorFlag = #"if_nametoindex failure";
// Get the size of the data available (store in len)
else if (sysctl(mgmtInfoBase, 6, NULL, &length, NULL, 0) < 0)
errorFlag = #"sysctl mgmtInfoBase failure";
// Alloc memory based on above call
else if ((msgBuffer = malloc(length)) == NULL)
errorFlag = #"buffer allocation failure";
// Get system information, store in buffer
else if (sysctl(mgmtInfoBase, 6, msgBuffer, &length, NULL, 0) < 0)
{
free(msgBuffer);
errorFlag = #"sysctl msgBuffer failure";
}
else
{
// Map msgbuffer to interface message structure
struct if_msghdr *interfaceMsgStruct = (struct if_msghdr *) msgBuffer;
// Map to link-level socket structure
struct sockaddr_dl *socketStruct = (struct sockaddr_dl *) (interfaceMsgStruct + 1);
// Copy link layer address data in socket structure to an array
unsigned char macAddress[6];
memcpy(&macAddress, socketStruct->sdl_data + socketStruct->sdl_nlen, 6);
// Read from char array into a string object, into traditional Mac address format
NSString *macAddressString = [NSString stringWithFormat:#"%02X:%02X:%02X:%02X:%02X:%02X",
macAddress[0], macAddress[1], macAddress[2], macAddress[3], macAddress[4], macAddress[5]];
NSLog(#"Mac Address: %#", macAddressString);
// Release the buffer memory
free(msgBuffer);
return macAddressString;
}
// Error...
NSLog(#"Error: %#", errorFlag);
return nil;
}
It's not possible anymore on devices running iOS 7.0 or later, thus unavailable to get MAC address in Swift.
As Apple stated:
In iOS 7 and later, if you ask for the MAC address of an iOS device, the system returns the value 02:00:00:00:00:00. If you need to identify the device, use the identifierForVendor property of UIDevice instead. (Apps that need an identifier for their own advertising purposes should consider using the advertisingIdentifier property of ASIdentifierManager instead.)
#import <sys/socket.h>
#import <net/if_dl.h>
#import <ifaddrs.h>
#import <sys/xattr.h>
#define IFT_ETHER 0x6
...
- (NSString*)macAddress
{
NSString* result = nil;
char* macAddressString = (char*)malloc(18);
if (macAddressString != NULL)
{
strcpy(macAddressString, "");
struct ifaddrs* addrs = NULL;
struct ifaddrs* cursor;
if (getifaddrs(&addrs) == 0)
{
cursor = addrs;
while (cursor != NULL)
{
if ((cursor->ifa_addr->sa_family == AF_LINK) && (((const struct sockaddr_dl*)cursor->ifa_addr)->sdl_type == IFT_ETHER) && strcmp("en0", cursor->ifa_name) == 0)
{
const struct sockaddr_dl* dlAddr = (const struct sockaddr_dl*) cursor->ifa_addr;
const unsigned char* base = (const unsigned char*)&dlAddr->sdl_data[dlAddr->sdl_nlen];
for (NSInteger index = 0; index < dlAddr->sdl_alen; index++)
{
char partialAddr[3];
sprintf(partialAddr, "%02X", base[index]);
strcat(macAddressString, partialAddr);
}
}
cursor = cursor->ifa_next;
}
}
result = [[[NSString alloc] initWithUTF8String:macAddressString] autorelease];
free(macAddressString);
}
return result;
}
To create a uniqueString based on unique identifier of device in iOS 6:
#import <AdSupport/ASIdentifierManager.h>
NSString *uniqueString = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
NSLog(#"uniqueString: %#", uniqueString);
A lot of these questions only address the Mac address. If you also require the IP address I just wrote this, may need some work but seems to work well on my machine...
- (NSString *)getLocalIPAddress
{
NSArray *ipAddresses = [[NSHost currentHost] addresses];
NSArray *sortedIPAddresses = [ipAddresses sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
numberFormatter.allowsFloats = NO;
for (NSString *potentialIPAddress in sortedIPAddresses)
{
if ([potentialIPAddress isEqualToString:#"127.0.0.1"]) {
continue;
}
NSArray *ipParts = [potentialIPAddress componentsSeparatedByString:#"."];
BOOL isMatch = YES;
for (NSString *ipPart in ipParts) {
if (![numberFormatter numberFromString:ipPart]) {
isMatch = NO;
break;
}
}
if (isMatch) {
return potentialIPAddress;
}
}
// No IP found
return #"?.?.?.?";
}

Get Wifi Address Problem

I try to get ip address using asyncsocket framework. When do it via ethernet cable the following method works good.
But when try to get ip address using wifi access point it returns nil.
Here is a method:
- (NSData *)wifiAddress
{
// On iPhone, WiFi is always "en0"
NSData *result = nil;
struct ifaddrs *addrs;
const struct ifaddrs *cursor;
if ((getifaddrs(&addrs) == 0))
{
cursor = addrs;
while (cursor != NULL)
{
NSLog(#"cursor->ifa_name = %s", cursor->ifa_name);
if (strcmp(cursor->ifa_name, "en0") == 0)
{
if (cursor->ifa_addr->sa_family == AF_INET)
{
struct sockaddr_in *addr = (struct sockaddr_in *)cursor->ifa_addr;
NSLog(#"cursor->ifa_addr = %s", inet_ntoa(addr->sin_addr));
result = [NSData dataWithBytes:addr length:sizeof(struct sockaddr_in)];
cursor = NULL;
}
else
{
cursor = cursor->ifa_next;
}
}
else
{
cursor = cursor->ifa_next;
}
}
freeifaddrs(addrs);
}
return result;
}
The issue we had was that an exact match on en0 would not always return the wifi address. We have something similar to the following. Hope this helps.
NSString* wifiIp = [NetUtils getLocalAddress:#"en"];
+ (NSString *) getLocalAddress:(NSString*) interface
{
NSString *address = nil;
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
success = getifaddrs(&interfaces);
if (success == 0)
{
temp_addr = interfaces;
while(temp_addr != NULL)
{
if(temp_addr->ifa_addr->sa_family == AF_INET)
{
NSRange range = [[NSString stringWithUTF8String:temp_addr->ifa_name] rangeOfString : interface];
if(range.location != NSNotFound)
{
address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
}
}
temp_addr = temp_addr->ifa_next;
}
}
freeifaddrs(interfaces);
return address;
}

Async CFStream networking with runloop

I am trying to implement async tcp networking with runloop.
currently I manage to connect, but when I try to send something I get that -1 bytes have been written - but CFWriteStreamCopyError returns null.
code sample below, first function connects, second send a simple message.
any help will be appreciated, including random bug spotting (I am new to objective-c and to iphone development in general).
struct header
{
uint32_t length;
uint32_t type;
} header;
- (void) connect
{
NSLog(#"Attempting to (re)connect to %#:%d", m_host, m_port);
while(TRUE)
{
CFHostRef host = CFHostCreateWithName(kCFAllocatorDefault, (CFStringRef)m_host);
if (!host)
{
NSLog(#"Error resolving host %#", m_host);
[NSThread sleepForTimeInterval:5.0];
continue;
}
CFStreamCreatePairWithSocketToCFHost(kCFAllocatorDefault, host , m_port, &m_in, &m_out);
CFRelease(host);
if (!m_in)
{
NSLog(#"Error");
}
CFStreamClientContext context = {0, self,nil,nil,nil};
if (CFReadStreamSetClient(m_in, kCFStreamEventHasBytesAvailable | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered, networkReadEvent, &context))
{
CFReadStreamScheduleWithRunLoop(m_in, CFRunLoopGetCurrent(),kCFRunLoopCommonModes);
}
if (CFWriteStreamSetClient(m_out, kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered, networkWriteEvent, &context))
{
CFWriteStreamScheduleWithRunLoop(m_out, CFRunLoopGetCurrent(),kCFRunLoopCommonModes);
}
BOOL success = CFReadStreamOpen(m_in);
CFErrorRef error = CFReadStreamCopyError(m_in);
if (!success || (error && CFErrorGetCode(error) != 0))
{
NSLog(#"Connect error %s : %d", CFErrorGetDomain(error), CFErrorGetCode(error));
[NSThread sleepForTimeInterval:5.0];
}
else
{
NSLog(#"Connected");
break;
}
}
[self startSession];
}
- (void) startSession
{
struct header hh;
hh.type = RTR_CREATE_SESSION;
hh.length = 0;
CFIndex res = CFWriteStreamWrite(self.m_out, (const UInt8*)&hh, sizeof(hh));
NSLog(#"Written %d", res);
CFErrorRef error = CFWriteStreamCopyError(self.m_out);
if (error)
{
NSLog(#"Read error %s : %d", CFErrorGetDomain(error), CFErrorGetCode(error));
CFRelease(error);
}
}
figured it out, I forgot to open the write stream as well:
CFWriteStreamOpen(m_out);