Linux tcp connection refused

How to Fix a Client/Server Connection Refused Using netcat?

Netcat, or nc, is a versatile utility of Linux command line that allows users to read and write data across networks. It is mostly used for network troubleshooting and provides the simplest way to transfer files using the UDP and TCP protocols. While working with it, some users reported a “Connection refused” error from the client side.

This guide explains the multiple reasons and possible fixes for the client/server connection refused error using netcat.

  • What Causes the Connection Refused Error While Using the netcat Command?
  • Reason 1: netstat Utility is not Installed
  • Solution: Install the netstat Command on Linux
  • Reason 2: The Listening Port is Closed
  • Solution: Configure Port for Establish Connection

Reason 1: Connection Refused Error While Using the netcat Command?

If the error “Connection refused” comes up while trying to use the netcat command to connect to a remote server, it means the server is not accepting the connection. This is because the port is closed.

Another reason could be that the netstat utility is not installed on the remote server.

Solution: Install the netstat Command on Linux

To install the netstat command, use the following commands based on your distro:

$ sudo apt install netcat #Ubuntu/Debian $ sudo yum install nc #CentOS/RHEL $ sudo dnf install nc #Fedora

The above image confirms the installation of netcat on Ubuntu 22.04.

Reason 2: Connection Refused Error While Using the netcat Command?

To fix the “Connection Refused” error while using the netcat command, determine the cause first; there could be multiple causes, as discussed below.

Verify if the Server is Running

To check if the server is up and listening to the specific port, understand this command before executing it:

  • The option -z specifies the netstat command to scan for the ports.
  • -v enables the verbose mode to display additional information.
  • -n instructs the netstat command to perform DNS lookup on the following IP.
  • 2>&1 is there to print the errors.
$ netcat -z -v -n 192.168.222.135 1200-5000 2>&1

In the above image, all the ports from 1200-5000 are closed for communication.

Let’s set up a port for the netcat to use by executing this command and here:

  • -l sets the netstat to listening mode.
  • -p specifies the port on which the netstat command will listen.

The above command opens up a port “1234” for the netcat command to use.

Now open up another terminal session, and use the ip command to find the IP address of the server:

Once the IP is viewed, share it with the client, and on the client side, use the netcat command like this to connect:

The connection is now established, and you can now use the netcat command to perform various operations discussed in this guide with detail.

Читайте также:  Linux intel mesa drivers

Conclusion

To fix the client/server connection refused using netcat, the port on the server must be opened to listen to the client. To do this, the command “nc -l -p ” is executed, and from the client side, the command “nc ” is used. This fixes the error “Connection Refused” while the netcat command is being used.

This guide explained the reason for the client/server connection refused error using netcat and fixed it.

TUTORIALS ON LINUX, PROGRAMMING & TECHNOLOGY

Источник

Connection refused

TCP connections fail to establish for a number of reasons: congestion in the network, incorrect destination ( ip:port ), incompatible firewall rules, busy server, etc. Two common failures you’ll see are Connection refused and Connection timed out . Let’s look at Connection refused in greater detail.

In a nutshell:
Connection refused means “I heard back from the host, and the host isn’t allowing me to connect”.
Connection timed out means “I didn’t hear back from the host.”

The important take-away here is the connection refused tells you a bunch of things: — the target host exists and is reachable over the network — the target is not dropping your request packets — the target is responding with a TCP packet, most likely with the RST flag set. — the target either isn’t listening on the specified port, or is refusing to take new connections on that port.

By contrast, connection timed out means you didn’t hear any response back from the host before some arbitrary timer expired. You might explicitly set a timeout, or you could have one built into whatever tool / request library you’re using.

Connection Refused : I’m explicitly not taking connections

Let’s look at a successful HTTP request to a port where nginx is listening for new connections:

 ❯ curl -I 127.0.0.1:80 HTTP/1.1 200 OK . 

and an unsuccessful request to a port where nothing is listening:

 ❯ curl -I 127.0.0.1:81 curl: (7) Failed to connect to 127.0.0.1 port 81: Connection refused 

