c - ifconfig 和套接字 inet_ntop 的不同 IP 结果

标签 c linux bash sockets tcp

我正在 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);
}

差异的根源是什么?

最佳答案

如果你愿意,你可以尝试一下:

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

关于c - ifconfig 和套接字 inet_ntop 的不同 IP 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12423952/

相关文章:

python - 在其他功能中使用相机时从网络摄像头拍摄快照

c - 在 C 中为 shell 脚本使用变量

bash:如果 grep 管道选择任何行则退出

c++ - MSVC 中的 "interface"关键字是什么?

c - 我需要将分散-聚集 DMA 链表放入不可缓存的内存中吗?

linux - 我需要读取一个名称文件并在之后处理它,比如找出他的 inode 号和其他东西

bash - 函数可以用在 $(( func arg ? str1 : str2 ))?

c - 为什么sigprocmask用于阻止SIGCHLD在以下代码中传递

C语言不必要的重复

python - 是否有与 Java 的 AWT Robot 类等效的 Python?