Skip to main content

How to Fix TCP Socket Error Code 10061 in C++, Python, and Java

If you are interested in my TCP socket software development, consulting or training services, please feel free to contact me.  

contact email: tcpfast@gmail.com


TCP  socket error code 10061 is a common network connection error that indicates that the target server refused the connection request. This usually happens when you try to connect to a service that is not running on the target host, or when your network firewall or antivirus software blocks the port communication. In this blog post, I will explain the possible causes of this error and how to fix it in different programming languages, such as C++, Python, and Java.


Possible Causes of TCP Socket Error Code 10061

There are several possible reasons why you may encounter TCP error code 10061 when you try to establish a TCP connection with a server. Some of the most common ones are:

- You are using the wrong port number or protocol type (TCP or UDP) to connect to the server. For example, if the server is listening on port 80 using TCP, but you try to connect to port 81 using UDP, you will get this error.

- Your Windows firewall or other firewall software is blocking the port communication between your client and the server. For example, if the server is listening on port 80 using TCP, but your firewall does not allow outgoing TCP connections on port 80, you will get this error.

- The server is not running the service that you are trying to connect to, or the service is not listening on the port that you are trying to connect to. For example, if the server is supposed to run a web server on port 80 using TCP, but the web server is not started, or it is listening on a different port, you will get this error.


How to check the rules of firewall software?

Check if your Windows firewall or other firewall software is allowing the port communication between your client and the server. You can use the Windows Firewall with Advanced Security console to configure the firewall rules for your application, or temporarily disable the firewall to test the connection. You can also use the `netsh` command to manage the firewall settings from the command prompt. 

For example, the following command allows outgoing TCP connections on port 80:

cmd

  1. netsh advfirewall firewall add rule name="Allow TCP 80" dir=out action=allow protocol=TCP localport=80


Check

If the server is running the service that you are trying to connect to, or the service is listening on the port that you are trying to connect to. You can use the `telnet` command to test the connection to the server from the command prompt. For example, the following command tries to connect to a web server on port 80:

cmd

  1. telnet www.example.com 80


If the connection is successful, you will see a blank screen. If the connection is refused, you will see an error message like this:

Connecting To www.example.com...Could not open connection to the host, on port 80: Connect failed


You can also use the `netstat` command to check the listening ports on the server from the command prompt. For example, the following command shows the listening TCP ports on the server:


cmd

  1. netstat -an | findstr /i "tcp" | findstr /i "listen"


If the server is listening on port 80, you will see a line like this:

    TCP    0.0.0.0:80             0.0.0.0:0              LISTENING


How to Fix TCP Socket Error Code 10061 in C++

In C++, you can use the `WSAGetLastError()` function to get the last error code that occurred during a socket operation. If the error code is 10061, you can use the following steps to troubleshoot and fix the problem:

Check if you are using the correct port number and protocol type (TCP or UDP) to connect to the server. You can use the `getaddrinfo()` function to get the address information of the server, and the `socket()` function to create a socket with the appropriate protocol type. For example, the following code snippet creates a TCP socket and connects to a server on port 80:

C++ demo: 

  1. #include <iostream>
  2. #include <winsock2.h>
  3. #include <ws2tcpip.h>
  4. #pragma comment(lib, "ws2_32.lib")
  5. int main()
  6. {
  7.     // Initialize Winsock
  8.     WSADATA wsaData;
  9.     int iResult = WSAStartup(MAKEWORD(22), &wsaData);
  10.     if (iResult != 0) {
  11.         std::cout << "WSAStartup failed: " << iResult << std::endl;
  12.         return 1;
  13.     }
  14.     // Get the address information of the server
  15.     struct addrinfo *result = NULL, *ptr = NULLhints;
  16.     ZeroMemory(&hints, sizeof(hints));
  17.     hints.ai_family = AF_UNSPEC; // Use either IPv4 or IPv6
  18.     hints.ai_socktype = SOCK_STREAM; // Use TCP
  19.     hints.ai_protocol = IPPROTO_TCP; // Use TCP
  20.     iResult = getaddrinfo("www.example.com""80", &hints, &result);
  21.     if (iResult != 0) {
  22.         std::cout << "getaddrinfo failed: " << iResult << std::endl;
  23.         WSACleanup();
  24.         return 1;
  25.     }
  26.     // Create a socket and connect to the server
  27.     SOCKET ConnectSocket = INVALID_SOCKET;
  28.     for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
  29.         // Create a socket
  30.         ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
  31.         if (ConnectSocket == INVALID_SOCKET) {
  32.             std::cout << "socket failed: " << WSAGetLastError() << std::endl;
  33.             WSACleanup();
  34.             return 1;
  35.         }
  36.         // Connect to the server
  37.         iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
  38.         if (iResult == SOCKET_ERROR) {
  39.             std::cout << "connect failed: " << WSAGetLastError() << std::endl;
  40.             closesocket(ConnectSocket);
  41.             ConnectSocket = INVALID_SOCKET;
  42.             continue;
  43.         }
  44.         break;
  45.     }
  46.     freeaddrinfo(result);
  47.     if (ConnectSocket == INVALID_SOCKET) {
  48.         std::cout << "Unable to connect to server" << std::endl;
  49.         WSACleanup();
  50.         return 1;
  51.     }
  52.     // Do some communication with the server
  53.     // ...
  54.     // Close the socket and clean up
  55.     closesocket(ConnectSocket);
  56.     WSACleanup();
  57.     return 0;
  58. }


How to Fix TCP Socket Error Code 10061 in Python ?

