Linux free the port

Manually closing a port from commandline

I want to close an open port which is in listening mode between my client and server application.

Is there any manual command line option in Linux to close a port?

NOTE: I came to know that «only the application which owns the connected socket should close it, which will happen when the application terminates.»

I don’t understand why it is only possible by the application which opens it . But I’m still eager to know if there is any other way to do it.

15 Answers 15

I had same problem, the process must keep alive but the socket must close. Closing a socket in a running process is not impossible but difficult:

locate the process :

You get a source/destination ip:port portstate pid/processname map

locate the the socket’s file descriptor in the process

You get a list: process name, pid, user,fileDescriptor, . a connection string.

Locate the matching fileDescriptor number for the connection. It’ll be something like «97u» which means «97».

Now connect the process:

Now close the socket:

Then detach gdb:

And the socket is closed.

You’re kind of asking the wrong question here. It isn’t really possible to simply «close a port» from outside the application that opened the socket listening on it. The only way to do this is to completely kill the process that owns the port. Then, in about a minute or two, the port will become available again for use. Here’s what’s going on (if you don’t care, skip to the end where I show you how to kill the process owning a particular port):

Ports are resources allocated by the OS to different processes. This is similar to asking the OS for a file pointer. However, unlike file pointers, only ONE process at a time may own a port. Through the BSD socket interface, processes can make a request to listen on a port, which the OS will then grant. The OS will also make sure no other process gets the same port. At any point, the process can release the port by closing the socket. The OS will then reclaim the port. Alternatively, if the process ends without releasing the port, the OS will eventually reclaim the port (though it won’t happen immediately: it’ll take a few minutes).

Now, what you want to do (simply close the port from the command-line), isn’t possible for two reasons. First, if it were possible, it would mean one process could simply steal away another process’s resource (the port). This would be bad policy, unless restricted to privileged processes. The second reason is it is unclear what would happen to the process that owned the port if we let it continue running. The process’s code is written assuming that it owns this resource. If we simply took it away, it would end up crashing on it’s own, so OS’s don’t let you do this, even if you’re a privileged process. Instead, you must simply kill them.

Anyway, here’s how to kill a process that owns a particular port:

That will output the line corresponding to the process holding port , for example:

In this case, procHoldingPort is the name of the process that opened the port, 4683 is its pid, and 8000 (note that it is TCP) is the port number it holds.

Then, look in the last column, you’ll see /. Then execute this:

If that doesn’t work (you can check by re-running the netstat command). Do this:

In general, it’s better to avoid sending SIGKILL if you can. This is why I tell you to try kill before kill -9 . Just using kill sends the gentler SIGTERM.

Like I said, it will still take a few minutes for the port to re-open if you do this. I don’t know a way to speed this up. If someone else does, I’d love to hear it.

Источник

Ubuntu: How To Free Up Port 53, Used By systemd-resolved

Ubuntu has systemd-resolved listening on port 53 by default. In case you want to run your own DNS server, you can’t because port 53 is already in use, so you’ll get an error similar to this: «listen tcp 0.0.0.0:53: bind: address already in use».

This article explains how to stop systemd-resolved from using port 53 on Ubuntu. The instructions were tested on Ubuntu 20.04, but they should also work on other Ubuntu versions, e.g. Ubuntu 18.04, the upcoming Ubuntu 20.10, as well as Ubuntu-based Linux distributions like Pop!_OS, Zorin OS, Elementary OS, Linux Mint, and so on. Basically, this works on any system having systemd version 232 or newer.

To see if port 53 is in use on your system, use:

Читайте также:  Драйвера для установки принтера hp deskjet 2135

Example with output, showing that systemd-resolved is using port 53 on a default Ubuntu 20.04 system:

In case you don’t get any output, it means that port 53 is not in use.

How to stop systemd-resolved from using port 53 on Ubuntu

It’s worth noting that you can free up port 53 by simply uncommenting DNSStubListener and setting it to no in /etc/systemd/resolved.conf . The other steps are for enabling a DNS server — without it, your system will not be able to resolve any domain names, so you won’t be able to visit websites in web browser, etc.

