PDA

View Full Version : IP address find



kpmsivachand
21st February 2009, 06:20
Hi !

guys, In my project i need to find out the current system ip address. By using ifconfig we can get ip address. But i really need ipaddress by using the qt. I tried with QHostAddress, but leads failed (:. How can i get ip address of local mech using qt???

talk2amulya
21st February 2009, 07:27
try using QProcess

kpmsivachand
21st February 2009, 10:27
Thanks for your reply....
ya i used QProcess. But i need only ipaddress.

if,


QProcess *proc=new QProcess();
proc->start("ifconfig eth0 | head -n 2 \ | sed 'N;s/\n/ /;N;s/\n/ /' | awk '{print $7 " " $9 " " $5}' \ | sed -e 's/addr://g' -e 's/Mask://g'");


How can i use the | (pipe symbol) in QProcess??? :confused: And also i tried grep but it doesn't work. Other wise tell me how to use grep in QProcess. :(

talk2amulya
21st February 2009, 11:24
u r executing commands using QProcess the wrong way :)

try this:


QString prog = "/bin/bash";//shell
QStringList arguments;
arguments << "-c" << "ifconfig eth0 | head -n 2 \ | sed 'N;s/\n/ /;N;s/\n/ /' | awk '{print $7 " " $9 " " $5}' \ | sed -e 's/addr://g' -e 's/Mask://g'";
QProcess* process = new QProcess(this);
process->start(prog , arguments);
process->waitForFinished();
QString tmp = process->readAll();
qDebug() << tmp;

like this, u can run any command that u can run on a normal shell. just change the second argument in the "arguments" stringlist.. if it doesnt work, break commands and see if the results are right and then move forward..hopefully, this will work anyway

Cruz
21st February 2009, 11:33
Using ifconfig as information source makes you dependent on the platform. Probably the gurus will come up with an easier way, but how about opening up a socket with a default address and reading the IP address out of that?

kpmsivachand
21st February 2009, 18:36
Thank u very much for your replies :) I got it. :)

Finally i got it the ipaddress only by using the QProcess.

My code was



QString prog = "/bin/bash";//shell
QStringList arguments;
arguments << "-c" << "ifconfig eth0 | grep ‘inet ‘ | awk ‘{print $2}’ | sed ’s/addr://’";
QProcess* process = new QProcess(this);
process->start(prog , arguments);
process->waitForFinished();
QString tmp = process->readAll();
qDebug() << tmp;


Above code will return only the ip address of the local mechine [ etho inet address: ]

aamer4yu
21st February 2009, 19:11
Did you have a look at QHostInfo ??
This might work for you ..

QString ipaddress = QHostInfo::.addresses().first().toString()

:)