Firewall Port 1433 not opening
I am using MS Server 2008 with MSSQL 2008-R2 as database server.
Each time for some work i have to login to server via Remote connection.I tried to configure the SQL Server remote connection on, followed the following steps.
1.Created Inbound and outbound rules for tcp port 1433.
2.In sqlserver configuration manager ,all is set for IP address and POrt no properties.
3.Set the SqlServer instance for remote connections.
But still its not working.
Also when i checked port 1433 for tcp on local computer it is shown closed.
thanks in advance.
5 Answers 5
- Probably port 1433 is disabled, so enable it using MS WIndows firewall.
- Probably MS SQL Server Browser Service is not running. So go to Services and start it.
or just execute under Run menu
- Probably TCP/IP channel is disabled under SQL Server 2008/2014 Configuration Manager. SO go there and enable all TCP/IP options.

- Just in case at the same place (SQL Server 2008/2014 Configuration Manager) make sure you have 1433 port.

- Make sure that SQL server is configured to allow remote connections. Use MS SQL Management Studio and right click on the top node which server itself.

![]()
In the SQL Server Configuration Manager->SQL Server Network Configuration->Protocols, check that named pipes and tcp/ip are enabled.
If that doesn’t work then it may be your firewall blocking it, try this link: http://msdn.microsoft.com/en-us/library/cc646023.aspx
If named pipes and TCP/IP access are already enabled in SQL Server Configuration Manager, then you need to either add a rule for UDP port 1434, or a rule for sqlbrowser.exe so that the SSMS client can talk to the SQL Server Browser service.
I actually see people having this problem surprisingly often so I wrote up an explanation here: http://blog.dereenigne.com/microsoft-sql-server-dynamic-ports-windows-firewall-and-you/
If you’re trying to connect to an SQL Server Express instance as is my case right now. it doesn’t use port 1433 by default. One must check the IpAll => TCP Dynamic Ports in Sql Server Configuration Manager . Mine is 52848.
After entering the correct port 52848 in DbSchema app (the one I’m trying to use), it connected successfully.
Check the following screenshot: 
This is the way to go:
The default SQL Server express installation does not enable TCP network protocols, so here are some steps to take to be able to communicate with SQL Server Express. These steps should be similar for MS SQL Server Express 2017, 2016, 2014, 2012, 2008, and 2005.
Launch the SQL Server Configuration Manager. It should be in the Start -> Programs -> Microsoft SQL Server 2005 -> Configuration Tools start menu option.
Select the SQL Server 2005 Network Configuration tab. There should be a Protocols for SQLExpress option, and one of the protocols should be TCP IP.
Enable the TCP IP protocol if it is not enabled.
The default port for SQL Express may not be 1433. To find the port it is listening on, right-click on the TCP IP protocol and scroll all the way down to the IP All heading. There should be a section called TCP Dynamic Ports. This should list the port SQL Express is listening on. You can then put this value into the port field when adding the connection profile via RazorSQL.
Name already in use
sql-docs / docs / sql-server / install / configure-the-windows-firewall-to-allow-sql-server-access.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Configure the Windows Firewall to allow SQL Server access
Firewall systems help prevent unauthorized access to computer resources. If a firewall is turned on but not correctly configured, attempts to connect to [!INCLUDEssNoVersion] might be blocked.
To access an instance of the [!INCLUDEssNoVersion] through a firewall, you must configure the firewall on the computer that is running [!INCLUDEssNoVersion]. The firewall is a component of [!INCLUDEmsCoName] Windows. You can also install a firewall from another vendor. This article discusses how to configure the Windows Firewall, but the basic principles apply to other firewall programs.
[!NOTE]
This article provides an overview of firewall configuration and summarizes information of interest to a [!INCLUDEssNoVersion] administrator. For more information about the firewall and for authoritative firewall information, see the firewall documentation, such as Windows Firewall security deployment guide.
Users familiar with managing the Windows Firewall, and know which firewall settings they want to configure can move directly to the more advanced articles:
Basic firewall information
Firewalls work by inspecting incoming packets, and comparing them against the following set of rules:
- The packet meets the standards dictated by the rules, then the firewall passes the packet to the TCP/IP protocol for more processing.
- The packet doesn’t meet the standards specified by the rules.
- The firewall then discards the packet.- If logging is enabled, an entry is created in the firewall logging file.
The list of allowed traffic is populated in one of the following ways:
Automatically: When a computer with a firewall enabled starts communication, the firewall creates an entry in the list so that the response is allowed. The response is considered solicited traffic, and there’s nothing that needs to be configured.
Manually: An administrator configures exceptions to the firewall. It allows either access to specified programs or ports on your computer. In this case, the computer accepts unsolicited incoming traffic when acting as a server, a listener, or a peer. The configuration must be completed to connect to [!INCLUDEssNoVersion].
Choosing a firewall strategy is more complex than just deciding if a given port should be open or closed. When designing a firewall strategy for your enterprise, make sure you consider all the rules and configuration options available to you. This article doesn’t review all the possible firewall options. We recommend you review the following documents:
Default firewall settings
The first step in planning your firewall configuration is to determine the current status of the firewall for your operating system. If the operating system was upgraded from a previous version, the earlier firewall settings may have been preserved. The Group Policy or Administrator can change the firewall settings in the domain.
[!NOTE]
Turning on the firewall will affect other programs that access this computer, such as file and print sharing, and remote desktop connections. Administrators should consider all applications that are running on the computer before adjusting the firewall settings.Programs to configure the firewall
Configure the Windows Firewall settings with either Microsoft Management Console or netsh.
Microsoft Management Console (MMC)
The Windows Firewall with Advanced Security MMC snap-in lets you configure more advanced firewall settings. This snap-in presents most of the firewall options in an easy-to-use manner, and presents all firewall profiles. For more information, see Using the Windows Firewall with Advanced Security Snap-in later in this article.
netsh
The netsh.exe is an Administrator tool to configure and monitor Windows-based computers at a command prompt or using a batch file. By using the netsh tool, you can direct the context commands you enter to the appropriate helper, and the helper does the command. A helper is a Dynamic Link Library (.dll) file that extends the functionality. The helper provides: configuration, monitoring, and support for one or more services, utilities, or protocols for the netsh tool.
All operating systems that support [!INCLUDEssNoVersion] have a firewall helper. [!INCLUDEwinserver2008] also has an advanced firewall helper called advfirewall. Many of the configuration options described can be configured by using netsh. For example, run the following script at a command prompt to open TCP port 1433:
A similar example using the Windows Firewall for Advanced Security helper:
For more information about netsh, see the following links:
PowerShell
See the following example to open TCP port 1433 and UDP port 1434 for [!INCLUDEssNoVersion] default instance, and [!INCLUDEssNoVersion] Browser Service:
For Linux
On Linux, you also need to open the ports associated with the services you need access to. Different distributions of Linux and different firewalls have their own procedures. For two examples, see SQL Server on Red Hat, and SQL Server on SUSE.
Ports used by SQL Server
The following tables can help you identify the ports being used by [!INCLUDEssNoVersion].
Ports used by the Database Engine
By default, the typical ports used by [!INCLUDEssNoVersion] and associated database engine services are: TCP 1433, 4022, 135, 1434, UDP 1434. The table below explains these ports in greater detail. A named instance uses Dynamic ports.
The following table lists the ports that are frequently used by the [!INCLUDEssDE].
SELECT name, protocol_desc, port, state_desc
SELECT name, protocol_desc, port, state_desc FROM sys.tcp_endpoints
For step-by-step instructions to configure the Windows Firewall for the [!INCLUDEssDE], see Configure a Windows Firewall for Database Engine Access.
By default, named instances (including [!INCLUDEssExpress]) use dynamic ports. means each time [!INCLUDEssDE] starts, it identifies an available port and uses that port number. If the named instance is the only instance of the [!INCLUDEssDE] installed, it will probably use TCP port 1433. If other instances of the [!INCLUDEssDE] are installed, it will probably use a different TCP port. Because the port selected might change every time that the [!INCLUDEssDE] is started, it’s difficult to configure the firewall to enable access to the correct port number. If a firewall is used, we recommend reconfiguring the [!INCLUDEssDE] to use the same port number every time. A fixed port or a static port is recommended. For more information, see Configure a Server to Listen on a Specific TCP Port (SQL Server Configuration Manager).
An alternative to configuring a named instance to listen on a fixed port is to create an exception in the firewall for a [!INCLUDEssNoVersion] program such as sqlservr.exe (for the [!INCLUDEssDE]). The port number won’t appear in the Local Port column of the Inbound Rules page when you’re using the Windows Firewall with Advanced Security MMC snap-in. It can be difficult to audit which ports are open. Another consideration is that a service pack or cumulative update can change the path to the [!INCLUDEssNoVersion] executable file and invalidate the firewall rule.
To add an exception for SQL Server using Windows Firewall with Advanced Security, see Use the Windows Firewall with Advanced Security snap-in later in this article.
Ports used by Analysis Services
By default, the typical ports used by [!INCLUDEssNoVersion] Analysis Services and associated services are: TCP 2382, 2383, 80, 443. The table below explains these ports in greater detail.
The following table lists the ports that are frequently used by [!INCLUDEssASnoversion].
If users access [!INCLUDEssASnoversion] through IIS and the Internet, you must open the port on which IIS is listening. Next, specify port in the client connection string. In this case, no ports have to be open for direct access to [!INCLUDEssASnoversion]. The default port 2389, and port 2382, should be restricted together with all other ports that aren’t required.
For step-by-step instructions to configure the Windows Firewall for [!INCLUDEssASnoversion], see Configure the Windows Firewall to Allow Analysis Services Access.
Ports used By Reporting Services
By default, the typical ports used by [!INCLUDEssNoVersion] Reporting Services and associated services are: TCP 80, 443. The table below explains these ports in greater detail.
The following table lists the ports that are frequently used by [!INCLUDEssRSnoversion].
Feature Port Comments [!INCLUDEssRSnoversion] Web Services TCP port 80 Used for an HTTP connection to [!INCLUDEssRSnoversion] through a URL. We recommend that you don’t use the preconfigured rule World Wide Web Services (HTTP). For more information, see the Interaction with Other Firewall Rules section below. [!INCLUDEssRSnoversion] configured for use through HTTPS TCP port 443 Used for an HTTPS connection through a URL. HTTPS is an HTTP connection that uses TLS. We recommend that you don’t use the preconfigured rule Secure World Wide Web Services (HTTPS). For more information, see the Interaction with Other Firewall Rules section below. When [!INCLUDEssRSnoversion] connects to an instance of the [!INCLUDEssDE] or [!INCLUDEssASnoversion], you must also open the appropriate ports for those services. For step-by-step instructions to configure the Windows Firewall for [!INCLUDEssRSnoversion], Configure a Firewall for Report Server Access.
Ports used by Integration Services
The following table lists the ports that are used by the [!INCLUDEssISnoversion] service.
For step-by-step instructions to configure the Windows Firewall for [!INCLUDEssISnoversion], see Integration Services Service (SSIS Service).
Other ports and services
The following table lists ports and services that [!INCLUDEssNoVersion] might depend on.
The firewall has a setting (UnicastResponsesToMulticastBroadcastDisabled Property of the INetFwProfile Interface) which controls the behavior of the firewall and unicast responses to a broadcast (or multicast) UDP request. It has two behaviors:
If the setting is TRUE, no unicast responses to a broadcast are permitted at all. Enumerating services will fail.
Special considerations for port 135
When you use RPC with TCP/IP or with UDP/IP as the transport, inbound ports are dynamically assigned to system services as required. TCP/IP and UDP/IP ports that are larger than port 1024 are used. The ports are referred to as «random RPC ports.» In these cases, RPC clients rely on the RPC endpoint mapper to tell them which dynamic ports were assigned to the server. For some RPC-based services, you can configure a specific port instead of letting RPC assign one dynamically. You can also restrict the range of ports that RPC dynamically assigns to a small range, independent of the service. Because port 135 is used for many services, it’s frequently attacked by malicious users. When opening port 135, consider restricting the scope of the firewall rule.
For more information about port 135, see the following references:
Interaction with other firewall rules
The Windows Firewall uses rules and rule groups to establish its configuration. Each rule or rule group is associated with a particular program or service, and that program or service might modify or delete that rule without your knowledge. For example, the rule groups World Wide Web Services (HTTP) and World Wide Web Services (HTTPS) are associated with IIS. Enabling those rules will open ports 80 and 443, and [!INCLUDEssNoVersion] features that depend on ports 80 and 443 will function if those rules are enabled. However, administrators configuring IIS might modify or disable those rules. If you’re using port 80 or port 443 for [!INCLUDEssNoVersion], you should create your own rule or rule group that maintains your preferred port configuration independently of the other IIS rules.
The Windows Firewall with Advanced Security MMC snap-in allows any traffic that matches any applicable allow rule. So if there are two rules that both apply to port 80 (with different parameters). Traffic that matches either rule will be permitted. So if one rule allows traffic over port 80 from local subnet and one rule allows traffic from any address, the net effect is that all traffic to port 80 is independent of the source. To effectively manage access to [!INCLUDEssNoVersion], administrators should periodically review all firewall rules enabled on the server.
Overview of firewall profiles
Firewall profiles are used by the operating systems to identify and remember each of the networks by: connectivity, connections, and category.
There are three network location types in Windows Firewall with Advanced Security:
- Domain: Windows can authenticate access to the domain controller for the domain to which the computer is joined.
- Public: Other than domain networks, all networks are initially categorized as public. Networks that represent direct connections to the Internet or are in public locations, such as airports and coffee shops should be left public.
- Private: A network identified by a user or application as private. Only trusted networks should be identified as private networks. Users will likely want to identify home or small business networks as private.
The administrator can create a profile for each network location type, with each profile containing different firewall policies. Only one profile is applied at any time. Profile order is applied as follows:
- The domain profile is applied if all interfaces are authenticated to the domain controller where the computer is a member.
- If all interfaces are either authenticated to the domain controller or are connected to networks that are classified as private network locations, the private profile is applied.
- Otherwise, the public profile is applied.
Use the Windows Firewall with Advanced Security MMC snap-in to view and configure all firewall profiles. The Windows Firewall item in Control Panel only configures the current profile.
Additional firewall settings using the Windows Firewall item in Control Panel
The added firewall can restrict the opening of the port to incoming connections from specific computers or local subnet. Limit the scope of the port opening to reduce how much your computer is exposed to malicious users.
[!NOTE]
Using the Windows Firewall item in Control Panel only configures the current firewall profile.Change the scope of a firewall exception using the Windows Firewall item in Control Panel
In the Windows Firewall item in Control Panel, select a program or port on the Exceptions tab, and then select Properties or Edit.
In the Edit a Program or Edit a Port dialog box, select Change Scope.
Choose one of the following options:
Any computer (including computers on the Internet): Not recommended. Any computer that can address your computer to connect to the specified program or port. This setting might be necessary to allow information to be presented to anonymous users on the internet, but increases your exposure to malicious users. Enabling this setting an allow Network Address Translation (NAT) traversal, such as the Allow edge traversal option will increase exposure.
My network (subnet) only: A more secure setting than Any computer. Only computers on the local subnet of your network can connect to the program or port.
Custom list: Only computers that have the IP addresses listed can connect. A secure setting can be more secure than My network (subnet) only, however, client computers using DHCP can occasionally change their IP address; will disable the ability to connect. Another computer, which you had not intended to authorize, might accept the listed IP address and connect to it. The Custom list is appropriate for listing other servers that are configured to use a fixed IP address.
IP addresses can be spoofed by an intruder. Restricting firewall rules are only as strong as your network infrastructure.
Use the Windows Firewall with Advanced Security snap-in
Advanced firewall settings can be configured by using the Windows Firewall with Advanced Security MMC snap-in. The snap-in includes a rule wizard and settings that aren’t available in the Windows Firewall item in Control Panel. These settings include:
- Encryption settings
- Services restrictions
- Restricting connections for computers by name
- Restricting connections to specific users or profiles
- Edge traversal allowing traffic to bypass Network Address Translation (NAT) routers
- Configuring outbound rules
- Configuring security rules
- Requiring IPsec for incoming connections
Create a new firewall rule using the New Rule wizard
- On the Start menu, select Run, type WF.msc , and then select OK.
- In the Windows Firewall with Advanced Security, in the left pane, right-click Inbound Rules, and then select New Rule.
- Complete the New Inbound Rule Wizard using the settings that you want.
Add a program exception for the SQL Server executable
From the start menu, type wf.msc. Press Enter or select the search result wf.msc to open Windows Defender Firewall with Advanced Security.
In the left pane, select Inbound rules.
In the right pane, under Actions, select New rule. . New Inbound Rule Wizard opens.
On Rule type, select Program. Select Next.
On Program, select This program path. Select Browse to locate your instance of [!INCLUDEssNoVersion]. The program is called sqlservr.exe . It’s normally located at:
C:\Program Files\Microsoft SQL Server\MSSQL<VersionNumber>.<InstanceName>\MSSQL\Binn\sqlservr.exe
Select Next.
On Action, select Allow the connection. Select Next.
On Profile, include all three profiles. Select Next.
On Name, type a name for the rule. Select Finish.
For more information about endpoints, see:
Troubleshoot firewall settings
The following tools and techniques can be useful in troubleshooting firewall issues:
The effective port status is the union of all rules related to the port. It can be helpful to review all the rules that cite the port number, when trying to block access to a port. Review the rules with the Windows Firewall with Advanced Security MMC snap-in and sort the inbound and outbound rules by port number.
Review the ports that are active on the computer on which [!INCLUDEssNoVersion] is running. The review process includes verifying which TCP/IP ports are listening and also verifying the status of the ports.
The PortQry utility can be used to report the status of TCP/IP ports as listening, not listening, or filtered. (The utility may not receive response from the port if it has a filtered status.) The PortQry utility is available for download from the Microsoft Download Center.
List which TCP/IP ports are listening
To verify which ports are listening, display active TCP connections and IP statistics use the netstat command-line utility.
Open the Command Prompt window.
At the command prompt, type netstat -n -a .
The -n switch instructs netstat to numerically display the address and port number of active TCP connections. The -a switch instructs netstat to display the TCP and UDP ports on which the computer is listening.
Настройка Брандмауэра Windows для MS SQL Server 2012 / 2008 (R2)
Если к службе Microsoft SQL Server должны подключаться программы с других компьютеров в сети, то необходимо чтобы правильным образом был настроен Брандмауэр Windows на сервере, где запущена служба. А именно разрешены входящие подключения по определенному порту, используемому компонентой Database Engine SQL Server. О том как узнать, какой порт использует SQL Server, изменить этот порт, а также настроить Брандмауэр Windows читайте в данной статье.
0. Оглавление
1. Что понадобится
- Статья будет актуальна для Microsoft SQL Server 2012 и для Microsoft SQL Server 2008 (R2).
- В качестве операционной системы сервера рассматриваются Microsoft Windows Server 2012 (R2) или Microsoft Windows Server 2008 (R2)
2. Определение / изменения порта для «экземпляра по умолчанию»
По умолчанию SQL Server использует для соединения порт 1433. Чтобы проверить это, запустим оснастку «Диспетчер конфигурации SQL Server» (SQL Server Configuration Manager). В Microsoft Windows Server 2012 (R2) ее можно найти в списке всех программ.

