Как открыть и отредактировать файл hosts в macOS. Где находится файл hosts в Mac OS X и как его отредактировать Файл hosts mac os x

Как открыть и отредактировать файл hosts в macOS. Где находится файл hosts в Mac OS X и как его отредактировать Файл hosts mac os x

13.10.2021

Для разработчиков сайтов и клиент-серверных приложений на Mac OS файл HOSTS служит удобным средством отладки ПО. Файл имеет строковый формат, где каждая запись описывает порядок разрешения доменных имён на данном компьютере. Управление виртуальными подсетями – важная функция для любого компьютера, имеющего выход в интернет.

Технология

Для открытия веб страницы мы указываем её адрес, который включает доменное имя. Так, доменом является apple.com. Физически страница находится на сервере Apple, который имеет некоторый адрес в IPv4, например: 205.192.12.11. Чтобы превратить «apple.com» в IP адрес нужно обратиться к серверу доменных имён зоны.com (по-другому, DNS сервер домена COM). Адреса серверов.com, .ru и т.д. известны заранее и нужны для работы браузера.

Файл HOSTS имеет записи, аналогичные таблице DNS сервера, причём данные файла имеют приоритет над внешним DNS. Это означает, что если указать в качестве адреса для домена apple.com IP адрес своего компьютера и путь к папке, в которой лежит некоторая веб страница, то именно она будет загружаться в браузерах и других сторонних приложениях при вводе apple.com в адресную строку. Такой механизм помогает тестировать серверные программы до фактической отгрузки в интернет.

Как отредактировать записи

На Mac OS файл HOSTS расположен в системной памяти, поэтому открыть его можно через терминал.

  • Сочетанием клавиш Command+R вызовем панель запуска приложений и выберем «Терминал».
  • С помощью встроенного редактора Nano содержимое файла может просматриваться и редактироваться прямо в терминале.
  • Для этого вводим команду «sudonano /private/etc/hosts» и жмём Enter.

Стандартной записью файла hosts является сопоставление стандартного адреса компьютера с доменом localhost. Далее могут записываться пользовательские данные. Если вы хотите сопоставить домену mysite.com адрес 200.200.1.1, нужно добавить строку «200.200.1.1 mysite.com»

Структура файла практически не отличается от HOSTS для Windows. Важно при редактировании сохранять широковещательный адрес (запись с 255.255.255.255), который используется для массовой рассылки сетевых пакетов. Если в настройках интернета и локальной сети предусмотрено использование протокола IPv6, для него также должен быть описан адрес localhost.

Помимо переадресации, может присутствовать блок закрытых адресов (сюда в частности заносятся подозрительные сайты, найденные антивирусом), который начинается со строки «# Block».

Need to edit or modify the hosts file on a Mac? This guide will show you exactly how to edit the hosts file in Mac OS. You’ll find hosts in Mac OS X is stored at /private/etc/hosts but it can also be accessed at the more traditional location of /etc/hosts. That said, if you’re looking to edit hosts, you’ll want to target the file located in /private/etc/ though.

We’ll walk through how to manually edit the hosts file in MacOS Mojave, MacOS Catalina, MacOS High Sierra, MacOS Sierra, OS X El Capitan, Yosemite, OS X Lion, OS X Mountain Lion, and OS X Mavericks, this will be done with the command line using the simple text editor called nano. Don’t let the command line or Terminal sound intimidating though because it’s not, we’ll make the entire process of editing a Mac hosts file super easy.

How to Edit Hosts File on Mac OS

Let’s get started making some edits to /etc/hosts in macOS and Mac OS X!

  1. Launch Terminal, found in /Applications/Utilities/ or launched through Spotlight
  2. Type the following command at the prompt:
  3. sudo nano /private/etc/hosts

  4. Enter the administrator password when requested, you will not see it typed on screen as usual with the command line
  5. Once the hosts file is loaded within nano, use the arrow keys to navigate to the bottom of the hosts file to make your modifications
  6. When finished, hit Control+O followed by ENTER/RETURN to save changes to /private/etc/hosts, then hit Control+X to exit out of nano
  7. Quit out of Terminal when finished

You can verify your hosts modifications immediately with ping, Safari, or any other network app.

Changes take effect immediately though some adjustments may need to be accompanied by a which can be done with the following command in macOS 10.12+ through OS X 10.9:

dscacheutil -flushcache;sudo killall -HUP mDNSResponder

