Testing AdSense in localhost [#20]

When using AdSense, you may want to test how your website looks with ads before going live. If you are running the website on your machine, you may have a URL such as "http://localhost:4200/" for example. If you have already added the AdSense scripts to the website, you may notice that while running in localhost, you have some blank spaces similar to the ones in the following screenshot.

Basically, the problem is that you have set AdSense to run using a domain such as abarrenechea.net, and on your machine, you are using a domain that AdSense does not expect. This issue can be addressed using a subdomain such as dev.abarrenechea.net or local.abarrenechea.net and mapping it to your localhost environment.

Map a subdomain to a free IP in our local environment

  • Choose an IP

    The first step is to find an unused IP in your local environment. You have many options to accomplish this. I will use a NetStat command (NetStat is a cross-system network tool) in a bash command line. After running the command, I decided to go with the IP 127.65.43.22, which was free.

    netstat -a -n -p TCP | grep "LISTENING"
  • Map the subdomain to the free IP we chose in the previous step

    We will edit the "hosts" file in Windows to accomplish this. You can find the file in c:\Windows\System32\Drivers\etc\hosts. Open the file in administrator mode in Notepad or another text editor and add the IP and subdomain. It should look like this after the changes.

  • Add a proxy

    Now, we must map the IP in the previous step (127.65.43.22) to localhost. I will use a tool called Network Shell (NetSh) to accomplish this.

    netsh interface portproxy add v4tov4 listenport=80 listenaddress=127.65.43.22 connectport=4200 connectaddress=127.0.0.1

After this configuration, you should be able to go to your browser and use your subdomain to load your website on your machine.

Other NetSh (Network Shell) useful commands

Remove an existing port proxy

This commands removes a proxy configuration added through netsh.

netsh interface portproxy delete v4tov4 listenport=80 listenaddress=127.65.43.22
Show interface configuration
netsh interface ipv4 show config
Show TCP connections
netsh interface ipv4 show tcpconnections