The above (failed) request to port 81 returns immediately, even though it didn’t successfully establish a connection. To see why, we can look at what’s happening at the TCP layer in the successful and unsuccessful cases.

Let’s capture one half of the TCP conversation during the successful request to port 80 using tcpdump . We’ll snoop traffic on the loopback interface ( lo ) since we’re issuing the request locally via 127.0.0.1 (ie, the request never actually hits a real network interface). curl will issue the request using some high numbered ephemeral port given to it by the kernel, but the request destination will be 127.0.0.1:80 . Similarly, responses will originate from 127.0.0.1:80 , so we can monitor the traffic that is issued from source port 80 to see the response half of the conversation:

 ❯ sudo tcpdump -i lo -n src port 80 # meanwhile, issue `curl -I 127.0.0.1:80` . 20:56:37.780057 IP 127.0.0.1.80 > 127.0.0.1.45522: Flags [S.], seq 657845710, ack 1014454379, win 43690, options [mss 65495,sackOK,TS val 278491 ecr 278491,nop,wscale 6], length 0 20:56:37.781185 IP 127.0.0.1.80 > 127.0.0.1.45522: Flags [.], ack 75, win 683, options [nop,nop,TS val 278491 ecr 278491], length 0 20:56:37.782287 IP 127.0.0.1.80 > 127.0.0.1.45522: Flags [P.], seq 1:240, ack 75, win 683, options [nop,nop,TS val 278492 ecr 278491], length 239 20:56:37.797218 IP 127.0.0.1.80 > 127.0.0.1.45522: Flags [F.], seq 240, ack 76, win 683, options [nop,nop,TS val 278495 ecr 278493], length 0 

Look at the TCP flags set on the response packets: — [S.] : SYN + ACK — this is part of the three way handshake to establish the TCP connection) — [.] : ACK — this ACK acknowledges the request from curl — [P.] : PUSH + ACK — this packet contains the HTTP response, pushed without TCP buffering by nginx — [F.] : FIN + ACK — cleanly terminate the connection

Читайте также:  Can linux see windows files

Now contrast this with the results curling to a port ( 81 ) where no process is listening:

 ❯ sudo tcpdump -i lo -n src port 81 # meanwhile, issue `curl -I 127.0.0.1:81` 21:10:24.508842 IP 127.0.0.1.81 > 127.0.0.1.44138: Flags [R.], seq 0, ack 404185781, win 0, length 0 

In this case, we see a single response packet with a 0-length data payload and the [R.] flags (RESET + ACK). The reset flag notifies the connecting client that the connection will be immediately destroyed. In this case, since no TCP handshake was ever completed, it tells the client that the server will not be establishing the requested connection.

The Response is from the Kernel

Consider the fact that no process is actually bound to port 81. This means that the operating system alone must be issuing the reset packet; in fact, connection management in Linux is completely handled by the kernel’s TCP stack in either case (successful handshake or otherwise) before the connection is handed off to the application at all.

We can observe this with a bit of strace -ing in the positive case. I’ll attach strace to nginx and its worker processes, filtering for system calls by nginx to accept inbound IPv4 connections. I’ll also use -tt to print the wall-clock time in microseconds. At the same time, I’ll capture a tcpdump so we can compare the order of operation:

 # set up tcpdump ❯ sudo tcpdump -i lo -n src port 80 
 # in another terminal, set up strace ❯ pgrep nginx 345 346 347 348 351 ❯ sudo strace -f -p 345,346,347,348,351 -e trace=accept4 -tt 
 # in a third terminal, issue the curl ❯ curl -I 127.0.0.1:80 

