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    

相关内容