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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM