Linux popen obtains ip test OK and popentest
Task: unix. linux obtains the local IP address through the c program.
1. The standard I/O library functions have an extra buffer (, buf) compared to the functions called by the system, and buf is used to prevent overflow in security.
2. For output functions such as printf, if "is included, remember to replace it with an escape character \"
[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'; // remove line breaks
Else {
Fputc (ch, stdout );
}
}
Printf ("\" \ n ");
Pclose (fp); // close piping
Return 0;
}
~
After compilation, the local IP address is obtained successfully.