linux popen 擷取 ip test ok,popentest

來源:互聯網
上載者:User

linux popen 擷取 ip test ok,popentest

任務:unix,linux通過c程式擷取本機IP.

1. 標準I/O庫函數相對於系統調用的函數多了個緩衝區(,buf),安全性上通過buf 防溢出。

2.printf 這類輸出函數中“ ”若包含“記得要換成逸出字元\" 

 

[objc] view plain copy print?

  1. #include<stdio.h>

  2. #define sizeofbuf 512    

  3. int main(int argc,char **argv)

  4. {

  5.         char    buf[sizeofbuf];

  6.         FILE    *fp;

  7.         char     ch;

  8.  

  9.         snprintf(buf,sizeof(buf),"ifconfig |grep -v 127.0.0.1|grep 'inet addr'|awk '{print $2}'|cut -d \":\" -f2");

  10.         fp = popen(buf,"r");

  11.         if( NULL == fp)

  12.         {

  13.                  printf("error");

  14.                  return -1;

  15.         }

  16.         printf("var ip = \"");

  17.         while( EOF != (ch=fgetc(fp)) )

  18.         {

  19.                 if (ch == '\n')

  20.                         ch = '\0'; //去除分行符號

  21.                 else{

  22.                         fputc(ch,stdout);

  23.                 }

  24.         }

  25.         printf("\"\n");

  26.         pclose(fp);//close piping 

  27.         return 0;

  28. }

  29. ~           

   編譯後運行成功擷取本機IP    

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.