admin 管理员组

文章数量: 1086019

unix,linux通过c程序获取本机IP. popen get ip test ok

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

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

  10.         if( NULL == fp)

  11.         {

  12.                  printf("error");

  13.                  return -1;

  14.         }

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

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

  17.         {

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

  19.                         ch = '\0'; //去除换行符

  20.                 else{

  21.                         fputc(ch,stdout);

  22.                 }

  23.         }

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

  25.         pclose(fp);//close piping 

  26.         return 0;

  27. }

  28. 参考 

本文标签: Unix linux通过c程序获取本机IP popen get iptest ok