Ошибка сокета 10048

I’m trying to create a very basic server in python that listens in on a port, creates a TCP connection when a client tries to connect, receives data, sends something back, then listens again (and repeats the process indefinitely). This is what I have so far:

from socket import *

serverName = "localhost"
serverPort = 4444
BUFFER_SIZE = 1024

s = socket(AF_INET, SOCK_STREAM)
s.bind((serverName, serverPort))
s.listen(1)

print "Server is ready to receive data..."

while 1:
        newConnection, client = s.accept()
        msg = newConnection.recv(BUFFER_SIZE)

        print msg

        newConnection.send("hello world")
        newConnection.close()

Sometimes this seems to work perfectly well (if I point my browser to «localhost:4444» the server prints out the HTTP GET request and the webpage print the text «hello world»). But I’m getting the following error message sporadically when I try to start the server after closing it in the last few minutes:

Traceback (most recent call last):
  File "path\server.py", line 8, in <module>
    s.bind((serverName, serverPort))
  File "C:\Python27\lib\socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
error: [Errno 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted

I’m programming in python using Windows 7. Any ideas on how to fix this?

I started with the simple server tutorial on the msdn website in order to learn how to use sockets in client and server applications.

Once I was done following thet tutorial, I started adapting the client and server code into multithreaded proggrams in order to make a tchat client and server. Everything was going very well until I ran into WSA error 10048. I tried using different ports for each socket but it still did not solve the error.

Here is my server code :

#undef UNICODE

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <thread>
#include <vector>

// Need to link with Ws2_32.lib
#pragma comment (lib, "Ws2_32.lib")
// #pragma comment (lib, "Mswsock.lib")

//Global values
//I put them as global values in order to get the server up and running.
//I will try to pass them as params later on
int iResult;
struct addrinfo *result = NULL;
struct addrinfo hints;
int numClients = 0;
SOCKET ClientSocket[5];
std::thread** sendReceiveThread = new std::thread*[5];

//Prototypes
int listen(SOCKET ListenSocket);
int accept(SOCKET ListenSocket);
int sendReceive();
int shutdownFunction(SOCKET ClientSocket);

#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT1 "1016"
#define DEFAULT_PORT2 "1017"
#define DEFAULT_PORT3 "1018"
#define DEFAULT_PORT4 "1019"
#define DEFAULT_PORT5 "1020"

int main()
{
    std::cout << 1 << std::endl;
    WSADATA wsaData;

    SOCKET ListenSocket = INVALID_SOCKET;


    // Initialize Winsock
    std::cout << 2 << std::endl;
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0) {
        std::cout << 3 << std::endl;
        printf("WSAStartup failed with error: %d\n", iResult);
        return 1;
    }

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;

    std::thread ListenThread{ [ListenSocket](){listen(ListenSocket); } };
    ListenThread.join();

    return 0;
}