1. Edit /etc/systemd/resolved.conf with a text editor (as root), e.g. open it with Nano console text editor:

And uncomment (remove # from the front of the line) the DNS= line and the DNSStubListener= line. Next, change the DNS= value in this file to the DNS server you want to use (e.g. 127.0.0.1 to use a local proxy, 1.1.1.1 to use the Cloudflare DNS, etc.), and also change the DNSStubListener= value from yes to no .

This is how the file should look after you’ve made these changes (I’m using 1.1.1.1 as the DNS server here, which is the Cloudflare DNS):

To save the file using Nano text editor, press Ctrl + x , then type y and press Enter .

2. Create a symbolic link for /run/systemd/resolve/resolv.conf with /etc/resolv.conf as the destination:

Here, -s is for creating a symbolic and not hard link, and -f is for removing any existing destination files (so it removes /etc/resolv.conf if it exists).

3. Reboot your system.

Port 53 should now be free on your Ubuntu system, and you shouldn’t be getting errors like «listen tcp 127.0.0.1:53: bind: address already in use» anymore.

You can check to see if port 53 is in use or not by running sudo lsof -i :53 — if port 53 is not in use, this command shouldn’t show any output.

How to undo the changes

Do you want to undo the changes made by following the instructions in this article? This is what you must do.

1. Start by editing /etc/systemd/resolved.conf with a text editor (as root), e.g. open it with Nano console text editor:

And comment out (add # in front of the line) DNS= and DNSStubListener=no , then save the file. To save the file using Nano text editor, press Ctrl + x , then type y and press Enter .

Источник

Linux command get unused port

I’m looking for a command or script which returns an unused port on my ubuntu linux system. I have look on internet and the only thing I find is about the used/Listen port with the nestat command. Apparently something with the netstat command will work but don’t know what exactly. Any idea how?

10 Answers 10

netstat -lat gives the complete list of listening and established ports.

When a port is not on any of those states doesn’t exist for the system, so you won’t find a command that shows the list of unused ports.

Keep in mind that there are 65535 ports, so anything that isn’t on netstat -lat is an unused port.

The following bash script will do a simple scan of tcp ports, and let you know which are open and which are closed :

If you save it as portscan.sh then it must be run as ./portscan.sh IP first_port last_port, for example: ./portscan.sh 127.0.0.1 20 135 will scan the local equipment from ports 20 to 135. Remember to make it executable with chmod +x portscan.sh .

Ruby 2.x (one-liner):

ruby -e ‘require «socket»; puts Addrinfo.tcp(«», 0).bind <|s| s.local_address.ip_port >‘

On my machine right now that printed:

A subsequent invocation printed:

This technique causes the current user to request an unused port (bind to port «0»), and then prints out the port number that the operating system provided. And since the current user is the one asking, ports below 1024 will not be returned (unless current user = root).

Credit where credit’s due — this solution comes from a comment by Franklin Yu on unix.stackexchange.com’s What’s the easiest way to find an unused local port?

Short bash script that randomly generates a number between 1025 and 60000 and loops until that number isn’t found in the list of used ports. This is a quick ‘n dirty solution that has a bias to larger ports:

One-liner

I’ve put together a nice one-liner that quickly serves the purpose, allowing to grab an arbitrary number of ports in an arbitrary range (here it’s divided in 4 lines for readability):

Line by line

comm is a utility that compares sorted lines in two files. It outputs three columns: lines that appear only in the first file, lines that only appear in the second one and common lines. By specifying -23 we suppress the latter columns and only keep the first one. We can use this to obtain the difference of two sets, expressed as a sequence of text lines. I learned about comm here.

The first file is the range of ports that we can select from. seq produces a sorted sequence of numbers from $FROM to $TO . The result is piped to comm as the first file using process substitution.

The second file is the sorted list of ports, that we obtain by calling the ss command (with -t meaning TCP ports, -a meaning all — established and listening — and -n numeric — don’t try to resolve, say, 22 to ssh ). We then pick only the fourth column with awk , which contains the local address and port. We use cut to split address and port with the : delimiter and keep only the latter ( -f2 ). ss also output an header, that we get rid of by grep ping for non-empty sequences of numbers that are no longer than 5. We then comply with comm ‘s requirement by sort ing numerically ( -n ) and getting rid of duplicates with uniq .

Читайте также:  Epson wf m5190 драйвер linux

Now we have a sorted list of open ports, that we can shuf fle to then grab the first «$HOWMANY» ones with head -n .

Example

Grab the three random open ports in the private range (49152-65535)

Источник

Open or close server ports

Open server ports for remote access

IMPORTANT: Making this application’s network ports public is a significant security risk. You are strongly advised to only allow access to those ports from trusted networks. If, for development purposes, you need to access from outside of a trusted network, please do not allow access to those ports via a public IP address. Instead, use a secure channel such as a VPN or an SSH tunnel. Follow these instructions to remotely connect safely and reliably.

By default, the Bitnami virtual machine’s firewall is configured to allow access on any port(s) required by the application and the SSH port. This implies that ports 80, 443 and 22 are usually open by default.

To open a different port:

Log in to the server console.

Check which firewall program is installed in your system:

If ufw is the firewall program enabled in your machine, execute the following command to open a different port, replacing the PORT placeholder with the number of the port to be opened:

If nft is the firewall program enabled in your machine, modify the /etc/nftables.conf file and add the following line inside the chain inbound block, replacing the PORT placeholder with the number of the port to be opened:

More information about modifying the firewall configuration is available on the nftables Wiki.

Close server ports and deny remote access

By default, the Bitnami virtual machine’s firewall is configured to allow access on any port(s) required by the application and the SSH port. This implies that ports 80, 443 and 22 are usually open by default.

To close an open port:

Log in to the server console.

Check which firewall program is installed in your machine:

If ufw is the firewall program enabled in your machine, execute the following command to close a port, replacing the PORT placeholder with the number of the port to be closed:

More information about modifying the firewall configuration is available on the Debian Wiki.

If nft is the firewall program enabled in your machine, modify the /etc/nftables.conf file and modify the following line inside the chain inbound block, replacing the PORT placeholder with the number of the port to be opened:

Replace the line and remove the port to be opened:

More information about modifying the firewall configuration is available on the nftables Wiki.

Источник

Opening a port on Linux

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Before we learn about opening a port on Linux, let’s understand what network ports are. A port is a communication endpoint. Within an operating system, a port allows the data packets specific processes or network services.

Typically, ports identify a specific network service assigned to them. This can be changed by manually configuring the service to use a different port, but in general, the defaults can be used.

The first 1024 ports (Ports 0-1023) are referred to as well-known port numbers and are reserved for the most commonly used services include SSH (port 22), HTTP and HTTPS (port 80 and 443), etc. Port numbers above 1024 are referred to as ephemeral ports.

Among ephemeral ports, Port numbers 1024-49151 are called the Registered/User Ports. The rest of the ports, 49152-65535 are called as Dynamic/Private Ports.

In this tutorial, we will show how we can open an ephemeral port on Linux, since the most common services use the well-known ports.

List all open ports

Before opening a port on Linux, let us first check the list of all open ports, and choose an ephemeral port to open from that list.

We can use the netstat command to list all open ports, including those of TCP, UDP, which are the most common protocols for packet transmission in the network layer.

NOTE: If your distribution doesn’t have netstat , it is not a problem. You can use the ss command to display open ports via listening sockets.

This will print all listening sockets ( -l ) along with the port number ( -n ), with TCP ports ( -t ) and UDP ports ( -u ) also listed in the output.

List Open Ports

Just to ensure that we are getting consistent outputs, let’s verify this using the ss command to list listening sockets with an open port.

List Listening Sockets

This gives more or less the same open ports as netstat , so we are good to go!

Opening a port on Linux to Allow TCP Connections

Let’s open a closed port and make it listen to TCP Connections, for the sake of this example.

Since port 4000 is not being used in my system, I choose to open port 4000. If that port is not open in your system, feel free to choose another closed port. Just make sure that it’s greater than 1023!

Читайте также:  Postgresql psql from file

Again, just to make sure, let’s ensure that port 4000 is not used, using the netstat or the ss command.

The output must remain blank, thus verifying that it is not currently used, so that we can add the port rules manually to the system iptables firewall.

For Ubuntu Users and ufw firewall based Systems

Ubuntu has a firewall called ufw , which takes care of these rules for ports and connections, instead of the old iptables firewall. If you are a Ubuntu user, you can directly open the port using ufw

You can skip the next few steps, and directly test your newly opened port!

For CentOS and firewalld based Systems

For these types of systems, if you have firewalld as your primary firewall, it is recommended that you use the firewall-cmd to update your firewall rules, instead of the old iptables firewall.

NOTE: This will reset the firewalld rules to default on a reboot, so if you want to modify this setting permanently, add the —permanent flag to the command.

You can skip the next few steps, and directly test your newly opened port!

For Other Linux Distributions

So let’s add this new port to our system iptables rules, using the iptables command.

If this command is not yet installed, get it using your package manager.

This sets the firewall to append ( -A ) the new rule to accept input packets via protocol ( -p ) TCP where the destination port ( —dport ) is 4000, and specifies the target jump ( -j ) rule as ACCEPT.

To update the firewall rules, restart the iptables service.

OR using systemctl if you have it.

Test the newly opened port for TCP Connections

Now that we have successfully opened a new TCP port (Port 4000 in my case), let’s test it out.

First, we will start netcat ( nc ) and listen on port 4000, while sending the output of ls to any connected client. So after a client has opened a TCP connection on port 4000, they will receive the output of ls .

This makes netcat listen on port 4000. Leave this session alone for now.

Open another terminal session on the same machine.

Since I’ve opened a TCP port, I’ll use telnet to check for TCP Connectivity. If the command doesn’t exists, again, install it using your package manager.

Format for telnet:

So input your server IP and the port number, which is 4000 in my case, and run this command.

This tries to open a TCP connection on localhost on port 4000.

You’ll get an output similar to this, indicating that a connection has been established with the listening program ( nc ).

Check Port Using Telnet

As you can see, the output of ls ( while.sh in my case) has also been sent to the client, indicating a successful TCP Connection!

To show you that the port is indeed open, we can use nmap to check this.

Check Open Port

Indeed, our port has been opened! We have successfully opened a new port on our Linux system!

NOTE: nmap only lists opened ports which have a currently listening application. If you don’t use any listening application such as netcat, this will display the port 4000 as closed, since there isn’t any application listening on that port currently. Similarly, telnet won’t work either, since it also needs a listening application to bind to. This is the reason why nc is such a useful tool. This simulates such environments in a simple command.

But this is only temporary, as the changes will be reset every time we reboot the system.

Need to update rules after every reboot

The approach presented in this article will only temporarily update the firewall rules until the system shuts down/reboots. So similar steps must be repeated to open the same port again after a restart.

For ufw Firewall

The ufw rules are not reset on reboot, so if you’re a Ubuntu user, you need not worry about this part!

This is because it is integrated into the boot process and the kernel saves the firewall rules using ufw , via appropriate config files.

For firewalld

As mentioned earlier, firewalld also suffers from the same problem, but this can be avoided by appending a —permananent flag to the initial command, when opening a port or setting any other rule.

For example, you can open the TCP Port 4000 permanently using the below command:

For iptables

For the iptables firewall, although this inconvenience cannot be avoided, we could minimize the hassle.

We can save the iptables rules to a config file, such as /etc/iptables.conf .

We can then retrieve it from the config file after we reboot, using the below command:

Now, the iptables rules are now updated, and our ports are opened again!

Conclusion

In this tutorial, we showed you how you could open a new port on Linux and set it up for incoming connections.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Источник

КомпСовет