Windows socket error 10048 on api bind

Hello,  My application a simple MDI application.Take data in serial port and send it to another computer using tcp/ip .In the first iterartion every thing is fine.Both server and client systems works well.Then if the server is turned of off(disconnect using socket.close() method) and then client is also closed .without closing the application if i start open the socket and execute socket.bind() method , the exception 10048

RRS feed

  • Remove From My Forums
  • Question

  • Hello,
      My application a simple MDI application.Take data in serial port and send it to another computer using tcp/ip .
    In the first iterartion every thing is fine.Both server and client systems works well.
    Then if the server is turned of off(disconnect using socket.close() method) and then client is also closed .
    without closing the application if i start open the socket and execute socket.bind() method , the exception 10048

    thanks in advance.

    cheers,
    watashi

All replies

  • It means that yProxy is unable to bind to the Local (Proxy) Port that you have configured. That port is probably already in use.

  • Hello,
     Thnks for u  r reply.but as i hv stated the same application was using that ip and port and are closed using close() method.And then when try to open the same ip and port which was closed then i m getting the above error.

  • The problem is that binding and unbinding to endpoints is a costly operation for the Operating System.. And it takes a while before it is performed… If you want to speed up this process you’ll have to find a way to pass in the option SO_REUSEADDR (i can’t remember the .net equivalent right now) to notify the OS that the resource has to be cleaned up faster (and thus make it available faster)…

    serverSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.ReuseAddress, true);

    (Another interesting setting could be HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesTcpipParametersTcpTimedWaitDelay)

  • thnks a lot
     But i didnt get that interesting setting « HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesTcpipParametersTcpTimedWaitDelay)»

  • Basically a TCP connection is unique with the combination of (client ip, client socket, server ip, server socket).

    I can think of two issues in this case

      1. the previous connection with this combination is still alive in the system.(do a netstat -a). Most probably it will be in TIME_WAIT state.

      2. and you are again trying to make use of same combination in next request. 

    Thats the reason it gives that error.

    May be you can use SO_REUSEADDR or SO_EXCLUSIVEADDRUSE while trying to connect again.

    -Sushil

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: %dn", 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: %dn", 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: %dn", 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: %dn", 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: %dn", 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: %dn", 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: %ldn", 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: %dn", 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: %dn", 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: %dn", 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: %dn", 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: %dn", WSAGetLastError());
                    closesocket(ClientSocket[currentNumClients]);
                    WSACleanup();
                    return 1;
                }
                printf("Bytes sent: %dn", 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: %dn", 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: %dn", WSAGetLastError());
        closesocket(ClientSocket);
        WSACleanup();
        return 1;
    }

    return 0;
}

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

Addresses that are already in use.
Normally, each socket address (protocol/IP address/port) is allowed to be used only once.
This error occurs if the application tries to bind a socket to an IP address/port that is already in use for an existing socket, or a socket that is not properly closed, or is still in the process of being closed.
For server applications that need to bind multiple sockets to the same port number, such as when a client process is taskkill and starts again, consider using setsockopt (SO_REUSEADDR).
Client applications usually do not need to call bind-connect to automatically select an unused port. When calling bind with a wildcard address (including ADDR_ANY), the WSAEADDRINUSE error may be delayed until a specific address is committed. This may occur later when another function is called, including connect, listen, WSAConnect, or WSAJoinLeaf.

        BOOL bOptVal = TRUE;
        int bOptLen = sizeof(BOOL);
        iResult = setsockopt(ListenSocket, SOL_SOCKET, SO_REUSEADDR, (char *)&bOptVal, bOptLen);
        if (iResult == SOCKET_ERROR)
        {
            char m[500];
            snprintf(m, 500, "%s %d: setsockopt failed, port %d failed with error: %d",
                __func__, __LINE__, port_number, WSAGetLastError());
            printf("%sn", m);
            freeaddrinfo(result);
            closesocket(ListenSocket);
            WSACleanup();
            return -1;
        }

