任务:unix,linux通过c程序获取本机IP.
1. 标准I/O库函数相对于系统调用的函数多了个缓冲区(,buf),安全性上通过buf 防溢出。
2.printf 这类输出函数中“ ”若包含“记得要换成转义字符\"
[objc] view plain copy print?
#include<stdio.h>
#define sizeofbuf 512
int main(int argc,char **argv)
{
char buf[sizeofbuf];
FILE *fp;
char ch;
snprintf(buf,sizeof(buf),"ifconfig |grep -v 127.0.0.1|grep 'inet addr'|awk '{print $2}'|cut -d \":\" -f2");
fp = popen(buf,"r");
if( NULL == fp)
{
printf("error");
return -1;
}
printf("var ip = \"");
while( EOF != (ch=fgetc(fp)) )
{
if (ch == '\n')
ch = '\0'; //去除换行符
else{
fputc(ch,stdout);
}
}
printf("\"\n");
pclose(fp);//close piping
return 0;
}
~
编译后运行成功获取本机IP