int listen(SOCKET ListenSocket)
{
    int numPort = 1;
    std::vector<std::thread*> thread_vec;
    while (true)
    {
        if (numPort == 1)
        {
            // Resolve the server address and port
            std::cout << 4 << std::endl;
            iResult = getaddrinfo(NULL, DEFAULT_PORT1, &hints, &result);
            numPort++;
            if (iResult != 0) {
                std::cout << 5 << std::endl;
                printf("getaddrinfo failed with error: %d\n", iResult);
                WSACleanup();
                break;
            }
        }

        else if (numPort == 2)
        {
            // Resolve the server address and port
            std::cout << 4 << std::endl;
            iResult = getaddrinfo(NULL, DEFAULT_PORT2, &hints, &result);
            numPort++;
            if (iResult != 0) {
                std::cout << 5 << std::endl;
                printf("getaddrinfo failed with error: %d\n", iResult);
                WSACleanup();
                break;
            }
        }

        else if (numPort == 3)
        {
            // Resolve the server address and port
            std::cout << 4 << std::endl;
            iResult = getaddrinfo(NULL, DEFAULT_PORT3, &hints, &result);
            numPort++;
            if (iResult != 0) {
                std::cout << 5 << std::endl;
                printf("getaddrinfo failed with error: %d\n", iResult);
                WSACleanup();
                break;
            }
        }

        else if (numPort == 4)
        {
            // Resolve the server address and port
            std::cout << 4 << std::endl;
            iResult = getaddrinfo(NULL, DEFAULT_PORT4, &hints, &result);
            numPort++;
            if (iResult != 0) {
                std::cout << 5 << std::endl;
                printf("getaddrinfo failed with error: %d\n", iResult);
                WSACleanup();
                break;
            }
        }

        else if (numPort == 5)
        {
            // Resolve the server address and port
            std::cout << 4 << std::endl;
            iResult = getaddrinfo(NULL, DEFAULT_PORT5, &hints, &result);
            numPort++;
            if (iResult != 0) {
                std::cout << 5 << std::endl;
                printf("getaddrinfo failed with error: %d\n", iResult);
                WSACleanup();
                break;
            }
        }

        // Create a SOCKET for connecting to server
        std::cout << 6 << std::endl;
        ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
        if (ListenSocket == INVALID_SOCKET) {
            std::cout << 7 << std::endl;
            printf("socket failed with error: %ld\n", WSAGetLastError());
            freeaddrinfo(result);
            WSACleanup();
            break;
        }

        // Setup the TCP listening socket
        std::cout << 8 << std::endl;
        iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
        if (iResult == SOCKET_ERROR) {
            std::cout << 9 << std::endl;
            printf("bind failed with error: %d\n", WSAGetLastError());
            freeaddrinfo(result);
            closesocket(ListenSocket);
            WSACleanup();
            break;
        }

        freeaddrinfo(result);

        std::cout << 10 << std::endl;
        iResult = listen(ListenSocket, SOMAXCONN);
        if (iResult == SOCKET_ERROR) {
            std::cout << 11 << std::endl;
            printf("listen failed with error: %d\n", WSAGetLastError());
            closesocket(ListenSocket);
            WSACleanup();
            break;
        }


        static std::thread AcceptThread{ [ListenSocket](){accept(ListenSocket); } };
        thread_vec.push_back(&AcceptThread);
    }
    for (auto it : thread_vec) it->join();
    return 0;
}

int accept(SOCKET ListenSocket)
{
    numClients++;
    const int currentNumClients = numClients;
    for (int i = 0; i <= 5; i++)
    {
        ClientSocket[i] = INVALID_SOCKET;
    }

    // Accept a client socket
    std::cout << 12 << std::endl;

    std::cout << 13 << std::endl;

    ClientSocket[currentNumClients] = accept(ListenSocket, NULL, NULL);
    if (ClientSocket[currentNumClients] == INVALID_SOCKET)
    {
        printf("accept failed with error: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    sendReceiveThread[currentNumClients] = new std::thread([](){sendReceive(); });
    (*sendReceiveThread[currentNumClients]).join();
    delete sendReceiveThread[currentNumClients];

    return 0;
}

int sendReceive()
{
    int currentNumClients = numClients;
    int iSendResult;
    char recvbuf[DEFAULT_BUFLEN];
    int recvbuflen = DEFAULT_BUFLEN;

    // Receive until the peer shuts down the connection
    while(true)
    {
        std::cout << 14 << std::endl;
        iResult = recv(ClientSocket[currentNumClients], recvbuf, recvbuflen, 0);
        std::cout << iResult << std::endl;
        if (iResult > 0) {
            std::cout << 15 << std::endl;
            printf("Bytes received: %d\n", iResult);

            // Echo the buffer back to the clients
            std::cout << 16 << std::endl;
            for (int i = 1; i <= numClients; i++)
            {
                iSendResult = send(ClientSocket[currentNumClients], recvbuf, iResult, 0);
                if (iSendResult == SOCKET_ERROR) {
                    std::cout << 17 << std::endl;
                    printf("send failed with error: %d\n", WSAGetLastError());
                    closesocket(ClientSocket[currentNumClients]);
                    WSACleanup();
                    return 1;
                }
                printf("Bytes sent: %d\n", iSendResult);
            }
        }
        else if (iResult == 0) {
            std::cout << 18 << std::endl;
            printf("Connection closing...\n");
            break;
        }
        else {
            std::cout << 19 << std::endl;
            printf("recv failed with error: %d\n", WSAGetLastError());
            std::cout << "On client #" << currentNumClients << std::endl;
            break;
        }

    }

    iResult = shutdownFunction(ClientSocket[currentNumClients]);

    std::cout << 22 << std::endl;
    // cleanup
    closesocket(ClientSocket[currentNumClients]);
    WSACleanup();

    return 0;
}

int shutdownFunction(SOCKET ClientSocket)
{
    std::cout << 20 << std::endl;
    iResult = shutdown(ClientSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
        std::cout << 21 << std::endl;
        printf("shutdown failed with error: %d\n", WSAGetLastError());
        closesocket(ClientSocket);
        WSACleanup();
        return 1;
    }

    return 0;
}

You might notice the different couts, those are just couts to know how the proggram behaves.

Socket Error 10048 — Specified Address Already in Use

This error only normally occurs during VPOP3 startup. It occurs if some other software running on the same machine as VPOP3 is using one of the ports that VPOP3 is already using. This could be a proxy like WinGate, WinProxy or anti-virus software that acts as a proxy, an LDAP server (e.g. Active Directory) or another mail server program (e.g. Exchange Server). The latter two causes are particularly common on server versions of Windows.

To prevent this problem you should either remove the conflicting service from the other software or change the port which either that other software or VPOP3 uses for that mail service. You can change the ports that VPOP3 uses for its various services on the Services page in the VPOP3 settings.

There are two ways to find out which program is using the conflicting port number. Each provides different evidence so if the results of one method are unclear try the other.

Method 1

Open a command prompt and at the prompt type in telnet <ip> <port> where <ip> is the IP address of the VPOP3 machine and <port> is the port number which is in conflict.

The response you get back should indicate the name of the program currently using the port.

Method 2

The alternative is to use a free tool called TCPView (originally from SysInternals) which lists all the ports currently in use for both TCP and UDP along with which programs are using them.

Error 10048 means Address already in use. You are trying to open a connection on a socket that is already in use. If a client disconnects from the server then the server needs to close the server socket that was used for that client.

How do I use TFTP 3CDaemon server?

Use or configure 3CDaemon’s TFTP server
use

Why do I get TCP error 10048 on WCF?

If you poll often enough, you will end up using all available ports, resulting in TCP error 10048. In general, WCF breaks it to avoid this problem by combining connections and such. Typically, this refers to services that are not transmitted over the Internet.

Why is my Python Server getting a 10048 error?

Of course, you can restart the server at any time, which will usually keep the client body running longer. (Except that the webserver might get error 10048 when trying to bind the socket because the OS is storing it for the previous owner. If you see this, see SO_REUSEADDR in the documentation.)

How do I fix bind error 10048?

Cause 1 can be resolved by terminating the program using your port, or your program is using a sorted port. Reason 2 can be changed by running only one instance of your program at a time. Cause 3 can be resolved by figuring it out within a few minutes or by using one of our SO_REUSEADDR socket options.

How do I fix Runtime Error 10048 address in use?

This error occurs when your home operating system cannot name new sockets….

How do I fix error 10048?

To avoid this process issue, you should either remove the conflicting service from other applications frequently or change the port used by other software or VPOP3 for that mail service. You can change the ports that VPOP3 uses for its various services on the About Services page in the VPOP3 settings.

What causes socket errors of 10048 on the client?

See http://msdn.microsoft.com/en-us/library/e160993d%28v=VS.90%29.aspx SetSocketOption. They have DontLinger or ReuseAddr or both, I’m not sure. Essentially, your sockets can get stuck in the TIME_WAIT state almost any time after the main TCP connection is dropped. Once you get enough of this, you won’t be ready to create new client attachments.

Why is winerror 10048 refusing to open socket?

When running another instance of the script, the running service actually opened the listening port, so trying to open it throws a 10048 / WSAEADDRINUSE reject error. Usually, if you want to run the script again, you need to set the running service to stop and close the socket.

Vijay is a tech writer with years of experience in the Windows world. He’s seen it all – from simple problems to catastrophic system failures. He loves nothing more than helping people fix their PCs, and he’s always happy to share his wisdom with anyone who needs it.

When Vijay isn’t fixing Windows problems, he likes to spend time with his wife and two young children. He also enjoys reading, playing cricket, and watching Bollywood movies.

������� Process Explorer, ����� ��� �������� 1� (� ��� ����� ���������) � ����� ��.

������� �� ��������� �������:

1. ����������� ��������� �������� ������. �� ��������� �� 5000, ����� ���������� �� 65536.
HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\MaxUserPort
2. ����� ��������� ����� ���������� ���������� � ��������� �������� � 4 ����� �� 30 ������.
HKLM\System\CurrentControlSet\Services\Tcpip\Parameters\TCPTimedWaitDelay

3. ������� ���� (���������, �������� � ��.) ���������� ����� 1�


�������, ������������ ������� ��������, � ��� ������� ��� ������ ��� ��������. ���� � ���������� - ����� ����������! :)

 

Понравилась статья? Поделить с друзьями:
  • Ошибка старта воспроизведения netsdk ошибка
  • Ошибка сошал клаб 134
  • Ошибка стерлинг нот локинг рено меган 2
  • Ошибка смешение стилей
  • Ошибка старого волшебника фильм скачать торрент