In Python, you can use the `socket` module to create and manage sockets. If you encounter TCP error code 10061 when you try to connect to a server, you can use the following steps to troubleshoot and fix the problem:

Check if you are using the correct port number and protocol type (TCP or UDP) to connect to the server. You can use the `socket.getaddrinfo()` function to get the address information of the server, and the `socket.socket()` function to create a socket with the appropriate protocol type. For example, the following code snippet creates a TCP socket and connects to a server on port 80:


Python Demo:

  1. import socket
  2. # Get the address information of the server
  3. host = "www.example.com"
  4. port = 80
  5. addr_info = socket.getaddrinfo(host, port, family=socket.AF_UNSPEC, type=socket.SOCK_STREAM, proto=socket.IPPROTO_TCP)
  6. if not addr_info:
  7.     print("getaddrinfo failed")
  8.     exit(1)
  9. # Create a socket and connect to the server
  10. sock = None
  11. for addr in addr_info:
  12.     try:
  13.         # Create a socket
  14.         sock = socket.socket(addr[0], addr[1], addr[2])
  15.         if not sock:
  16.             print("socket failed")
  17.             exit(1)
  18.         # Connect to the server
  19.         sock.connect(addr[4])
  20.         break
  21.     except socket.error as e:
  22.         print("connect failed:", e)
  23.         sock.close()
  24.         sock = None
  25.         continue
  26. if not sock:
  27.     print("Unable to connect to server")
  28.     exit(1)
  29. # Do some communication with the server
  30. # ...
  31. # Close the socket
  32. sock.close()


How to Fix TCP Error Socket Code 10061 in Java ?

Java Demo:

  1. import java.io.IOException;
  2. import java.net.InetAddress;
  3. import java.net.InetSocketAddress;
  4. import java.net.Socket;
  5. import java.net.UnknownHostException;
  6. public class TCPClient {
  7.     public static void main(String[] args) {
  8.         // The host name and port number of the server
  9.         String host = "www.example.com";
  10.         int port = 80;
  11.         // Create a socket object
  12.         Socket socket = new Socket();
  13.         try {
  14.             // Get the IP address of the server
  15.             InetAddress address = InetAddress.getByName(host);
  16.             // Create a socket address object with the IP address and port number
  17.             InetSocketAddress socketAddress = new InetSocketAddress(address, port);
  18.             // Connect to the server with a timeout of 10 seconds
  19.             socket.connect(socketAddress, 10000);
  20.             // Do some communication with the server
  21.             // ...
  22.             // Close the socket
  23.             socket.close();
  24.             System.out.println("Connection successful");
  25.         } catch (UnknownHostException e) {
  26.             // The host name could not be resolved
  27.             System.out.println("Unknown host: " + e.getMessage());
  28.         } catch (IOException e) {
  29.             // There was an input/output error or the connection was refused
  30.             System.out.println("Connection failed: " + e.getMessage());
  31.         }
  32.     }
  33. }

If you are interested in my TCP socket software development, consulting or training services, please feel free to contact me.  

contact email: tcpfast@gmail.com


Comments

Popular posts from this blog

How to Set Buffer Size for TCP Socket Programming in C++

TCP socket programming is a common way to communicate between different processes or machines over the network. However, one of the challenges of TCP socket programming is how to set the buffer size for sending and receiving data. The buffer size determines how much data can be stored in memory before it is transmitted or processed. If the buffer size is too small, the data may be fragmented or lost, resulting in poor performance or errors. If the buffer size is too large, the memory may be wasted or the data may be delayed, affecting the responsiveness or timeliness of the communication. In this blog post, I will explain how to set the buffer size for TCP socket programming in C++, and provide some examples of how to use the relevant functions and parameters. The buffer size for TCP socket programming in C++ can be set by using the setsockopt function, which allows the programmer to change the options for a socket. The setsockopt function has the following prototype: int setsockopt...

Example: A TCP Socket Echo Server in Python

Introduction TCP (Transmission Control Protocol) is one of the most widely used protocols in the Internet. It provides reliable, ordered, and error-checked delivery of data between applications running on different devices. A TCP socket is an endpoint of a TCP connection, which is identified by an IP address and a port number. A TCP socket can send and receive data to and from another TCP socket over the network. In this article, I will show you how to write a simple TCP socket echo server in Python, which is a program that listens for incoming connections from TCP socket clients, and echoes back whatever data it receives from them. This program can be useful for testing the functionality and performance of TCP sockets, as well as learning the basics of socket programming in Python. Requirements To write and run this program, you will need the following: - A computer with Python 3 installed. You can download Python 3 from [here]. - A text editor or an IDE (Integrated Development Enviro...

How to Capture and Modify TCP Packets Using Npcap Library in C

email:  tcpfast@gmail.com  In this blog post, I will show you how to use the pcap library in C to capture and modify TCP packets on the fly. The pcap library is a powerful tool for network analysis and manipulation, which allows you to access raw packets from various network interfaces. You can use the pcap library to implement your own network applications, such as firewalls, proxies, sniffers, etc. The Code The code I will use as an example is as follows: # include <stdio.h> # include <stdlib.h> # include <pcap.h> # include <Packet32.h> # include <ntddndis.h> # define MAX_PACKET_SIZE 65536 # define KEYWORD "keyword1" # define IP1 "192.168.0.1" # define PORT1 12345 void packet_handler (u_char* user_data, const struct pcap_pkthdr* pkthdr, const u_char* packet) ; int main () { pcap_t * handle; char errbuf[PCAP_ERRBUF_SIZE]; // Open the network adapter handle = pcap_open_live( "\\Device\\...