Interleaving the strace and tcpdump results in chronological order, we get:

 21:25:57.939622 IP 127.0.0.1.80 > 127.0.0.1.45542: Flags [S.], seq 3721359522, ack 2397758014, win 43690, options [mss 65495,sackOK,TS val 630523 ecr 630523,nop,wscale 6], length 0 [pid 346] 21:25:57.940386 accept4(6, sa_family=AF_INET, sin_port=htons(45542), sin_addr=inet_addr("127.0.0.1")>, [16], SOCK_NONBLOCK) = 12 21:25:57.943629 IP 127.0.0.1.80 > 127.0.0.1.45542: Flags [.], ack 75, win 683, options [nop,nop,TS val 630524 ecr 630524], length 0 21:25:57.945494 IP 127.0.0.1.80 > 127.0.0.1.45542: Flags [P.], seq 1:240, ack 75, win 683, options [nop,nop,TS val 630524 ecr 630524], length 239 21:25:57.957252 IP 127.0.0.1.80 > 127.0.0.1.45542: Flags [F.], seq 240, ack 76, win 683, options [nop,nop,TS val 630527 ecr 630525], length 0 

The strace output clearly shows that nginx doesn’t actually accept(2) the connection until after the TCP stack replies with the SYN-ACK packet, indicating the connection is fully established.

Источник

Get rid of «connection refused» error in bash script

To keep using set -e but still allow a known error, use this incantation:

This uses the || operator to ‘consume’ the error so that it is deemed nonfatal to an environment in which set -e is active.

You’re already using 2>/dev/null to suppress standard error, so are you sure the error is coming from the line you cite here? Also, rather than using exec , I propose as a more readable alternative:

if ! nc -z localhost 9091 1> /dev/null 2>&1; then port_free="yes" fi 

Since the return code of nc is checked by the if statement, this is also safe after set -e .

thanks, I am not sure how to use the incantation in the context of the script above. my guess is /bin/false || exec 3<>/dev/tcp/127.0.0.1/9091 > /dev/null 2>&1 is that right? I think using netcat like you have is prob better, yes.

if I use set -e with the nc command you have in the if statement it will conk out, so I need to use /bin/false before the nc command.

@AlexanderMills he meant : code which ends up returning non zero || : (false is just an exemple of a code returning non-zero)

To properly redirect both the error and output streams to /dev/null, thereby suppressing the error message, you need to group the whole exec command:

< exec 3<>/dev/tcp/127.0.0.1/9091; > > /dev/null 2>&1 || PORT_IS_FREE=»yes»

exec is a shell builtin, so it is hard to predict for me how it will behave, however I assume that even though it is able to treat < and >specially, the whole operation is still carried out in several steps, the streams of only the last of which get redirected. Someone who knows more about the workings of exec might be able to shed some light on this.

EDIT: I do not know why you needed brace-grouping for your variable assignment since it’s a single command, but you can still use braces in conjunction with my examples if you want to, instead of the bare assignment I used.

As for ignoring the error, you could terminate the command after the redirection with ; instead of using its exit status via || :

< exec 3<>/dev/tcp/127.0.0.1/9091; > > /dev/null 2>&1 ; PORT_IS_FREE=»yes»

Of course, in this case, there is the issue that you will not be able to catch any other error either. I just tried and the exit status is 1 after the error in question happens. If other codes are returned on different errors (which I doubt actually, since 1 is a very generic error code), you could test for 1. EDIT: This solution also comes with the benefit of not exiting when code 1 is returned after the exec , when set -e is used:

< exec 3<>/dev/tcp/127.0.0.1/9091; > > /dev/null 2>&1 || [ «$?» = 1 ] && PORT_IS_FREE=»yes»

Otherwise, you might use grep to try and match the error message, which is more reliable in my opinion:

socketOpenOutput="$(< exec 3<>/dev/tcp/127.0.0.1/9091; > 2>&1`)" socketOpenErrorCode="$?" if [ "$socketOpenErrorCode" != 0 ]; then if ! echo "$socketOpenOutput" | grep 'connect\s*:\s*Connection refused' >/dev/null; then echo "An unexpected error happened when opening the socket!" exit 1 fi fi PORT_IS_FREE="yes" 

This one, however, does not work well with set -e .

Источник

Оцените статью
Adblock
detector