В Microsoft Windows Server 2008 (R2) в меню «Пуск» (Start) — «Microsoft SQL Server 2012» — «Средства настройки» ( Configuration Tools ) — «Диспетчер конфигурации SQL Server» (SQL Server Configuration Manager)

В запустившейся оснастке раскроем вкладку «Сетевая конфигурация SQL Server» (SQL Server Network Configuration), затем выделим вкладку «Протоколы для MSSQLSERVER» (Protocols for MSSQLSERVER). В окне слева в таблице найдем протокол TCP/IP, кликнем по нему правой кнопкой мыши и в контекстном меню выберем «Свойства» (Properties).

В открывшемся окне свойств перейдем на вкладку «IP-адреса» (IP Addresses), затем найдем и раскроем в дереве настроек ветку «IPAll». Здесь мы видим, что выбранный экземпляр SQL Server использует TCP-порт по умолчанию, а именно порт 1433. Если по каким то причинам требуется использовать другой номер порта, необходимо просто поменять текущее значение, нажать «Применить» (Apply) и перезапустить службу SQL Server.

3. Определение / изменения порта для именованного экземпляра SQL Server
В случае использования именованного экземпляра SQL Server ситуация аналогичная, за тем лишь исключением, что используются динамические TCP-порты. Это значит, что для каждого отдельного экземпляра будет назначен свой номер порта.
Для определения / изменения текущего порта, найдем в оснастке «Диспетчер конфигурации SQL Server» (SQL Server Configuration Manager) вкладку с сетевой конфигурацией необходимого нам экземпляра SQL Server и перейдем в свойства протокола TCP/IP для данного экземпляра. Здесь, как и в предыдущем случае, на вкладке «IP-адреса» (IP Addresses) в ветке «IPAll» можно узнать, а также изменить динамический TCP-порт для текущего экземпляра SQL Server.

