I have an application where a user can dynamically configure TCP connections between remote processes. I'd like to make sure the user input is valid, by providing them with a QComboBox
that is pre-populated with all the valid hostnames on their network. Is there a way to find the list of hostnames using Qt?
If possible I'd like to do this on both windows and linux.
This can be achieved using Qt classes, but you'll also need to use system tools to gather the hostname information, and those tools are different between linux and windows. That said, with a simple preprocessor switch, we can use QProcess
to call the right one, and pull the hostnames out of the result using a QRegExp
:
// find valid hostnames
QStringList hostnames;
QRegExp hostnameRx("\\\\\\\\(.*)");
QProcess cmd(this);
#ifdef _WIN32
cmd.start("cmd.exe");
cmd.write("net view\r\n");
cmd.write("exit\r\n");
#else
cmd.start("smbtree", QStringList() << "--no-pass");
#endif // _WIN32
cmd.waitForFinished();
while (!cmd.atEnd())
{
QString line = cmd.readLine();
hostnameRx.indexIn(line);
if (!hostnameRx.cap(1).trimmed().isEmpty())
{
hostnames << hostnameRx.cap(1).trimmed();
}
}
The regex strips the begining '\\' returned by both net view
and smbtree
, because QTcpSocket
connections take hostnames without it.
Obviously, the QStringList
can be used to populate a QComboBox
:
QComboBox* box = new QComboBox(this);
box->insertItems(0, hostnames);
NOTE: net view
and smbtree
are only going to show computers with accessible shares. You can try nmap
for a more complete list of live hosts, but you're going to need to run as root and you'll still probably hit a lot of firewall issues.