When flushing DNS cache with that command you will need to enter the admin password.

If you’d like to see how this entire process is accomplished before doing it yourself, watch the video below to see a demonstration of the hosts file being modified on OS X to block the website ‘yahoo.com’ from loading:

Note: the procedure is the same with older versions of Mac OS X, though the path to hosts could be /etc/hosts if the version of OS X is dated significantly.

Tips to Consider When Editing Hosts Files

The following tips go beyond OS X and apply to any hosts file, be it on a Mac, Windows, or Linux.

  • The preceding IP address is where the following domain will resolve to
  • Always add new hosts to their own unique line
  • The # symbol functions as a comment, it can be used to add comments to hosts entries or to comment out hosts modifications
  • You by adding them to the file and sending them nowhere, preventing access
  • You can redirect websites locally using the same logic, perfect for
  • With some modifications, it can be necessary to with dscacheutil before the changes take effect
  • For juggling multiple hosts files consider using a
  • If the hosts file claims to be locked, it’s because you did not prefix the edit with the “sudo” command
  • Consider making a backup of hosts if you plan on making significant modifications, or it’s your first time editing the file (process described below)

Making a backup of the hosts file can be a good idea if you plan on making significant changes or just want to play around with modifications and see what happens, a simple way to do that would be to use this command, which would store a backup in your home ~/Documents/ folder:

sudo cp /private/etc/hosts ~/Documents/hosts-backup

Then, if you wanted to restore the modified hosts to the backup of the original file, you just have to swap the paths like so and rename the file again:

sudo cp ~/Documents/hosts-backup /private/etc/hosts

That’s it, though again you may need to flush the DNS for changes to take effect.

Finally, it’s worth mentioning that if you’d prefer to avoid the Terminal and the command line completely, you could to modify the contents of hosts that way through System Preferences instead. Generally speaking though, we recommend just using the tools that are built directly into the Mac.

Let us know in the comments if you have any questions or tips.

Your Mac’s hosts file is a small, but important text document that has the ability to map hostnames to specified IP addresses. Although the modern Internet uses a variety of public and private DNS servers to map IP addresses, the hosts file is a handy way to override those DNS servers, allowing you to manually point a website address to the desired IP address, or block access to a site altogether by pointing to an unused or internal IP address.

Here’s how to edit the Mac hosts file on macOS (previously known as Mac OS X).

Edit Your Mac Hosts File with Text Edit

There are two primary ways to edit the hosts file in Mac OS X. The first is by using TextEdit since the hosts file is a plain text document. However, you can’t open the file directly, since it resides in a protected area of the file system. Instead, we need to copy the file to an unprotected location, like the Desktop, edit it, and then copy it back.

To find the hosts file, open the Finder, which you can access by clicking on the desktop, the smiley face finder in the lower left of your screen, or by pressing command + spacebar + “Finder” . Then follow these steps:



To open it, simply double-click and it will display the file’s contents in TextEdit (or the text editor of your choice).

Block IP Addresses

