How do I output my host’s IP addresses from a C program?

后端 未结 8 662
猫巷女王i
猫巷女王i 2020-12-03 21:19

I need to display all the IP addresses from my local computer, using the C language. How can this be done?

8条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-03 22:03

    $ sudo ifconfig | grep 'inet addr' | cut -d':' -f2 | cut -d' ' -f1
    213.xx.xxx.xx
    192.168.xx.x
    127.0.0.1
    

    And you can put that into popen():

    /* not tested */
    ph = popen("sudo ifconfig | grep 'inet addr' | cut -d':' -f2 | cut -d' ' -f1", "r");
    while (fgets(buf, sizeof buf, ph)) {
        /* ip address, in nul-terminated string format, is in `buf` */
    }
    pclose(ph);
    

提交回复
热议问题