Network: 一种屏蔽网页广告的方法 - 修改hosts文件

手机上网是越来越流行了,但随之而来是网站运营商却越来越无耻了,动不动就让你抢个红包什么的,要是真的有红包可抢,那也就算了,关键是它有可能把你引到什么钓鱼网站,让你走入万劫不复的深渊。

我不想要这样的广告,我不想让浏览器下方的大片区域被这些可恶的广告占领;我也不想换能够屏蔽这些广告的浏览器,chrome这么好用,我为什么要更换。

  • 原理

那么,还有什么办法能够去除这些广告呢?我们知道当我们使用浏览器打开这些网页时,会与网站建立TCP连接并发送请求,如:

GET /index.html HTTP/1.1
Host: www.example.com

而服务器就会响应这个请求:

HTTP/1.1 200 OK
Date: Mon, 23 May 2005 22:38:34 GMT
Content-Type: text/html; charset=UTF-8
Content-Encoding: UTF-8
Content-Length: 138
Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)
ETag: "3f80f-1b6-3e1cb03b"
Accept-Ranges: bytes
Connection: close

<html>
<head>
  <title>An Example Page</title>
</head>
<body>
  Hello World, this is a very simple HTML document.
</body>
</html>

这里需要说明的是,我们可以得到网页的源代码,并且是以文本的形式,而通过chrome的inspect工具,我们可以定位页面显示的内容对应的源代码:

2017_04_23_uvpn_ad

这里我们可以看到底部内容对应的源代码,并且这些内容都是在iframe标签里,加载的内容来自http://pos.baidu.com。

为了不显示这些内容,我们可以这么做:

1. 将网页源代码中的相关代码移除

2. 使浏览器无法从相应的网站获取数据

显然,使用第2种方法会更简单一些,所以这里我们会使用这种方法。

使浏览器无法获取网站数据最简单的做法,当然是使浏览器无法与之建立连接,我们可以将域名指向localhost(127.0.0.1)。

为了能够让域名指向localhost, 最简单的做法:修改hosts文件。

  • 什么是hosts文件

在*nix中执行man hosts

The hosts file contains information regarding the known hosts on the network.  For each host a single line should be present with the following information:

           Internet address
           Official host name
           Aliases

Items are separated by any number of blanks and/or tab characters.  A ``#'' indicates the beginning of a comment; characters up to the end of the line are not interpreted by routines which search the file.

Network addresses may either be specified for IP version 4 or version 6.  IP version 4 addresses are specified in the conventional dotted address notation.  IP version 6 addresses are specified using the colon-separated notation described in RFC1924.

Host names may contain any printable character other than a field delimiter, newline, or comment character.

The hosts file is read by mDNSResponder(8) and used to supply results for calls to getaddrinfo(3), getnameinfo(3), etc. in addition to results obtained from multicast and unicast DNS.
  • 修改hosts文件

存放位置:

1. Windows: %SystemRoot%\System32\drivers\etc\hosts

2. *nix: /etc/hosts

3. Mac OS: /etc/hosts

4. Android: /system/etc/hosts (需要root权限)

修改方法:

# Localhost
127.0.0.1	localhost
::1	localhost ip6-localhost ip6-loopback

# Modified hosts start
127.0.0.1       pos.baidu.com

 

  • 相关的参考文档
  1. https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol

发表评论

电子邮件地址不会被公开。 必填项已用*标注