By default, the /etc/hosts file is relatively simple. It contains a number of lines of descriptive text which are “commented out” with the pound or number (also called a pound or hashtag) sign (#).

Any line that starts with a # sign is a comment and is not read by the /etc/hosts file. So comments are how you can add notes to your hosts file and comment out any lines that you want the /etc/hosts file to stop reading as entries but do not want to delete in case you need them in the future.

For each line, any text after the pound sign is ignored by the computer, making it a good way to add notes and descriptions to your files. It also contains default IP values for localhost and broadcasthost. To edit the file, you’ll add your own lines after broadcasthost.


In addition to testing newly developed websites and web hosting migrations, another reason to edit the hosts file is to block access to specific websites.

In our example, we’ll pretend that the computer we’re using is a device that we want to use exclusively for work, not allowing ourselves to get distracted by Facebook on our work machine.

To do this, type the IP address you wish to assign, followed by two tabs and the hostname. In our case, we want to block Facebook so we’ll map www.facebook.com to 0.0.0.0 which, as an invalid IP address, will result in an error.


Now, whenever we try to go to www.facebook.com from our Mac, the Web browser will fail to load the page, hopefully encouraging us to get back to work!

Reroute Web Addresses

Alternatively, you can enter the IP address of a valid site instead of 0.0.0.0, which will result in users attempting to access Facebook being directed to the site of your choosing.

To determine a website’s IP address, you can use the dig command, which comes standard with macOS. To “dig” the site via Terminal, we simply open up Terminal and then run the dig command on URL, which will then return the IP address as output.

$ dig www.сайт +short
104.25.27.105

Note: The +short option keeps the output to just the information we need, which is the IP address.

Make note of the IP address that’s returned and use it in your Mac hosts file mapping. For example, The New York Times website at www.nytimes.com returns an IP address of 170.149.172.130. If we map that to Facebook in our hosts file, any time someone using the Mac tries to go to Facebook, they’ll see The New York Times load instead.


Note: Many websites won’t allow you to map a domain name to the IP address currently mapped to the site so you’ll get a security error when you try.

You can add as many entries to the hosts file as you wish by entering new mappings on each line. Once you’ve made your desired changes to the hosts file, save it in its current location on the Desktop.

Then, drag and drop the hosts file from your Desktop back to its original location at /private/etc . If you’ve closed the Finder window pointing to this directory, simply use the Finder > Go > Go to Folder command, discussed above, to reopen it.

When you drop the hosts file back in its original location, macOS will ask you what to do about the unmodified hosts file that’s already there. Choose “Replace” and then enter your administrative user password to authenticate the transfer.

With the modified hosts file now in place, fire up your Web browser to test the changes.

Flush Your DNS Cache

In most cases, the new mapping should work immediately, but if you’re not seeing the correct behavior, you may need to flush your DNS cache, forcing the browser to read from your hosts file to determine the mapping.

To flush the DNS cache on your Mac, open Terminal and use the following command (sudo enables you to run this command as the admin of your machine):

$ sudo killall -HUP mDNSResponder

Note: You will need to enter your admin password to execute this command.

To get your Mac to clear your DNS cache, then confirm it’s cleared your cache by echoing a confirmation, enter these two commands separated by a semi-colon as shown here:

$ sudo killall -HUP mDNSResponder;say DNS cache has been flushed

Edit Your Mac Hosts File In Terminal With Nano

The steps in the previous section are easy enough, but if you want to avoid copying the hosts file you can edit it directly in Terminal using the UNIX Nano Text Editor, which is built into macOS.

To get started, launch Terminal, type the following command, and press Return. As with all sudo commands, you’ll need to also enter your admin password to execute it:
$ sudo nano /private/etc/hosts

You’ll now see the hosts file open in the Nano editor or vim or another editor of your choice. To navigate and edit the file in Nano, use the arrow keys on your keyboard.


Just as we did with the TextEdit method, above, we can add, edit, or remove hostname mappings at will. Because we launched Nano using sudo, any changes will be authenticated and saved directly to the original hosts file, without the need to copy it outside of its home directory.

When you’re done making changes, press Control-X to exit the editor, Y to save, and Return to overwrite the existing hosts file.

As we mentioned earlier, make sure to flush your DNS cache if you notice that your new mappings aren’t working properly.

Our examples mentioned blocking and redirecting distracting sites in a work environment but you can also use these steps to manually block access to malicious websites and, of course, other uses as well.

If you ever make a mistake and you’re not sure how to fix it, you can always restore the default hosts file contents by using one of the methods above to enter the following default information:

##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
##
127.0.0.1 localhost
255.255.255.255 broadcasthost::1 localhost
fe80::1%lo0 localhost

If you are a Mac user and found this article useful, you might want to check out other TechJunkie tutorials, including and

What’s the reason you are seeking to edit your Mac’s hosts file? How did it work out? Please tell us about it in the comments below!

First of all, what is the hosts file, and how does it differ from the more commonly known DNS?

The Domain Name System is the database that corresponds an IP address’ “dotted quad” numerical format with a website’s alphabetized web address. It’s a giant directory of which name belongs to which IP address, like an online yellow pages.

Your Mac’s hosts file, however, is localized to your own device, like a list of contacts in your phone: The web address acts as your contact’s name - that’s how you find who you want to talk to - and the IP address is their cell phone number, which is your actual way of getting in touch with them.

How editing the hosts file works

Editing your Mac hosts file is a bit like changing the phone number in your contact book. If you save the contact details with the wrong name, well, it’s still going to connect to that person when you ring the contact. If, however, you entered an incorrect phone number in our contacts analogy, whether that’s an invalid number or one that links to someone else’s, then you have no chance of getting through to that particular cell phone.

Editing the hosts file reroutes the IP address, but only from your own Mac. Entering the web address will bounce you to a different IP address of your choosing (and therefore a different website) or to an invalid IP, which will give you an error page on your browser that says it can’t find the site you’re looking for.

Can it boost my Mac"s speed?

Editing a hosts file is a way to speed up your browser performance. But if you"re tired of half-measures and want some solid improvement, we recommend a full browser cleanup, including deletion of browser cache. Our personal favorite is as it has a tool to uninstall browser extensions and the rest of the garbage Macs accumulate from the web, emails and message chats. Check it out - .

So why would you want to change your hosts file?

Typically if you enter a web address in your browser, it’s because you want to reach that IP address. So what are the benefits of rerouting?

    Network Testing: If you’re developing a network, you can reroute the real domain name to the development site to see how real users experience it. This will not affect other users accessing the real site.

    Block Malicious Sites: Apart from the risk of viruses and malware, undetected add-ons can also find their way into your system and begin slowing things down. Although it’s always worth investing in pop-up ad blockers, editing the hosts file prevents known malicious sites from being accessed. If a link or pop-up attempts to enter the site, your OS simply re-routes it and takes you to a safer page.

    Increased Speed: As we said earlier, finding a website via the DNS is like flicking through the yellow pages for the correct address. With the hosts file being localized to your Mac, this could potentially speed up your browsing by omitting the middle man.

    Improved Productivity: Maybe you or your team are getting distracted with social media sites or video streaming. Blocking access to time-wasting sites is a good way of keeping focused on the job at hand.

How to edit the hosts file with Terminal

Note: You will need administrator privileges, including the password, to edit the Mac hosts file.

1) Find the Terminal application on your system. You can do this by either:

