This is the sort of thing you might want to do if you made a network status indicator. In a loop, resolve the DNS and return the result of ping.
So, how can we make sure DNS resolve continues to work when the network device is changed? In this case by disconnecting the builtin network followed by connecting a GPRS modem.
I'm using Fedora 13 but I'm guessing it's the same behavior on many other nix-based systems.
As you can see from the log below, when switching it goes from "non-authoritative" to "authoritative" but the host is never found.
(Please tell me how to markdown escape << inside a pre code block or do i have to use HTML code?)
#include <iostream>
#include <boost/asio.hpp>
int main(int argc, char *argv[]) {
std::string DNS = "www.google.com";
while (1) {
try {
boost::asio::io_service io_service;
boost::asio::ip::tcp::resolver resolver(io_service);
boost::asio::ip::tcp::resolver::query query(DNS.c_str(), "");
boost::asio::ip::tcp::resolver::iterator iter = resolver.resolve(query);
boost::asio::ip::tcp::resolver::iterator end;
if (iter != end) {
boost::asio::ip::address addr = (iter++)->endpoint().address();
std::cout << addr.to_string() << std::endl;
}
}
catch (std::exception &e) {
std::cerr << "Error: GetIP():" << e.what() << std::endl;
}
usleep(1000000);
}
}
[test@Test-Live-1010001 Downloads]$ g++ -o test -lboost_system -lpthread testcase_hostname_not_found.cpp
[test@Test-Live-1010001 Downloads]$ ./test
209.85.149.106
209.85.149.99
209.85开发者_如何学C.149.104
209.85.149.147
209.85.149.106
209.85.149.103
209.85.149.105
209.85.149.99
209.85.149.103
209.85.149.103
209.85.149.106
Error: GetIP(): Host not found (non-authoritative), try again later
Error: GetIP(): Host not found (non-authoritative), try again later
Error: GetIP(): Host not found (non-authoritative), try again later
Error: GetIP(): Host not found (non-authoritative), try again later
Error: GetIP(): Host not found (non-authoritative), try again later
Error: GetIP(): Host not found (non-authoritative), try again later
Error: GetIP(): Host not found (non-authoritative), try again later
Error: GetIP(): Host not found (non-authoritative), try again later
Error: GetIP(): Host not found (non-authoritative), try again later
Error: GetIP(): Host not found (authoritative)
Error: GetIP(): Host not found (authoritative)
Error: GetIP(): Host not found (authoritative)
Since you're running Fedora, NetworkManager is probably running and automatically removing the DHCP-learned nameservers from /etc/resolv.conf
when the Ethernet goes down. (Or otherwise modifying resolv.conf
in response to the interface changes)
精彩评论