4. Добавление правила в Брандмауэр Windows
Теперь, когда мы определились с номером порта, который будет использоваться для подключения к службе SQL Server, создадим разрешающее правило в Брандмауэре Windows на сервере, где запущена служба.
О том, как добавить разрешающее правило для определенного порта в Microsoft Windows Server 2008 (R2) я уже писал здесь. В Windows Server 2012 (R2) действия аналогичны.
Запускаем брандмауэр Windows (Windows Firewall). Сделать это можно кликнув правой кнопкой мыши по « Пуск » ( Start ), затем « Панель управления » ( Control Panel ) — « Система и безопасность » ( System and Security ) — « Брандмауэр Windows » ( Windows Firewall ). Или же выполнив команду firewall.cpl (для этого необходимо нажать комбинацию клавиш Win + R, в окне « Отрыть » ( Open ) ввести имя команды и нажать « ОК » ) .

Далее нажимаем на « Дополнительные параметры » ( Advanced Settings ) в меню слева.

В открывшемся окне, в дереве слева откроем вкладку « Правила для входящих подключений » ( Inbound Rules ), а затем в меню « Действия » ( Actions ) выберем пункт « Создать правило… » ( New Rule… ).

Запустится «Мастер создания правила для нового входящего подключения» (New Inbound Rule Wizard). На первой странице выберем тип правила (Rule Type) «Для порта» (Port) и нажмем «Далее» (Next).

