0

我正在 Linux 上开发一个应用程序。Linux 执行命令:

ifconfig eth0 192.168.10.15 netmask 255.255.255.0

在使用 systemd 的引导过程中。

当我尝试在结果下方使用 ifconfig 了解我的 IP 地址时:

eth0      Link encap:Ethernet  HWaddr 00:18:31:E0:44:C6  
          inet addr:192.168.10.15  Bcast:192.168.10.255  Mask:255.255.255.0
          inet6 addr: fe80::218:31ff:fee0:44c6/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:24799 errors:0 dropped:1 overruns:0 frame:0
          TX packets:13753 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:5475289 (5.2 MiB)  TX bytes:1403459 (1.3 MiB)

另一方面,当我尝试通过下面的程序了解我的 IP 地址时,我得到 192.168.10.42。

void GetMyIp(char caIP[INET_ADDRSTRLEN])
{
  int s;
  struct ifconf ifconf;
  struct ifreq ifr[50];
  int ifs;
  int i;    

  s = socket(AF_INET, SOCK_STREAM, 0);
  if (s < 0) 
  {
      #ifdef _DEBUG_PROCESS
        if(EDebugProcess<GetDebugLevelOfPMC())
        {
        PrintToLogFile("Socket error\n");
        }
      #endif
  }

  ifconf.ifc_buf = (char *) ifr;
  ifconf.ifc_len = sizeof ifr;

  if (ioctl(s, SIOCGIFCONF, &ifconf) == -1) 
  {
    #ifdef _DEBUG_PROCESS
        if(EDebugProcess<GetDebugLevelOfPMC())
        {
        PrintToLogFile("ioctl error\n");
        }
      #endif
  }

  ifs = ifconf.ifc_len / sizeof(ifr[0]);
    struct sockaddr_in *s_in = (struct sockaddr_in *) &ifr[ifs-1].ifr_addr;
    if (!inet_ntop(AF_INET, &s_in->sin_addr, gcaMyIP, sizeof(gcaMyIP))) 
    {
    #ifdef _DEBUG_PROCESS
        if(EDebugProcess<GetDebugLevelOfPMC())
        {
        PrintToLogFile("inet_ntop error\n");
        }
    #endif
    }


    close(s);
    memcpy(caIP,gcaMyIP,INET_ADDRSTRLEN);
}

差异的根源是什么?

4

1 回答 1

0

如果你愿意,你可以试试:

http://www.binarytides.com/get-local-ip-in-c-on-linux/

于 2012-09-14T19:51:54.147 回答