qt中提供了可以實現域名解析功能的類QHostInfo,這個類解析域名提供兩種機制,一種是阻塞式,一種是非阻塞信號槽機制,下面介紹第二種機制的實現方法。
qt的幫助中給出了這個類的例子:
[cpp]
- QHostInfo::lookupHost("www.kde.org",this, SLOT(lookedUp(QHostInfo)));
-
- //當解析成功域名後,會調用lookedUp槽函數
- void MyWidget::lookedUp(const QHostInfo &host)
- {
- if (host.error() != QHostInfo::NoError) {
- qDebug() << "Lookup failed:" << host.errorString();
- return;
- }
-
- foreach (QHostAddress address, host.addresses())
- qDebug() << "Found address:" << address.toString();
- }
仿照這個例子,我做了Linuxidc.com域名的解析測試:
[cpp]
- QHostInfo::lookupHost("www.linuxidc.com",this,SLOT(slot_get_ip(QHostInfo)));
-
- void test::slot_get_ip(QHostInfo host_info)
- {
- if (host_info.error() != QHostInfo::NoError)
- {
- qDebug() << "Lookup failed:" << host_info.errorString();
- return;
- }
-
- for (int i = 0;i < host_info.addresses().size();i++)
- {
- qDebug() << "Found address:" << host_info.addresses()[i].toString() << endl;
- }
- }
在調試窗口可以看到解析結果:
[cpp]
- Found address: "64.233.183.106"
-
- Found address: "64.233.183.147"
-
- Found address: "64.233.183.99"
-
- Found address: "64.233.183.103"
-
- Found address: "64.233.183.104"
-
- Found address: "64.233.183.105"