乐闻世界logo
搜索文章和话题

How to close TCP and UDP ports via windows command line

1个答案

1

In the Windows environment, if you need to block a specific TCP or UDP port, you cannot directly 'close' a port; instead, you need to block network activity on that port or stop the service or program using the port. Here are several methods you can achieve this via command line:

1. Block Ports via Firewall Rules

You can use Windows Firewall to block communication on specific ports. This can be achieved using the netsh command-line tool. For example, if you want to block incoming TCP port 8080, you can use the following command:

bash
netsh advfirewall firewall add rule name="BlockTCP8080" dir=in action=block protocol=TCP localport=8080

This command creates a new rule named "BlockTCP8080" that blocks all incoming connections to TCP port 8080.

2. Terminate the Process Using the Port

If a program is using the port you want to block, you can terminate the process to free up the port. First, identify which process is using the port using the following command:

bash
netstat -aon | findstr :8080

Here, 8080 is the port number you want to search for. This command lists all processes using port 8080, along with their Process ID (PID).

Once you have the PID, use the taskkill command to terminate the process:

bash

Where 1234 should be replaced with the actual PID obtained from the netstat command.

If a service (such as IIS service, SQL service, etc.) is using the port, you can disable the entire service via command line. First, find the service name using:

bash
sc query

After identifying the service, stop it with:

bash
net stop "service name"

Replace "service name" with the actual service name.

Example

Suppose you find that a service named "ExampleService" is using TCP port 8080 on your computer. You can perform the following actions:

  1. Verify the service is running:

    bash

sc query | findstr "ExampleService"

shell
2. Stop the "ExampleService" service: ```bash net stop "ExampleService"
  1. Add a firewall rule as a precaution:

    bash

netsh advfirewall firewall add rule name="BlockTCP8080" dir=in action=block protocol=TCP localport=8080

shell
This way, port 8080 is no longer used by "ExampleService", and the firewall adds additional security measures.
2024年7月7日 11:08 回复

你的答案