【问题标题】:C - how to get all IPs connected to my pcC - 如何让所有 IP 连接到我的电脑
【发布时间】:2017-06-16 00:48:51
【问题描述】:

正如标题所说。我想获取连接到我的电脑的所有 IP 的列表。不是路由器,也不是网络上的 PC。只有我连接的IP。我知道 C# 中有一种方法,但你如何在 C 中做到这一点。
我在 linux 上这样做。

【问题讨论】:

  • 我们说的是 Linux 还是 Windows 操作系统?
  • @OferArial 我在谈论 linux - 让我通过编辑添加它
  • 我尝试在下面为 linux 提供一个解决方案。

标签: c ip


【解决方案1】:

This comment 链接到解析读取的程序:

/proc/net/tcp
/proc/net/udp
/proc/net/raw

【讨论】:

    【解决方案2】:

    您正在询问您的 IP 地址。要获取每个接口的 IP 地址列表,您可以使用ifconfig 内置的 linux 功能,该功能将输出数据,然后您可以对其进行解析。

    归功于answer,并基于它,您可以使用以下代码在新行中打印每个地址:

    在运行之前,使用locate ifconfig 并相应地设置字符串中的路径。

    注意我的评论:首先检查此命令是否通过终端为您输出所需的输出!

    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main( int argc, char *argv[] )
    {
    
      FILE *fp;
      char ip[15];
    
      /* Open the command for reading. */
      fp = popen("ifconfig | grep \"inet addr\" | cut -d\":\" -f2 | cut -d\" \" -f1", "r");
    
      /*First check that this command outputs the wanted output for you*/
      if (fp == NULL) {
        printf("Failed to run command\n" );
        exit(1);
      }
    
      /* Read the output a line at a time - output it. */
      while (fgets(ip, sizeof(ip)-1, fp) != NULL) {
        printf("%s", ip);
      }
    
      /* close */
      pclose(fp);
    
      return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-21
      • 1970-01-01
      相关资源
      最近更新 更多