【问题标题】:Why does this code works on Xcode simulator, but does not work on device?为什么这段代码可以在 Xcode 模拟器上运行,但不能在设备上运行?
【发布时间】:2012-04-05 07:24:34
【问题描述】:

我真的希望有人向我解释。 我正在编写一个使用它的设备mac地址的应用程序,此代码在模拟器上完美运行,但在设备上不起作用。

我从问题Get router mac (without system call for ARP) in Objective-C得到这个代码

#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

所以我的问题是为什么会发生这种情况,在模拟器和设备上运行有什么区别? 提前谢谢你。

【问题讨论】:

  • 嗨,你有什么解决方案,面临同样的问题。

标签: ios xcode macos kernel bsd


【解决方案1】:

iOS 设备 SDK 中根本没有头文件。无论出于何种原因,Apple 都不希望您使用它。如果你只是想让代码工作,你可以尝试提取所需的定义:

#define IFT_ETHER   0x6     /* Ethernet CSMACD */

并删除行

#include <net/if_types.h>

完全。虽然这破坏了与平台的兼容性,在这些平台上,该常量可能被定义为其他值。

【讨论】:

  • "...虽然这破坏了与平台的兼容性,在这些平台上,该常量可能被定义为其他值" - 好吧,/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.1.sdk 中的 grepping 表明它没有定义在全部。所以他在岩石和坚硬的地方之间。他也可以只遍历可能的值(如 0 到 10),然后等到他得到一个好的响应。一旦他得到了良好的响应,然后检查接口属性以确保媒体是首选的。
猜你喜欢
  • 1970-01-01
  • 2019-03-05
  • 1970-01-01
  • 2018-10-16
  • 1970-01-01
  • 2021-05-16
  • 2020-12-11
  • 2016-02-02
  • 2013-07-12
相关资源
最近更新 更多