2009-10-08

Para o Árabe não se armar em esperto: getting an interface IP using popen()

Generated to HTML using c2html

/* Author: Pedro Francisco
* License: GPLv2 or any later version
*/


#include <iostream>
#include <stdlib.h>

std::string _osName("eth0");

int _getIPv4(std::string & ipv4)
{
char *cmdline = NULL;

asprintf(&cmdline,
"LC_ALL=C ifconfig %s |grep \"inet addr.\" |sed 's_[a-z ]*:\\([0-9.]*\\).*_\\1_'",
_osName.c_str());

/* Thanks to dwhitney67 from Ubuntu Forums
* { http://ubuntuforums.org/showthread.php?p=5507024 }
* for the basis for this code
*/

FILE *pfd = popen(cmdline, "r");
if (pfd == NULL)
return -1;

const size_t BUFSZ = 1024;
char *buf = static_cast < char *>(malloc(BUFSZ));
size_t bufPos = 0;


bufPos += fread(buf + bufPos, 1, BUFSZ, pfd);
while (!feof(pfd)) {
// more data available
buf = static_cast < char *>(realloc(buf, bufPos + BUFSZ));
bufPos += fread(buf + bufPos, 1, BUFSZ, pfd);
}

buf[bufPos] = '\0';

pclose(pfd);
free(cmdline);

ipv4.assign(buf);
ipv4.assign(ipv4.substr(0, ipv4.find('\n')));

free(buf);

return 0;
}



int main(void)
{
std::string ipv4;

if (_getIPv4(ipv4) == 0)
std::cout << "ipv4 e' " << ipv4 << "\n";
else
std::cout << "Erro" << "\n";

return 0;
}


Generated to HTML using c2html

1 comment:

Halloween said...

Muito mais másculo! ;P