任務:unix,linux經過c程序獲取本機IP.linux
1. 標準I/O庫函數相對於系統調用的函數多了個緩衝區(,buf),安全性上經過buf 防溢出。安全
2.printf 這類輸出函數中「 」若包含「記得要換成轉義字符\" 函數
[objc] view plain copy print?spa
#include<stdio.h>.net
#define sizeofbuf 512 unix
int main(int argc,char **argv)blog
{ip
char buf[sizeofbuf];get
FILE *fp;it
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