https://docs.microsoft.com/en-us/windows/desktop/api/winsock/nf-winsock-setsockopt

Reproduced in: https://www.cnblogs.com/liujx2019/p/10811330.html

Read More:

думаю, что у вас просто закончились динамические порты в системе…..

ошибка (учитывая что изменение max_connection не помогает) формируется вовсе не из за mysql , а из-за невозможности винды предоставить нужное число портов.

WSAEADDRINUSE
(10048)
Address already in use.
Only one usage of each socket address (protocol/IP address/port) is normally permitted. This error occurs if an application attempts to bind a socket to an IP address/port that has already been used for an existing socket, or a socket that wasn’t closed properly, or one that is still in the process of closing. For server applications that need to bind multiple sockets to the same port number, consider using setsockopt(SO_REUSEADDR). Client applications usually need not call bind at all — connectwill choose an unused port automatically.»

что в общем случае означает —

Address already in use (Адрес уже используется).
Обычно разрешено только одно использование адреса сокета (проткол/адрес IP/порт). Эта ошибка возникает, когда приложение пытается привязаться к сокету функцией bind(), но комбинация адрес IP/порт уже используется существующим сокетом, или сокет не был корректно закрыт, или продолжается процесс закрытия сокета. Для серверных приложений, требующих привязки нескольких сокетов к одному и тому же номеру порта следует использовать setsockopt(SO_REUSEADDR). Клиентские приложения обычно не используют bind() — функция connect() автоматически выбирает неиспользуемый порт.

В вашем случае, при возрастании числа запросов к базе, когда открывается и закрывается куча подключений к базе, то оти попросту не успевают закрыться. Обратите внимание, что речь идет не о том, чтобы не забыть закрыть подключение mysql, а о том, что ресурсы для НОВОГО подключения освободятся не сразу….

Если мне память не изменяет, то есть в реестре пара параметров, которые на это влияют.

один из них — TcpTimedWaitDelay. Этот параметр определяет интервал времени, в течение которого подключение находится в состоянии ожидания, прежде чем будет закрыто. Пока подключение находится в состоянии ожидания, пара сокетов не может быть использована повторно. А согласно RFC793, данное значение должно в два раза превышать максимальное время жизни пакета.
Если учесть что в Windows XP и Microsoft Windows Server 2003 значение по умолчанию было установлено на 120 секунд, то получается что целых 2 минуты система просто ждет никому не отдавая уже освободившийся ресурс.

ищем тут

Код: Выделить всё • Развернуть
HKLMSYSTEMCurrentControLSetServicesTcpipParametersTcpTimedWaitDelay

и уменьшаем значение.
если нет, то создаем
REG_DWORD – время в секундах , с допустимыми параметрами 30-300 (в десятичной системе)

и второй параметр это MaxUserPort
находится он в

Код: Выделить всё • Развернуть
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesTcpipParameters

имеет тип DWORD и допустимые значения от десятичных 5000 (по умолчанию) до 65534

он определяет максимальный номер порта, который используется, когда программа запрашивает у системы доступный пользовательский порт.

в итоге изначально имеем в системе всего 5000-1024 = 3976 портов, доступных для приложений, да еще и повторно использовать их можно не чаще раза в 2 минуты…

отпишитесь, плиз, помогло написанное или нет ?

p.s. если параметра нет в реестре, то это не значит что он не используется, просто его значение принимается системой по умолчанию…..

по итогам размышлений над

http://bugs.mysql.com/bug.php?id=10498

и

http://bugs.mysql.com/bug.php?id=6580

Лучше установить FreeBSD, чем потратить 20 лет на Linux’ы и выяснить какой из них хуже.

1568 / 504 / 48

Регистрация: 04.04.2009

Сообщений: 1,891

1

20.03.2013, 11:49. Показов 5654. Ответов 2