Use the Spotlight application to search for it.

Select Applications from the sidebar of a Finder window, and from there select Utilities and then double-click on Terminal.

2) Once you have the Terminal window open, you can access the Nano text editor, which is where you will edit the hosts file. Type sudo nano /etc/hosts and hit Enter. You’ll then be prompted for your administrator password. Once you’ve entered it, hit Enter again and you will be in the Nano text editor.


The Nano text editor might look intimidating if you’re not used to coding on your OS, but don’t worry: it’s very simple, and very easy to do.

3) Use your keyboard arrow keys to position your cursor beneath the text that is already there. This is where you’re going to enter your alternative IP address. Type the IP address that you want the site to reroute to, hit tab, and then type the domain name you want to be associated with it. So, if you would prefer that YouTube reroutes to your homepage, simply type the numerical IP address of your site, hit Tab, and then type www.youtube.com. To add another entry, simply enter a new line of text.

If you have no particular alternative site in mind, or you simply want to block access to it entirely, you can either enter an invalid IP address, such as 000.0.0.100, or use 127.0.01, which always refers back to your own system.

4) Save the changes by pressing control and O, and then exit the Nano text editor by pressing control and X, which will return you to the main Terminal screen.

5) To make sure your Mac doesn’t get confused by the conflicting information from its hosts file and the DNS, before you exit the command line type sudo killall -HUP mDNSResponder and hit Return. This clears your Mac’s DNS caches so that the old directory doesn’t conflict with your newly updated hosts file.

How to edit the hosts file with TextEdit

An alternative to the Terminal application is to use TextEdit instead.

1) Click Finder > Go > Go to Folder...

Then type /private/etc/hosts and press Go. This will locate the hosts file in the ‘etc’ folder.


2) Copy the file onto your desktop, and then double-click the copied file to edit it. In the open text file, add your line of alternative IP addresses just as you would in Terminal: First the rerouted IP address and then the corresponding domain name. Make sure that there is a space between the IP address and the domain name, otherwise it won"t work.

If you don"t want your Mac to access certain websites, use 127.0.0.1 for IP address. This will reroute the address back to your Mac. For example, if I wanted to block the access to Facebook on a particular Mac, I would edit hosts file to look like this:


Note: If the file is locked to prevent you from editing it, which is likely if you’re running on OS X 10.11 or later, you must disable SIP protection before you can make any changes.

3) Save the file, and then drag it back into the ‘etc’ folder. Your Mac will ask if you want to replace the file, which you do, and you will have to enter your administrator password to save the changes.

Remember, even if you own the domain name you are rerouting, the web address itself will not be affected. The hosts file only changes what happens on the Mac that contains it.

