linux C++ 获取服务器外网IP地址(使用系统调用system)

废话不多说,直接贴代码:

#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include<string>


int _System(const std::string cmd, std::string &output)
{
    FILE * fp;
    int res = -1;
    if ((fp = popen(cmd.c_str(), "r") ) == NULL)
    {
        printf("Popen Error!\n");
        return -2;
    }
    else
    {
        char pRetMsg[10240]={0};
        //get lastest result
        while(fgets(pRetMsg,10240, fp) != NULL)
        {
            output+=pRetMsg;
        }

        if ( (res = pclose(fp)) == -1)
        {
            printf("close popenerror!\n");
            return -3;
        }
        return 0;
    }
}

int main()
{
    //test cmd
    //char *cmd = "lsmod";
    std::string cmd = "curl -s members.3322.org/dyndns/getip";
    int ret = 0;
    std::string result;
    ret  = _System(cmd, result);
    printf("ret = %d \nresult = %s\nlength = %d \n", ret, result.c_str(),result.length());
    return 0;
}

运行结果:

[login@server ~]$ g++ callsystemrt.cpp && ./a.out 
ret = 0 
result = 120.132.101.54

length = 15

本来想用C++socket来获得的,不过太麻烦,还不如直接通过 管道,来调用 system 系统回调.

可以做成配置,把 cmd 放到配置中,如果发现不起作用了,换一个其他的获取ip的第三方ip地址,并用 shell来筛选出ip地址,这样C++也不需要做处理,拿过来直接使用就好.

原文链接: https://www.cnblogs.com/ayanmw/p/7772661.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/262452

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月14日 下午3:09
下一篇 2023年2月14日 下午3:10

相关推荐