ios - 为什么这段代码在 Xcode 模拟器上可以运行,但在设备上却不能运行?

标签 ios xcode macos kernel bsd

我真的希望有人向我解释一下。 我正在编写一个使用它的设备 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 设备 SDK 中根本缺少头文件。无论出于何种原因,Apple 都不希望您使用它。如果你只是想让代码工作,你可以尝试提取所需的定义:

#define IFT_ETHER   0x6     /* Ethernet CSMACD */

并删除行

#include <net/if_types.h>

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

关于ios - 为什么这段代码在 Xcode 模拟器上可以运行,但在设备上却不能运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10024266/

相关文章:

ios - 正在使用performSelector :afterDelay: the most efficient way to queue or order methods?

swift - UIAlertView 已弃用且不可用于基于 UIScene 的应用程序,请使用 UIAlertController

ios - 缺少的框架是红色的,项目仍在构建

c++ - Mac C++ GUI 编码 - 与 Win32 的比较

ios - 如何交换 tableviewcell 中的 UIImage

ios - 同步两个数据库源的算法?

ios - 我一直遇到错误实例成员 'object' 不能用于类型 ___

javascript - 在不启动 Xcode 的情况下运行 React Native 应用程序?

macos - 从 Mac 终端编译/运行 Common LIsp

java - 如何在 java 中显示 native 文件系统的文件/文件夹的 "properties window"