You can block access to your site by IP with code or .htaccess.
If your site is being regularly accessed by bots or other undesirables, you can block them at the server level (e.g. via the .htaccess file) or you can use some code that stops the request process as early as possible.
The following bit of code runs very early in the request process to minimise the impact on your website. It uses the ‘muplugins_loaded‘ action which is run after all the plugins in the wp-content/mu-plugins directory are loaded. This is the first action listed in the WordPress Plugin Action Reference.
The code is simple – add the IP addresses to be blocked to the $ips_to_block array. You could use a plugin to maintain the list (e.g. LionScripts: IP Blocker Lite) but writing my own code was a learning experience for me.
The file must be put in the wp-content/mu-plugins directory to ensure that it runs very early. This also ensures that the site administrator cannot disable the plugin, accidentally or otherwise. I sometimes put very important custom plugin files in there for this reason.
Block with .htaccess
It is more efficient for the web server to block the IP before WordPress is loaded. The code above does not block direct access to assets on the server e.g. image files, because accessing them does not involve WordPress at all.
To completely block an IP you can add the following lines to the .htaccess file at the top of your web site area. I use the Block IPs tool at htaccesstools.com because I always forget the syntax. It also has a handy htpasswd generator.