- gethostname function (winsock.h)
- Syntax
- Parameters
- Return value
- Remarks
- Смена имени компьютера [Hostname] в Windows [GUI/CMD/PowerShell]
- Смена имени компьютера через графический интерфейс Windows [GUI]
- Смена имени компьютера через командную строку [CMD]
- Смена имени компьютера через командную строку [PowerShell]
- Indiana University Indiana University Indiana University
- ARCHIVED: In Windows, how do I find my computer’s hostname?
- In Windows 7, Vista, or XP
- Using the command prompt
- GetHostNameW function (winsock2.h)
- Syntax
- Parameters
- Return value
- Remarks
gethostname function (winsock.h)
The gethostname function retrieves the standard host name for the local computer.
Syntax
Parameters
A pointer to a buffer that receives the local host name.
The length, in bytes, of the buffer pointed to by the name parameter.
Return value
If no error occurs, gethostname returns zero. Otherwise, it returns SOCKET_ERROR and a specific error code can be retrieved by calling WSAGetLastError.
Error code | Meaning |
---|---|
WSAEFAULT | The name parameter is a NULL pointer or is not a valid part of the user address space. This error is also returned if the buffer size specified by namelen parameter is too small to hold the complete host name. |
WSANOTINITIALISED | A successful WSAStartup call must occur before using this function. |
WSAENETDOWN | The network subsystem has failed. |
WSAEINPROGRESS | A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function. |
Remarks
The gethostname function returns the name of the local host into the buffer specified by the name parameter. The host name is returned as a null-terminated string. The form of the host name is dependent on the Windows Sockets provider—it can be a simple host name, or it can be a fully qualified domain name. However, it is guaranteed that the name returned will be successfully parsed by gethostbyname and WSAAsyncGetHostByName.
The maximum length of the name returned in the buffer pointed to by the name parameter is dependent on the namespace provider.
If the gethostname function is used on a cluster resource on Windows ServerВ 2008, Windows ServerВ 2003, or WindowsВ 2000 Server and the CLUSTER_NETWORK_NAME environment variable is defined, then the value in this environment variable overrides the actual hostname and is returned. On a cluster resource, the CLUSTER_NETWORK_NAME environment variable contains the name of the cluster.
The gethostname function queries namespace providers to determine the local host name using the SVCID_HOSTNAME GUID defined in the Svgguid.h header file. If no namespace provider responds, then the gethostname function returns the NetBIOS name of the local computer.
The maximum length, in bytes, of the string returned in the buffer pointed to by the name parameter is dependent on the namespace provider, but this string must be 256 bytes or less. So if a buffer of 256 bytes is passed in the name parameter and the namelen parameter is set to 256, the buffer size will always be adequate.
WindowsВ PhoneВ 8: This function is supported for Windows Phone Store apps on WindowsВ PhoneВ 8 and later.
WindowsВ 8.1 and Windows ServerВ 2012В R2: This function is supported for Windows Store apps on WindowsВ 8.1, Windows ServerВ 2012В R2, and later.
Смена имени компьютера [Hostname] в Windows [GUI/CMD/PowerShell]
В этой статье мы рассмотрим три способа изменения имени компьютера в Windows. Через графический интерфейс[GUI], через командную строку[CMD] и через командную строку[PowerShell].
В новых версиях Windows, зачастую, имя компьютера автоматически генерируется при установке и имеет неудобный вид, для работы в сети. Примерно такой — DESKTOP-12U0F7U или WIN-OPRPPF4CR5Q.
Лично я считаю, что от такого имени компьютера нужно сразу избавляться. Два раза запустите ping, ещё разок пропишете в подключении к удалённому рабочему столу и сойдёте с ума. Конечно, вместо имени можно везде использовать IP-адрес, но это не всегда удобно.
Представленные в статье способы подойдут для смены имени ПК в Windows 7, 8, 8.1, 10, Server 2008, 2012, 2016.
Смена имени компьютера через графический интерфейс Windows [GUI]
И так заходим в «Панель управления«(Рис.1) -> «Система«.(Рис.2)
Рис.1 — Панель управления.
В окне «Система» находим раздел «Имя компьютера, имя домена и параметры рабочей группы«, справа нажимаем на надпись — «Изменить параметры«.(Рис.2)
Рис.2 — Система.
Откроется окно — «Свойства системы«.(Рис.3) [Кстати сразу же открыть это окно можно через «Выполнить«, вписав туда — sysdm.cpl]
На первой вкладке — «Имя компьютера» нажимаем кнопку — «Изменить«.
Рис.3 — Свойства системы.
Откроется еще одно окно — «Изменение имени компьютера или домена«.(Рис.4)
Рис.4 — Изменения имени компьютера или домена.
В строке — «Имя компьютера» вписываем, удобное для нас, имя компьютера. В моем случае я поменял на — «CONTROLLER«, и жмём — «ОК«.(Рис.5)
Рис.5 — Изменяем имя компьютера.
Получаем сообщение — «Чтобы изменения вступили в силу нужно перезагрузить компьютер» -> жмём — «ОК«.(Рис.6)
Рис.6 — Сообщение о необходимости перезагрузки ПК.
Закрываем окно — «Свойства системы«.(Рис.7)
Рис.7 — Закрываем окно «Свойства системы».
Получаем предложение — «Перезагрузить ПК сейчас» или «Перезагрузить ПК позже«.(Рис.8)
У меня ничего стороннего не запущено, и в сохранении ничего не нуждается. Короче перезагружаемся.
Рис.8 — Предложение перезагрузки ПК.
После перезагрузки проверяйте «Панель управления«(Рис.1) -> «Система«(Рис.2) Имя компьютера должно поменяться.
Смена имени компьютера через командную строку [CMD]
Для начала нам необходимо запустить командную строку с правами администратора, для этого выполните действия -> Заходим в «Выполнить«[Win+R] -> Вписываем — cmd -> Нажимаем на клавиатуре сочетание клавиш «CTRL«+»SHIFT«+»ENTER«. Всё! Приступаем.
Для начала, наверное, нужно посмотреть имя ПК, командой — hostname, а после, сделав выводы о том, что оно вас не устраивает, приступать к его изменению 😀 :
Для смены имени компьютера воспользуйтесь командой:
Так же покажу на своём примере. Я решил переименовать ПК в — «DC«.(Рис.9)
После ввода команды, ПК нужно перезагрузить. Раз уж начали в CMD, то и продолжим в CMD. Перезагружаемся командой — shutdown -r:
Рис.9 — Смена имени ПК через командную строку и перезагрузка.
После перезагрузки опять открываем командную строку и проверяем поменялось ли имя ПК, командой — hostname:(Рис.10)
Рис.10 — Проверяем поменялось ли имя ПК, командой Hostname.
Как видим в выводе команды написано — «DC«, а это значит, что смена имени ПК через командную строку прошла успешно. 🙂
Смена имени компьютера через командную строку [PowerShell]
Для начала нам необходимо запустить PowerShell c правами администратора, для этого выполните действия -> Заходим в «Выполнить«[Win+R] -> Вписываем — powershell -> Нажимаем на клавиатуре сочетание клавиш «CTRL«+»SHIFT«+»ENTER«. Всё! Приступаем.
Для начала посмотрим имя ПК[Оно хранится в переменной — $env:COMPUTERNAME](Рис.11):
Как видим: Имя моего ПК — DESKTOP-AREI4D1
Рис.11 — Просмотр имени ПК.
Для смены имени компьютера воспользуйтесь командой:
Как вы уже знаете — Для того чтобы cмена имени ПК завершилась, требуется перезагрузка.
Обратите внимание что в команде присутствует опция -Restart, а это значит, что ПК после ввода команды, сразу же перезагрузится. Можно конечно, удалить -Restart, взять паузу и перезагрузить ПК тогда, когда вам это будет необходимо, командой — Restart-Computer.
После перезагрузки проверьте имя ПК:
Indiana University Indiana University Indiana University
ARCHIVED: In Windows, how do I find my computer’s hostname?
To find your computer’s hostname:
In Windows 7, Vista, or XP
- In Windows 7, from the Start menu, right-click Computer . In Vista and XP, on the desktop, right-click Computer (Vista) or My Computer (XP).
- Select Properties . In Windows XP, then click the Computer Name tab.
Note: If this doesn’t match what you see, refer to Get around in Windows.
Windows XP default desktop view and Start menu are different from the Windows Classic View (e.g., in Windows 2000 ). Therefore, navigating to certain items can be different. In the interest of broad applicability, most Knowledge Base instructions assume you are using Classic View. For details about switching views, see
—>
Using the command prompt
- From the Start menu, select All Programs or Programs , then Accessories , and then Command Prompt .
- In the window that opens, at the prompt, enter hostname . The result on the next line of the command prompt window will display the hostname of the machine without the domain.
Note: Applications running on Unix systems are case sensitive, and recognize bl-uits-xxxxx and BL-UITS-XXXXX as two different computers. If you are providing your computer’s hostname to be used on one of these systems, be careful to indicate the correct character case.
GetHostNameW function (winsock2.h)
The GetHostNameW function retrieves the standard host name for the local computer as a Unicode string.
Syntax
Parameters
A pointer to a buffer that receives the local host name as a null-terminated Unicode string.
The length, in wide characters, of the buffer pointed to by the name parameter.
Return value
If no error occurs, GetHostNameW returns zero. Otherwise, it returns SOCKET_ERROR and a specific error code can be retrieved by calling WSAGetLastError.
Error code | Meaning |
---|---|
WSAEFAULT | The name parameter is a NULL pointer or is not a valid part of the user address space. This error is also returned if the buffer size specified by namelen parameter is too small to hold the complete host name. |
WSANOTINITIALISED | A successful WSAStartup call must occur before using this function. |
WSAENETDOWN | The network subsystem has failed. |
Remarks
The GetHostNameW function returns the name of the local host into the buffer specified by the name parameter in Unicode (UTF-16). The host name is returned as a null-terminated Unicode string. The form of the host name is dependent on the Windows Sockets provider—it can be a simple host name, or it can be a fully qualified domain name. However, it is guaranteed that the name returned will be successfully parsed by GetAddrInfoW.
With the growth of the Internet, there is a growing need to identify Internet host names for other languages not represented by the ASCII character set. Identifiers which facilitate this need and allow non-ASCII characters (Unicode) to be represented as special ASCII character strings (Punycode) are known as Internationalized Domain Names (IDNs). A mechanism called Internationalizing Domain Names in Applications (IDNA) is used to handle IDNs in a standard fashion. The GetHostNameW function does not convert the local hostname between Punycode and Unicode. The GetAddrInfoW function provides support for Internationalized Domain Name (IDN) parsing and performs Punycode/IDN encoding and conversion.
If the GetHostNameW function is used on a cluster resource on Windows ServerВ 2012 and the CLUSTER_NETWORK_NAME environment variable is defined, then the value in this environment variable overrides the actual hostname and is returned. On a cluster resource, the CLUSTER_NETWORK_NAME environment variable contains the name of the cluster.
The GetHostNameW function queries namespace providers to determine the local host name using the SVCID_HOSTNAME GUID defined in the Svgguid.h header file. If no namespace provider responds, then the GetHostNameW function returns the NetBIOS name of the local computer in Unicode.
The maximum length, in wide characters, of the string returned in the buffer pointed to by the name parameter is dependent on the namespace provider, but this string must be 256 wide characters or less. So if a buffer of 256 wide characters is passed in the name parameter and the namelen parameter is set to 256, the buffer size will always be adequate.
WindowsВ PhoneВ 8: This function is supported for Windows Phone Store apps on WindowsВ PhoneВ 8 and later.
WindowsВ 8.1 and Windows ServerВ 2012В R2: This function is supported for Windows Store apps on WindowsВ 8.1, Windows ServerВ 2012В R2, and later.