The risks of editing hosts file

Remember, you’re rerouting a domain to an IP address, not specifically a website. So if you have set one domain to be sent to another site, this depends on the IP address staying the same. If the destination website changes its IP address, your new route will no longer be valid, with the domain either ending up in a new website or producing an error message.

If your server is still taking too long to process requests, it may not be the DNS lookup that is slowing you down. It might be worth running a full clean of your OS to make sure the lag isn’t coming from your Mac.

How else you can protect privacy on your macOS

Anyone reading this is concerned enough about privacy and security to want to find a solution. As we’ve outlined in this article, there are several ways this can be done manually. Some of these fixes take time. Other solutions are fairly quick and easy to implement.

With , you can clean your system cache, user cache (which includes app and DNS cache history) and your browser cache. Of course, there is the manual way, as outlined in this article, or you can save a lot of time with one download and a few clicks to remove any digital footprints you want to delete.

If you want to clear cache safely and easily, here is how you can with CleanMyMac X:

  1. Launch CleanMyMac X ()
  2. Select System Junk.
  3. Click Scan > Clean.

In case you need to remove just DNS cache, do the following:

  1. Go to the Maintenance module.
  2. Choose Flush DNS Cache.
  3. Click Run.

Done! Your DNS cache flushed.

That’s all you need to do. Give it a try, or go through the steps outlined above to do this manually.

Справедливые, не завышенные и не заниженные. На сайте Сервиса должны быть цены. Обязательно! без "звездочек", понятно и подробно, где это технически возможно - максимально точные, итоговые.

При наличии запчастей до 85% процентов сложных ремонтов можно завершить за 1-2 дня. На модульный ремонт нужно намного меньше времени. На сайте указана примерная продолжительность любого ремонта.

Гарантия и ответственность

Гарантию должны давать на любой ремонт. На сайте и в документах все описано. Гарантия это уверенность в своих силах и уважение к вам. Гарантия в 3-6 месяцев - это хорошо и достаточно. Она нужна для проверки качества и скрытых дефектов, которые нельзя обнаружить сразу. Видите честные и реальные сроки (не 3 года), вы можете быть уверены, что вам помогут.

Половина успеха в ремонте Apple - это качество и надежность запчастей, поэтому хороший сервис работает с поставщиками на прямую, всегда есть несколько надежных каналов и свой склад с проверенными запчастями актуальных моделей, чтобы вам не пришлось тратить лишнее время.

Бесплатная диагностика

Это очень важно и уже стало правилом хорошего тона для сервисного центра. Диагностика - самая сложная и важная часть ремонта, но вы не должны платить за нее ни копейки, даже если вы не ремонтируете устройство по ее итогам.

Ремонт в сервисе и доставка

Хороший сервис ценит ваше время, поэтому предлагает бесплатную доставку. И по этой же причине ремонт выполняется только в мастерской сервисного центра: правильно и по технологии можно сделать только на подготовленном месте.

Удобный график

Если Сервис работает для вас, а не для себя, то он открыт всегда! абсолютно. График должен быть удобным, чтобы успеть до и после работы. Хороший сервис работает и в выходные, и в праздники. Мы ждем вас и работаем над вашими устройствами каждый день: 9:00 - 21:00

Репутация профессионалов складывается из нескольких пунктов

Возраст и опыт компании

Надежный и опытный сервис знают давно.
Если компания на рынке уже много лет, и она успела зарекомендовать себя как эксперта, к ней обращаются, о ней пишут, ее рекомендуют. Мы знаем о чем говорим, так как 98% поступающих устройств в СЦ восстанавливется.
Нам доверяют и передают сложные случаи другие сервисные центры.

Сколько мастеров по направлениям

Если вас всегда ждет несколько инженеров по каждому виду техники, можете быть уверены:
1. очереди не будет (или она будет минимальной) - вашим устройством займутся сразу.
2. вы отдаете в ремонт Macbook эксперту именно в области ремонтов Mac. Он знает все секреты этих устройств

Техническая грамотность

Если вы задаете вопрос, специалист должен на него ответить максимально точно.
Чтобы вы представляли, что именно вам нужно.
Проблему постараются решить. В большинстве случаев по описанию можно понять, что случилось и как устранить неисправность.



© 2024 beasthackerz.ru - Браузеры. Аудио. Жесткий диск. Программы. Локальная сеть. Windows