Пытаюсь запустить специфичную программу Parma (процесс TransData.exe) на рабочих компах Win XP Pro x32. При запуске (на любой машине) получаю ошибочку:

Windows socket error: Обычно разрешается одно использование адреса сокета (протокол/сетевой адрес/порт) (10048), on API «bind»

1. Глянул netstat -aon. Порт 10048 там не обнаружил.
2. Проверил значение MaxUserPort в HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/Tcpip/Parameters. Значение максимальное — 65534.
3. Касперского отключал.

Помогите, пожалуйста, с проблемой.

P.S. На домашнем ноуте Win 7 x32 Starter запускается без проблем.
P.P.S. Лог от ProcessMonitor (напоминаю, процесс TransData.exe) на всякий случай прилагаю.



0



4 / 4 / 6

Регистрация: 27.02.2013

Сообщений: 32

20.03.2013, 11:53

2

Открыть порт в ручную не пробовал.



0



1568 / 504 / 48

Регистрация: 04.04.2009

Сообщений: 1,891

20.03.2013, 17:52

 [ТС]

3

normalskt,

Цитата
Сообщение от normalskt
Посмотреть сообщение

Открыть порт в ручную не пробовал.

1. Пробовал.

2.

Цитата
Сообщение от The_Immortal
Посмотреть сообщение

Касперского отключал.

Соответственного и его фаервол. Штатные фаер также отключен.

3.

Цитата
Сообщение от The_Immortal
Посмотреть сообщение

На домашнем ноуте Win 7 x32 Starter запускается без проблем

Там никаких шаманств с портами не производил.

Добавлено через 5 часов 46 минут
В общем проблема оказалась в конфлитке с безобидным VNC-сервером, который работает как служба.

Не понимаю, чем мог помешать VNC-сервер? Он занимает конкретные порты 5800 и 5900. И все…

А причем тут вышеуказанный порт 10048 тогда?

Есть идеи?

Каждый раз тушить VCN как-то нехорошо…



0



Recommended Posts

igotregistered

Newbie

    • Report
    • Share

Current OS WinXP Pro SP2 all hotfixes and patches

Program using: DSLSpeed pc Webhosting 1.0

Im getting this message when I try to run a program which seems to utilize the same port which is already using it «Address already in use». How can I check to see what particular socket this program is trying to use and what seems to be already using it? Then, if it’s possible can I un-associate that assignment so the program I want to use can use that socket?

Thanks to all in advance!

  • Quote
Link to comment
Share on other sites

nellie2

Newbie

scuzzman

Newbie

    • Report
    • Share

You should be able to check that using the Command Prompt. Go to Start -> Run and type

cmd

This should open a black window with something similar to this prompt:

C:Documents and SettingsOwner>

In that window, type this command:

netstat -a

This will show you which programs are currently listening/connected and on which ports. HTH.

  • Quote
Link to comment
Share on other sites

cozofdeath

Newbie

    • Report
    • Share

Is this the program you mean? http://www.dsl-speed.org/webhosting.htm If it is I’ll try to find what for ports it uses but I would think 80, and you may want to upgrade. Netstat utilities won’t help because that program can’t even bind to a socket to make a connection, therefore nothing would show, but it will tell you what is connected.

This program should show you what exactly is going on with your sockets and where your problem is, I hope it helps.

http://www.sysinternals.com/Utilities/TdiMon.html

Winsock error #:

Address already in use.

Typically, only one usage of each socket address (protocol/IP address/port) is permitted. This error occurs if an application attempts to bind a socket to an IP address/port that has already been used for an existing socket, or a socket that was not closed properly, or one that is still in the process of closing. For server applications that need to bind multiple sockets to the same port number, consider using setsockopt (SO_REUSEADDR). Client applications usually need not call bind at all— connect chooses an unused port automatically. When bind is called with a wildcard address (involving ADDR_ANY), a WSAEADDRINUSE error could be delayed until the specific address is committed. This could happen with a call to another function later, including connect, listen, WSAConnect, or WSAJoinLeaf.

  • Quote
