廢話不多說,直接貼代碼:
#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++也不需要做處理,拿過來直接使用就好.
