首先你们要知道在浏览器上浏览虚拟主机,必须使用Hosts文件或域名系统(DNS)实现主机名到IP地址的解析。在局域网中用Hosts文件或DNS均可以,在Internet上只能用DNS了。
浏览器
1.当用户输入一个域名以百度为例(www.baidu.com)。网络
2.首先会到C:\Windows\System32\drivers\etc目录中用Hosts文件去查询相关的IP是否存在,若是存在就会访问该IP地址。dom
3.不存在该域名解析,那么就会到公网DNS查找。工具
当你访问域名出现异常,可能Hosts文件被修改了或者DNS被挟持了。ui
解决方案:spa
1.首先检查你的C:\Windows\System32\drivers\etc目录下的Hosts文件查看是否存在域名强制转向IP的状况,有的话把这个选项去掉。找不到文件设置隐藏文件可见。code
2.DNS被劫持或篡改了。你能够手动修改本地电脑的DNS,默认为空以下图,你能够在首选设置为:114.114.114.114,备用设置为:114.114.115.115;并查杀一下病毒。或者你的路由器被篡改了(设置的密码太弱),建议用修复工具修改。blog
上面介绍了网络正常域名访问出问题的缘由,那么下面就带你们使用C#搞一个Hosts修改工具(你们能够来研究,了解技术,可是不要用来恶搞他人):ip
private static void updateHosts(string ip,string domain) { string path = @"C:\WINDOWS\system32\drivers\etc\hosts"; //一般状况下这个文件是只读的,因此写入以前要取消只读 File.SetAttributes(path, File.GetAttributes(path) & (~FileAttributes.ReadOnly));//取消只读 //1.建立文件流 FileStream fs =ip==""? new FileStream(path, FileMode.Create): new FileStream(path, FileMode.Append); //2.建立写入器 StreamWriter sw = new StreamWriter(fs, Encoding.UTF8); //3.开始写入 bool result = false;//标识是否写入成功 try { StringBuilder sb = new StringBuilder(); sb.Append(ip);//IP地址 sb.Append(" "); sb.Append(domain);//网址 sw.WriteLine(sb.ToString()); result = true; } catch (Exception ex) { result = false; } finally { //4.关闭写入器 if (sw != null) { sw.Close(); } //5.关闭文件流 if (fs != null) { fs.Close(); } } if (result == true) { MessageBox.Show("成功!"); File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.ReadOnly);//设置只读 } else { MessageBox.Show("失败!"); return; } }
在网址部分输入www.baidu.com,以后添加试试看,你还能访问百度吗?路由
不要紧,以后你点清除,你又能够访问了!
源码地址:https://files.cnblogs.com/files/jiyuwu/HostsEdit.zip