Link to comment
Share on other sites

Join the conversation

You can post now and register later.
If you have an account, sign in now to post with your account.

Содержание

  1. Windows socket error 10048 on api bind
  2. Windows socket error 10048 on api bind
  3. Windows socket error 10048 on api bind
  4. Windows socket error 10048 on api bind
  5. Windows socket error 10048 on api bind

Windows socket error 10048 on api bind

Сообщения: 1501
Благодарности: 47

Petya V4sechkin, в общем проблема оказалась в безобидном VNC-сервере. Он работает как служба.

Не понимаю, чем мог помешать VNC-сервер? Он занимает конкретные порты 5800 и 5900. И все.

А причем тут вышеуказанный порт 10048 тогда?

Каждый раз тушить VCN как-то нехорошо.

moderator

Сообщения: 52190
Благодарности: 15075

Это не порт, а код ошибки Winsock.

smile

? moderator

Сообщения: 52190
Благодарности: 15075

Windows socket error 10048 on api bind

Сообщения: 1501
Благодарности: 47

Petya V4sechkin, в общем проблема оказалась в безобидном VNC-сервере. Он работает как служба.

Не понимаю, чем мог помешать VNC-сервер? Он занимает конкретные порты 5800 и 5900. И все.

А причем тут вышеуказанный порт 10048 тогда?

Каждый раз тушить VCN как-то нехорошо.

Источникmoderator

Сообщения: 52190
Благодарности: 15075

Это не порт, а код ошибки Winsock.

smile

? moderator

Сообщения: 52190
Благодарности: 15075

Windows socket error 10048 on api bind

Сообщения: 1501
Благодарности: 47

Petya V4sechkin, в общем проблема оказалась в безобидном VNC-сервере. Он работает как служба.

Не понимаю, чем мог помешать VNC-сервер? Он занимает конкретные порты 5800 и 5900. И все.

А причем тут вышеуказанный порт 10048 тогда?

Каждый раз тушить VCN как-то нехорошо.

Источникmoderator

Сообщения: 52190
Благодарности: 15075

Это не порт, а код ошибки Winsock.

smile

? moderator

Сообщения: 52190
Благодарности: 15075

Windows socket error 10048 on api bind

Сообщения: 1501
Благодарности: 47

Petya V4sechkin, в общем проблема оказалась в безобидном VNC-сервере. Он работает как служба.

Не понимаю, чем мог помешать VNC-сервер? Он занимает конкретные порты 5800 и 5900. И все.

А причем тут вышеуказанный порт 10048 тогда?

Каждый раз тушить VCN как-то нехорошо.

Источникmoderator

Сообщения: 52190
Благодарности: 15075

Это не порт, а код ошибки Winsock.

smile

?

Читайте также:  windows 10 search not working

moderator

Сообщения: 52190
Благодарности: 15075

Windows socket error 10048 on api bind

Сообщения: 1501
Благодарности: 47

Petya V4sechkin, в общем проблема оказалась в безобидном VNC-сервере. Он работает как служба.

Не понимаю, чем мог помешать VNC-сервер? Он занимает конкретные порты 5800 и 5900. И все.

А причем тут вышеуказанный порт 10048 тогда?

Каждый раз тушить VCN как-то нехорошо.

Источникmoderator

Сообщения: 52190
Благодарности: 15075

Это не порт, а код ошибки Winsock.

smile

? moderator

Сообщения: 52190
Благодарности: 15075

Adblock
detector

Источник

Понравилась статья? Поделить с друзьями:
  • Windows smm security mitigations table что это
  • Windows smartscreen не дает установить программу
  • Windows smartscreen как отключить windows server
  • Windows smartscreen cant be reached right now что значит
  • Windows smartscreen cant be reached right now перевод