为什么此代码在Xcode模拟器上有效,但在设备上不起作用? [英] Why does this code works on Xcode simulator, but does not work on device?

查看:124
本文介绍了为什么此代码在Xcode模拟器上有效,但在设备上不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很希望有人向我解释它. 我正在编写一个使用它的设备MAC地址的应用程序,该代码可以完美地在模拟器上运行,但不能在设备上运行.

I'm really hoping, that someone explains it to me. I'm writing an app that uses it's device mac address, and this code perfectly works on the simulator, but does not work on a device.

我是从问题在Objective-C中获取路由器mac(不使用ARP的系统调用)获得此代码的

#include <stdio.h>

#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <net/if_dl.h>
#include <ifaddrs.h>
#include <net/if_types.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) 
       {
           const struct sockaddr_dl *socAddr = 
           (const struct sockaddr_dl *)cursor->ifa_addr;
           _Bool afLinkFamily = (cursor->ifa_addr->sa_family == AF_LINK);
           /* Ethernet CSMA/CD */
           _Bool sdlIFTEther = (socAddr->sdl_type == IFT_ETHER);

           if ((afLinkFamily) && 
                sdlIFTEther &&
                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;
}

它给了我一个错误:

'net/if_types.h' file not found

所以我的问题是为什么会这样,在模拟器和设备上运行有什么区别? 预先谢谢你.

so my question is why is this happening, what is the difference between running on simulator and device? Thank you in advance.

推荐答案

iOS设备SDK中仅缺少头文件.无论出于何种原因,Apple都不希望您使用它.如果您只是想让代码正常工作,则可以尝试提取所需的定义:

The header file is simply missing in the iOS device SDK. Apple doesn't want you to use it, for whatever reason. If you just want the code to work, you can try to extract the required definition:

#define IFT_ETHER   0x6     /* Ethernet CSMACD */

并删除行

#include <net/if_types.h>

完全.尽管这破坏了与该常量可以定义为其他值的平台的兼容性.

completely. Although this breaks the compatibility with platforms where this constant may be defined to some other value.

这篇关于为什么此代码在Xcode模拟器上有效,但在设备上不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