Затем необходимо указать протокол (в нашем примере это TCP) и, непосредственно, номер порта (Specific local ports), который открываем. После чего жмем « Далее » ( Next ).

Теперь укажем действие связанное с добавляемым правилом. Выберем « Разрешить подключение » ( Allow the connection ) и нажмем « Далее » ( Next ).

На следующей странице нужно указать, для каких профилей брандмауэра будет действовать правило. Отмечаем нужные профили галочками и жмем « Далее » ( Next ).

Ну и наконец, вводим имя и описание для нового правила и нажимаем « Готово » ( Finish ) для завершения работы мастера.

А в оснастке « Брандмауэр Windows в режиме повышенной безопасности » ( Windows Firewall with Advanced Security ) в таблице « Правила для входящих подключений » ( Inbound Rules ) мы увидим только что созданное правило.

На этом настройка Брандмауэра завершена. Клиентские программы должны без препятствий подключиться к службе SQL Server.
5. Порт для администрирования MS SQL Server
Для того, чтобы к MS SQL Server можно было подключиться с помощью программы SQL Management Studio, необходимо также добавить правило для протокола UDP и порта 1434.
Подробнее о используемых SQL Server портах здесь.
Смотрите также:
Здесь будет рассказано как изменить политику паролей в Windows Server 2008. По умолчанию все пароли в Windows должны отвечать политике безопасности, а именно: Не содержать имени учетной записи пользователя…
Ниже будет рассказано о том, как добавить новое правило в Брандмауэр Windows Server 2008 R2. А конкретнее, будем добавлять разрешающее правило для порта 1433, который использует Microsoft SQL Server 2008 R2 или, как…
Ниже приведена небольшая инструкция об изменении политики паролей в Microsoft Windows Server 2012 R2. По умолчанию политика паролей определена таким образом, что все пароли учетных записей пользователей должны удовлетворять следующим…
Как изменить порт экземпляра Microsoft SQL Server?
09.07.2020
insci
SQL Server
Комментариев пока нетВ этой статье мы разберемся как узнать текущий TCP порт, на котором слушает и ожидает подключения именованный или default экземпляр MS SQL Server, как изменить порт подключения SQL Server на статический/динамический и как используется служба SQL Server Browser клиентами при подключении к SQL.
- Default экземпляр SQL Server (MSSQLSERVER) работает на статическом порту TCP 1433. Именно к этому порту подключаются клиенты, или консоль SQL Server Management Studio (SSMS);
- Именованные экземпляры MSSQL и SQL Server Compact по-умолчанию настроены на использование динамического TCP порта из диапазона RPC (49152 – 65535).
Динамической порт означает, что номер порта, на котором принимает подключение экземпляр MSSQL назначается при запуске службы SQL Server. В большинстве случаев, даже после перезагрузки сервера, SQL Server начнет слушать тот же самый динамический TCP порт, который был назначен до перезагрузки. Но если этот порт занят, SQL Server запустится на новом порту TCP (приложение, которое использует SQL обычно без проблем получит номер нового порта от службы SQL Server Browser, об этом чуть ниже). Динамический порты SQLServer удобны с точки зрения простоты администрирования нескольких экземпляров SQL на одном сервере, но вызывают множество проблем, если в вашей сети используются межсетевые экраны.
Изменение номера TCP порта экземпляра SQL Server
Вы можете перенастроить ваш сервер так, чтобы он слушал на другом статическом TCP или динамическом порту. Как правило это нужно, когда на одном SQL Server-e запушено несколько экземпляров, или у вас используются межсетевые экраны.
Для управления портами подключения нам потребуется SQL Server Configuration Manager. Обычно эта оснастка устанавливается вместе с экземпляром MSSQL.
Запустите SQL Server Configuration Manager и разверните секцию SQL Server Network Configuration.
В моём случае на сервере установлен всего 1 экземпляр MSSQL– NODE1, поэтому настраивать порты я буду для него. В списке доступных протоколов для данного экземпляра имеются:
- Протокол Shared Memory используется для подключения с локального компьютера (с того, где установлен экземпляр MSSQL). Отключать его не рекомендуется;
- Named Pipes может использоваться по протоколу TCP/IP, но его использования не несёт особой выгоды, поэтому оставим его выключенным;
- TCP/IP – именно здесь настраиваются сетевые параметры MSSQL.

