页首Html代码

返回顶部

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++也不需要做处理,拿过来直接使用就好.

 

posted @ 2017-11-02 15:54  ayanmw  阅读(2692)  评论(0编辑  收藏  举报

页脚Html代码