Щелкните дважды по TCP/IP.

На вкладке Protocol всего 3 параметра:
- Enabled – убедитесь, что протокол TCP/IP включен;
- Keep Alive – частота проверки того, что соединение еще актуально (в миллисекундах). Не меняйте этот параметр без необходимости;
- Listen All – неочевидная настройка, которая отвечает за секцию IPAll во вкладке IP Addresses. Если Listen All выставлена в No, то секция IPAll будет игнорироваться.
На вкладке IP Addresses вы увидите перечисление всех IP адресов машины (включая IPv6 и локальные) и соответствующие им настройки. Здесь вы можете задать разные TCP порты для локального и внешнего адреса подключения, или разные порты для разных внешних адресов (если у вас сервер с несколькими сетевыми интерфейсами в разных сегментах).

Скорее всего вы захотите изменить порт сразу для всех IP, поэтому нужно изменить его секции IPAll.

Параметр TCP Dynamic Ports отвечает за использование динамических портов.
- Пустое значение TCP Dynamic Ports отключает использование динамических портов SQL Server;
- 0 включает использование динамических TCP портовиз диапазона RPC 49152 – 65535;
- Выставлять здесь конкретное значение не имеет смысла – оно меняется каждый раз при перезагрузке экземпляра MSSQL.
Чтобы установить статический TCP порт для данного экземпляра SQL Server, отключите TCP Dynamic Ports, и задайте новый номер статического порта в параметре TCP Port.

Для применения изменений перезапустите службу SQL Server. Обратите внимание на отключенную службу SQL Server Browser.

Проверьте, что теперь к вашему экземпляру SQL можно подключиться через SSMS. Формат строки подключения такой:

Подключиться без указания порта не получится, поскольку SQL Browser выключен.
TCP порты и служба SQL Server Browser
До версии MSSQL 2000 нельзя было установить больше одного экземпляра СУБД на один компьютер. Такая возможность появилась в более новых версиях MSSQL. Служба SQL Server Browser впервые появилась в SQL Server 2005 и использовалась как посредник для распределения подключений между различными экземплярами MSSQL, установленными на одном компьютере.
Также SQL Server Browser отвечает за подключение к MSSQL (например, из SQL Server Management Studio) без указания порта, например testnode1\node1 . Служба SQL Server Browser узнает номер текущего динамического порта экземпляра из реестра и сообщает его клиенту.
Если вы отключите службу SQL Server Browser, то для подключения к экземпляру необходимо вручную указывать TCP порт. Например, testnode1\node1, 1440 .
При отключенной службе SQL Server Browser и использовании динамических портов приложения не смогут узнать номер порта, к которому нужно обращаться.
Стандартные порты SQL Server
- TCP 1433 — Стандартный порт SQL Server
- UDP 1433 – порт, используемый SQL Server Browser
Другие порты настраиваются при установке/настройке конкретного сервиса. Так что по умолчанию, Вам достаточно открыть в файерволе только два порта: 1433 TCP/UDP.
Если у вас используются строгие настройки фаервола, или если вы хотите максимально ограничить SQL Server, рекомендуется отключить Dynamic Ports (выставить пустое значение) и отключить службу SQL Server Browser.
Если же ваши SQL Server’a находятся в публичном доступе, то будет хорошей идеей поменять порт на нестандартный. Это не защитит от атак полностью, но снизит их число.
Предыдущая статья Следующая статья