Код ошибки 10049 bluetooth

Я пытаюсь установить соединение с настраиваемым устройством Bluetooth без использования COM-портов. Однако я получаю сообщение об ошибке: [10049] «Запрошенный адрес недействителен в своем контексте». Что я делаю неправильно?

static Guid serviceClass= new Guid("4d36e978-e325-11ce-bfc1-08002be10318"); //GUID of device class

static BluetoothAddress addr = BluetoothAddress.Parse("001210160177"); //from device            
BluetoothDeviceInfo device = new BluetoothDeviceInfo(addr); 

device.SetServiceState(serviceClass, true);

Console.WriteLine(BluetoothSecurity.PairRequest(device.DeviceAddress, "0000")); //pairing my device - writes True
BluetoothEndPoint ep = new BluetoothEndPoint(addr, serviceClass);

BluetoothClient conn = new BluetoothClient(ep); //10049 error
conn.Connect(ep);
Console.WriteLine(conn.GetStream());

2 ответа

Лучший ответ

Все это описано в документации по проекту. :-)

Короче, удалите эту строку SetServiceState, это ненужно / плохо. Выполнять сопряжение каждый раз также необязательно и немного медленно, но, вероятно, не стоит менять, если оно работает хорошо.

Docs :

1) http://32feet.codeplex.com/documentation

  • «См. Раздел« Общие подключения данных Bluetooth »ниже. BluetoothClient предоставляет поток для чтения и записи — нет необходимости использовать виртуальные COM-порты»

2) http://32feet.codeplex.com/wikipage?title=General % 20Bluetooth% 20Data% 20Connections

BluetoothAddress addr
  = BluetoothAddress.Parse("001122334455");
Guid serviceClass;
serviceClass = BluetoothService.SerialPort;
// - or - etc
// serviceClass = MyConsts.MyServiceUuid
//
var ep = new BluetoothEndPoint(addr, serviceClass);
var cli = new BluetoothClient();
cli.Connect(ep);
Stream peerStream = cli.GetStream();
peerStream.Write/Read ...

3) http://32feet.codeplex.com/wikipage?title=Errors

  • 10049 «Запрошенный адрес недействителен в своем контексте.»
  • На удаленном устройстве не работает служба с данным идентификатором класса обслуживания

То есть Неверный идентификатор класса обслуживания.


2

alanjmcf
15 Мар 2014 в 14:55

Вот как наконец катится.

device.SetServiceState(serviceClass, true); //do it before pairing
...
BluetoothClient conn = new BluetoothClient(); 
conn.Connect(ep);

Также моя ошибка здесь:

static Guid serviceClass = new Guid("4d36e978-e325-11ce-bfc1-08002be10318"); 
//GUID of device class

Должно быть:

static Guid serviceClass = new Guid("00001101-0000-1000-8000-00805f9b34fb"); 
//GUID of bluetooth service

Чтобы увидеть правильный GUID, обратитесь к настройкам / свойствам вашего устройства (не ключа). Вы можете увидеть их из Windows.


0

ammme
14 Мар 2014 в 13:23

  • Remove From My Forums
  • Question

  • Hi,

    I’m writing a program to connect to a bluetooth device using Winsock.  In discovery mode, I can find the device, but when I try to connect() I always get the error 10049 (WSAEADDRNOTAVAIL — Address not available). What is the problem?

    		WSADATA wsaData;
    		if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0)
    			return (EXIT_FAILURE);
    		
    		if ((_socket	= socket(AF_BT, SOCK_STREAM, BTHPROTO_RFCOMM)) == INVALID_SOCKET)
    			return (EXIT_FAILURE);
    
    		SOCKADDR_BTH sa;
    		std::memset(&sa, 0, sizeof(sa));
    		int nSizeInput = sizeof(sa);
    		int result = WSAStringToAddress(_address, AF_BTH, NULL, (LPSOCKADDR)&sa, &nSizeInput);
    
    		// To validate the address...
    		char  addressStr[64] = {0};
    		DWORD  dwSizeOfStr = sizeof(addressStr);
    		WSAAddressToStringA((LPSOCKADDR)&sa, nSizeInput, NULL, addressStr, &dwSizeOfStr);
    
    		result = connect(_socket, (SOCKADDR*)&sa, sizeof(sa));
    
    

Answers

  • There’s a sample that covers this in the WM6 SDK:
    Windows Mobile 6 SDKSamplesPocketPCCPPwin32BluetoothBthChat

    Try setting the addressFamily member of SOCKADDR_BTH to AF_BT.

    Also, try setting the btAddr member to one of the devices returned from WSALookupServiceNext.
    http://msdn.microsoft.com/en-us/library/aa916570.aspx

    -PaulH

    • Marked as answer by

      Tuesday, March 1, 2011 8:15 AM

I’m developing a dll in visual-c++ for client side application to connect my pc to my android phone via bluetooth. I use this function to find my bluetooth service on the phone(see commented code!):

bool BlueRayXVR::findPairedService(GUID* guid, _SOCKET_ADDRESS* ret){
    this->checkStartup();

    HBLUETOOTH_DEVICE_FIND found_devices;

    BLUETOOTH_DEVICE_INFO device_info;
    device_info.dwSize = sizeof(device_info);

    BLUETOOTH_DEVICE_SEARCH_PARAMS search_criteria;
    search_criteria.dwSize = sizeof(BLUETOOTH_DEVICE_SEARCH_PARAMS);
    search_criteria.fReturnAuthenticated = TRUE;
    search_criteria.fReturnRemembered = FALSE;
    search_criteria.fReturnConnected = FALSE;
    search_criteria.fReturnUnknown = FALSE;
    search_criteria.fIssueInquiry = FALSE;
    search_criteria.cTimeoutMultiplier = 0;

    found_devices = BluetoothFindFirstDevice(&search_criteria, &device_info);

    if (found_devices == NULL)
    {
        _tprintf(TEXT("Error: n%sn"), getErrorMessage(WSAGetLastError(), error));
        return false;
    }

    WSAQUERYSET querySet;
    memset(&querySet, 0, sizeof(querySet));
    querySet.dwSize = sizeof(querySet);
    querySet.lpServiceClassId = guid;
    querySet.dwNameSpace = NS_BTH;

    SOCKADDR_BTH sab;
    memset (&sab, 0, sizeof(sab));
    sab.addressFamily  = AF_BTH;

    char addressAsString[1000];
    DWORD addressSize = sizeof(addressAsString);

    bool found = false;

    do
    {
        sab.btAddr = device_info.Address.ullLong;
        if (0 != WSAAddressToString((LPSOCKADDR)&sab, sizeof(sab), NULL, (LPWSTR)addressAsString, &addressSize)){
            _tprintf(TEXT("Error get the mac of the device %sn.Going to the next device."), device_info.szName);
        }
        else{
            _tprintf(TEXT("Check on device %s%s for the service.n"), device_info.szName, addressAsString);
            querySet.lpszContext =(LPWSTR) addressAsString;
            HANDLE service_lookup_handle;
            DWORD flags = LUP_FLUSHCACHE |LUP_RETURN_NAME | LUP_RETURN_ADDR | LUP_RETURN_BLOB;

            int result = WSALookupServiceBegin(&querySet, flags, &service_lookup_handle);

            if (0 == result)
            {
                BYTE buffer[2000];
                DWORD bufferLength = sizeof(buffer);
                WSAQUERYSET *pResults = (WSAQUERYSET*)&buffer;
                if(0 == WSALookupServiceNext(service_lookup_handle, flags, &bufferLength, pResults))
                {
                    _tprintf(TEXT("Service : %sn"), pResults->lpszServiceInstanceName);
                    _tprintf(TEXT("Comment : %sn"), pResults->lpszComment);
                    *ret = pResults->lpcsaBuffer->RemoteAddr;
                    found = true;

                /*  this->sock = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);                      
                    if (0 == ::connect(sock, ret->lpSockaddr, ret->iSockaddrLength))
                    {
                        printf("connected");
                        //closesocket (*sock);
                        //return TRUE;
                    }
                    wprintf(L"errore %d: %s", WSAGetLastError(), this->getErrorMessage(WSAGetLastError(), this->error));
                    */
                }
                result = WSALookupServiceEnd(service_lookup_handle);
            }
            else
                _tprintf(TEXT("%snGoing to the next device..n"), getErrorMessage(GetLastError(), error));
        }
    } while (BluetoothFindNextDevice(found_devices, &device_info) && !found);

    if(found_devices)
        BluetoothFindDeviceClose(found_devices);

    _tprintf(TEXT("No more device.n"));
    return found;
}

And this one to connect to the phone:

bool BlueRayXVR::connect(_SOCKET_ADDRESS* host)
{
    this->sock = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM); 
    if (this->sock == INVALID_SOCKET)
    {
        _tprintf(TEXT("Failed to get bluetooth socket! %sn"), getErrorMessage(WSAGetLastError(), error));
        exit(1);
    }

    if (0 == ::connect(sock, host->lpSockaddr, host->iSockaddrLength))
    {
        printf("connectedn");
        return TRUE;
    }
    wprintf(L"errore %d: %s", WSAGetLastError(), this->getErrorMessage(WSAGetLastError(), this->error));
    return FALSE;
}

In my test console app i do:

       _SOCKET_ADDRESS address;
    memset (&address, 0, sizeof(address));
    if(blue->findPairedService(&blue->getDefaultGUID4XVR(), &address)){
        printf("service founded..try to connect..n");
        if(blue->connect(&address))
            blue->read();
    }

The problem is that if i run my code i always get error 10049.

the strange thing is that if i uncomment the lines of code in findPairedService function and i just do

       _SOCKET_ADDRESS address;
    memset (&address, 0, sizeof(address));
    if(blue->findPairedService(&blue->getDefaultGUID4XVR(), &address)){

it succesfully connect to the phone….

what’s wrong??

Thanks!

I’m developing a dll in visual-c++ for client side application to connect my pc to my android phone via bluetooth. I use this function to find my bluetooth service on the phone(see commented code!):

bool BlueRayXVR::findPairedService(GUID* guid, _SOCKET_ADDRESS* ret){
    this->checkStartup();

    HBLUETOOTH_DEVICE_FIND found_devices;

    BLUETOOTH_DEVICE_INFO device_info;
    device_info.dwSize = sizeof(device_info);

    BLUETOOTH_DEVICE_SEARCH_PARAMS search_criteria;
    search_criteria.dwSize = sizeof(BLUETOOTH_DEVICE_SEARCH_PARAMS);
    search_criteria.fReturnAuthenticated = TRUE;
    search_criteria.fReturnRemembered = FALSE;
    search_criteria.fReturnConnected = FALSE;
    search_criteria.fReturnUnknown = FALSE;
    search_criteria.fIssueInquiry = FALSE;
    search_criteria.cTimeoutMultiplier = 0;

    found_devices = BluetoothFindFirstDevice(&search_criteria, &device_info);

    if (found_devices == NULL)
    {
        _tprintf(TEXT("Error: n%sn"), getErrorMessage(WSAGetLastError(), error));
        return false;
    }

    WSAQUERYSET querySet;
    memset(&querySet, 0, sizeof(querySet));
    querySet.dwSize = sizeof(querySet);
    querySet.lpServiceClassId = guid;
    querySet.dwNameSpace = NS_BTH;

    SOCKADDR_BTH sab;
    memset (&sab, 0, sizeof(sab));
    sab.addressFamily  = AF_BTH;

    char addressAsString[1000];
    DWORD addressSize = sizeof(addressAsString);

    bool found = false;

    do
    {
        sab.btAddr = device_info.Address.ullLong;
        if (0 != WSAAddressToString((LPSOCKADDR)&sab, sizeof(sab), NULL, (LPWSTR)addressAsString, &addressSize)){
            _tprintf(TEXT("Error get the mac of the device %sn.Going to the next device."), device_info.szName);
        }
        else{
            _tprintf(TEXT("Check on device %s%s for the service.n"), device_info.szName, addressAsString);
            querySet.lpszContext =(LPWSTR) addressAsString;
            HANDLE service_lookup_handle;
            DWORD flags = LUP_FLUSHCACHE |LUP_RETURN_NAME | LUP_RETURN_ADDR | LUP_RETURN_BLOB;

            int result = WSALookupServiceBegin(&querySet, flags, &service_lookup_handle);

            if (0 == result)
            {
                BYTE buffer[2000];
                DWORD bufferLength = sizeof(buffer);
                WSAQUERYSET *pResults = (WSAQUERYSET*)&buffer;
                if(0 == WSALookupServiceNext(service_lookup_handle, flags, &bufferLength, pResults))
                {
                    _tprintf(TEXT("Service : %sn"), pResults->lpszServiceInstanceName);
                    _tprintf(TEXT("Comment : %sn"), pResults->lpszComment);
                    *ret = pResults->lpcsaBuffer->RemoteAddr;
                    found = true;

                /*  this->sock = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);                      
                    if (0 == ::connect(sock, ret->lpSockaddr, ret->iSockaddrLength))
                    {
                        printf("connected");
                        //closesocket (*sock);
                        //return TRUE;
                    }
                    wprintf(L"errore %d: %s", WSAGetLastError(), this->getErrorMessage(WSAGetLastError(), this->error));
                    */
                }
                result = WSALookupServiceEnd(service_lookup_handle);
            }
            else
                _tprintf(TEXT("%snGoing to the next device..n"), getErrorMessage(GetLastError(), error));
        }
    } while (BluetoothFindNextDevice(found_devices, &device_info) && !found);

    if(found_devices)
        BluetoothFindDeviceClose(found_devices);

    _tprintf(TEXT("No more device.n"));
    return found;
}

And this one to connect to the phone:

bool BlueRayXVR::connect(_SOCKET_ADDRESS* host)
{
    this->sock = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM); 
    if (this->sock == INVALID_SOCKET)
    {
        _tprintf(TEXT("Failed to get bluetooth socket! %sn"), getErrorMessage(WSAGetLastError(), error));
        exit(1);
    }

    if (0 == ::connect(sock, host->lpSockaddr, host->iSockaddrLength))
    {
        printf("connectedn");
        return TRUE;
    }
    wprintf(L"errore %d: %s", WSAGetLastError(), this->getErrorMessage(WSAGetLastError(), this->error));
    return FALSE;
}

In my test console app i do:

       _SOCKET_ADDRESS address;
    memset (&address, 0, sizeof(address));
    if(blue->findPairedService(&blue->getDefaultGUID4XVR(), &address)){
        printf("service founded..try to connect..n");
        if(blue->connect(&address))
            blue->read();
    }

The problem is that if i run my code i always get error 10049.

the strange thing is that if i uncomment the lines of code in findPairedService function and i just do

       _SOCKET_ADDRESS address;
    memset (&address, 0, sizeof(address));
    if(blue->findPairedService(&blue->getDefaultGUID4XVR(), &address)){

it succesfully connect to the phone….

what’s wrong??

Thanks!

I’m trying to establish a connection with a custom bluetooth device without using COM ports. However, I’m getting an error: [10049] «The requested address is not valid in its context». What am I doing wrong?

static Guid serviceClass= new Guid("4d36e978-e325-11ce-bfc1-08002be10318"); //GUID of device class

static BluetoothAddress addr = BluetoothAddress.Parse("001210160177"); //from device            
BluetoothDeviceInfo device = new BluetoothDeviceInfo(addr); 

device.SetServiceState(serviceClass, true);

Console.WriteLine(BluetoothSecurity.PairRequest(device.DeviceAddress, "0000")); //pairing my device - writes True
BluetoothEndPoint ep = new BluetoothEndPoint(addr, serviceClass);

BluetoothClient conn = new BluetoothClient(ep); //10049 error
conn.Connect(ep);
Console.WriteLine(conn.GetStream());

asked Mar 12, 2014 at 8:45

ammme's user avatar

Its all covered in the project’s documentation. :-)

In short, remove that SetServiceState line it is unnecessary/bad. Doing the pairing each time is also unnecessary and a bit slow but probably not worth changing if its working well.

Docs:

1) http://32feet.codeplex.com/documentation

  • «See section General Bluetooth Data Connections below. The BluetoothClient provides the Stream to read and write on — there is no need to use virtual COM ports»

2) http://32feet.codeplex.com/wikipage?title=General%20Bluetooth%20Data%20Connections

BluetoothAddress addr
  = BluetoothAddress.Parse("001122334455");
Guid serviceClass;
serviceClass = BluetoothService.SerialPort;
// - or - etc
// serviceClass = MyConsts.MyServiceUuid
//
var ep = new BluetoothEndPoint(addr, serviceClass);
var cli = new BluetoothClient();
cli.Connect(ep);
Stream peerStream = cli.GetStream();
peerStream.Write/Read ...

3) http://32feet.codeplex.com/wikipage?title=Errors

  • 10049 «The requested address is not valid in its context.»
  • No Service with given Service Class Id is running on the remote device

i.e. Wrong Service Class Id.

answered Mar 15, 2014 at 10:55

alanjmcf's user avatar

alanjmcfalanjmcf

3,4221 gold badge17 silver badges14 bronze badges

Here’s how it finally rolls.

device.SetServiceState(serviceClass, true); //do it before pairing
...
BluetoothClient conn = new BluetoothClient(); 
conn.Connect(ep);

Also, my mistake here:

static Guid serviceClass = new Guid("4d36e978-e325-11ce-bfc1-08002be10318"); 
//GUID of device class

Should be:

static Guid serviceClass = new Guid("00001101-0000-1000-8000-00805f9b34fb"); 
//GUID of bluetooth service

For seeing the proper GUID, refer to your device’s (not dongle’s) settings/properties. You can see them from Windows.

answered Mar 14, 2014 at 9:23

ammme's user avatar

ammmeammme

331 silver badge4 bronze badges

  • Remove From My Forums
  • Question

  • Hi,

    I’m writing a program to connect to a bluetooth device using Winsock.  In discovery mode, I can find the device, but when I try to connect() I always get the error 10049 (WSAEADDRNOTAVAIL — Address not available). What is the problem?

    		WSADATA wsaData;
    		if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0)
    			return (EXIT_FAILURE);
    		
    		if ((_socket	= socket(AF_BT, SOCK_STREAM, BTHPROTO_RFCOMM)) == INVALID_SOCKET)
    			return (EXIT_FAILURE);
    
    		SOCKADDR_BTH sa;
    		std::memset(&sa, 0, sizeof(sa));
    		int nSizeInput = sizeof(sa);
    		int result = WSAStringToAddress(_address, AF_BTH, NULL, (LPSOCKADDR)&sa, &nSizeInput);
    
    		// To validate the address...
    		char  addressStr[64] = {0};
    		DWORD  dwSizeOfStr = sizeof(addressStr);
    		WSAAddressToStringA((LPSOCKADDR)&sa, nSizeInput, NULL, addressStr, &dwSizeOfStr);
    
    		result = connect(_socket, (SOCKADDR*)&sa, sizeof(sa));
    
    

Answers

  • There’s a sample that covers this in the WM6 SDK:
    Windows Mobile 6 SDKSamplesPocketPCCPPwin32BluetoothBthChat

    Try setting the addressFamily member of SOCKADDR_BTH to AF_BT.

    Also, try setting the btAddr member to one of the devices returned from WSALookupServiceNext.
    http://msdn.microsoft.com/en-us/library/aa916570.aspx

    -PaulH

    • Marked as answer by

      Tuesday, March 1, 2011 8:15 AM

Я пытаюсь установить соединение с настраиваемым устройством Bluetooth без использования COM-портов. Однако я получаю сообщение об ошибке: [10049] «Запрошенный адрес недействителен в своем контексте». Что я делаю неправильно?

static Guid serviceClass= new Guid("4d36e978-e325-11ce-bfc1-08002be10318"); //GUID of device class

static BluetoothAddress addr = BluetoothAddress.Parse("001210160177"); //from device            
BluetoothDeviceInfo device = new BluetoothDeviceInfo(addr); 

device.SetServiceState(serviceClass, true);

Console.WriteLine(BluetoothSecurity.PairRequest(device.DeviceAddress, "0000")); //pairing my device - writes True
BluetoothEndPoint ep = new BluetoothEndPoint(addr, serviceClass);

BluetoothClient conn = new BluetoothClient(ep); //10049 error
conn.Connect(ep);
Console.WriteLine(conn.GetStream());

2 ответа

Лучший ответ

Все это описано в документации по проекту. :-)

Короче, удалите эту строку SetServiceState, это ненужно / плохо. Выполнять сопряжение каждый раз также необязательно и немного медленно, но, вероятно, не стоит менять, если оно работает хорошо.

Docs :

1) http://32feet.codeplex.com/documentation

  • «См. Раздел« Общие подключения данных Bluetooth »ниже. BluetoothClient предоставляет поток для чтения и записи — нет необходимости использовать виртуальные COM-порты»

2) http://32feet.codeplex.com/wikipage?title=General % 20Bluetooth% 20Data% 20Connections

BluetoothAddress addr
  = BluetoothAddress.Parse("001122334455");
Guid serviceClass;
serviceClass = BluetoothService.SerialPort;
// - or - etc
// serviceClass = MyConsts.MyServiceUuid
//
var ep = new BluetoothEndPoint(addr, serviceClass);
var cli = new BluetoothClient();
cli.Connect(ep);
Stream peerStream = cli.GetStream();
peerStream.Write/Read ...

3) http://32feet.codeplex.com/wikipage?title=Errors

  • 10049 «Запрошенный адрес недействителен в своем контексте.»
  • На удаленном устройстве не работает служба с данным идентификатором класса обслуживания

То есть Неверный идентификатор класса обслуживания.


2

alanjmcf
15 Мар 2014 в 14:55

Вот как наконец катится.

device.SetServiceState(serviceClass, true); //do it before pairing
...
BluetoothClient conn = new BluetoothClient(); 
conn.Connect(ep);

Также моя ошибка здесь:

static Guid serviceClass = new Guid("4d36e978-e325-11ce-bfc1-08002be10318"); 
//GUID of device class

Должно быть:

static Guid serviceClass = new Guid("00001101-0000-1000-8000-00805f9b34fb"); 
//GUID of bluetooth service

Чтобы увидеть правильный GUID, обратитесь к настройкам / свойствам вашего устройства (не ключа). Вы можете увидеть их из Windows.


0

ammme
14 Мар 2014 в 13:23

Содержание

  1. bind() fails with windows socket error 10049
  2. 4 Answers 4
  3. Ошибка Winsock 10049 пытается связать
  4. Решение
  5. Другие решения
  6. Socket UDP from local computer, Error code 10049
  7. 2 Answers 2
  8. Windows socket error code 10049
  9. Socket Error Перечисление
  10. Определение
  11. Комментарии

bind() fails with windows socket error 10049

I try to make a client/server program in C with IPv6 and UDP. When the program binds the socket it return the WSAError 10049. I know that this is a problem with the adress name but don’t see whats the problem. I hope someone can help.

4 Answers 4

I would suggest to memset zero the below arrays,structures:

Before you can use the sockaddr_in6 struct, you will have to memset it to zero:

The reason is that the struct sockaddr_in6 structure contains other fields which you are not initializing (such as sin6_scope_id ) and which might contain garbage.

bcmrv

rXvMA

I have faced the same error.

@askMish ‘s answer is quite right.I didn’t understand it at the first place,however I find it out eventually.

This normally results from an attempt to bind to an address that is not valid for the local computer..

Normally we have our computer under some gateway.

If we run ipconfig we will find the IP address is 192.168.something.

So that’s the IP we could use to bind in code.

While other should connect with the public IP(if you can surf Internet you have one for sure.) like 47.93.something if they are in the same LAN with you.

You need to find that IP at your gateway(possibly your family’s route).

I had that same error code when calling bind() under windows.

The reason in my case was not the same as in the initial poster’s code, but i guess other will have made the very same mistake as me:

But inet_addr() already returns the address in byte-network-order, so the call htonl(inaddr) was wrong in my code and caused error 10049:

When calling bind() using «all local interfaces» ( INADDR_ANY ) it worked, because of this coincidence INADDR_ANY == htonl(INADDR_ANY) :

Источник

Ошибка Winsock 10049 пытается связать

У меня проблема с подключением к серверу. При попытке привязать сервер к IP-адресу моего внешнего устройства я получил ошибку winsock: 10049 Невозможно назначить запрошенный адрес. Использование локального сервера работает правильно.
Этот IP-адрес: 192.168.0.202 пинг успешно.
Я работал на win8.1. Я отключил брандмауэр и Windows Defender, и это не помогло.

Решение

bind() Функция используется для указания того, какой адрес серверной системы используется для приема соединений от удаленных клиентов, а не для указания, какому удаленному клиенту разрешено подключаться к серверу. bind() Функция может использоваться только с адресами, которые действительны для самого сервера, но не для адресов удаленных устройств или хостов.

Чтобы определить, какому удаленному хосту разрешено подключаться к вашему серверу, вам необходимо принять подключение и подтвердить удаленный адрес в это время. Если адрес не правильный, соединение закрывается.

В общем, вы хотите использовать INADDR_ANY если ваш сервер не является многодомным (более одного физического подключения к нескольким сетям), и только тогда, если вы пытаетесь ограничить подключения к одной из сетей, к которым подключен ваш сервер.

Другие решения

Winsock возвращает флаг ошибки 10049 (WSAEADDRNOTAVAIL) через свой API WSAGetLastError всякий раз, когда приложение пытается связаться с неверным IP-адресом.

привязка к определенному IP-адресу означает, что всякий раз, когда вы запускаете программу (сервер), адрес должен быть действительным (доступным), но, тем не менее, DHCP выдает вам динамические IP-адреса каждый раз, когда вы отключаете / подключаете адаптер, так что вы адрес, который вы связывали с сервером в прошлый раз недопустимо исправить его, откройте cmd и введите:

вы получите список адресов ip4 / ip6, затем вы можете выбрать один из них и привязать свой сервер, однако этот метод действительно скучный, поэтому альтернативой является привязка к INADDR_ANY так что вы позволяете системе делать работу за вас.

вам нужно только с клиента ввести адрес сервера и порт и подключиться.

Источник

Socket UDP from local computer, Error code 10049

i have been searching the web for a solution, but no luck.

We are making a socket, that can send and recieve data. Both the client and server version are acting as a client and server. The problem is, that the client server version ip is on a network that use NAT, which means, that when the server is trying to recieve the message, it wont, because the server have the public ip and we cant seem to find a solution, for how to recieve the data.

The SetIPProtectionLevel is Unrestricted, so it should work.

Thanks for the help.

We have tried to change the ip on the server version to local and then send from client to public server ip, but with no luck.

From local client ip to local server ip it is working.

2 Answers 2

There’s no reason this should give you any problems, provided that one side is not behind NAT and the side that’s behind NAT sends the first packet. Just follow these rules:

1) On the server, check the list of all IP addresses the host has. Bind a UDP socket to each IP address. You can skip this if the server only has one public IP address and that’s the only address it will be reached on.

2) Send a UDP reply on precisely the same socket you received the request on. This is critical to ensure the source address of the reply matches the destination address.

3) Send the UDP reply to precisely the same IP address and port as you received the query on. Ignore anything the other end says about what it thinks its IP address is or what port it thinks it’s sending from.

By «the server», I mean the side that’s not behind NAT. If you have no distinction between client and server, then follow the server rules for both sides and you’ll be fine.

These rules apply whether or not a packet is, strictly speaking, a reply. They apply to any packet you expect to get to the other side.

Remember, you can’t rely on the IP/port information in the packet to tell you who the packet came from, because NAT can change it. So you will have to put sufficient information in the payload of the datagram to do that. Ideally, expect that an endpoint’s IP/port can change at any time and send all packets to the IP/port from which you last received a packet from that particular client.

Источник

Windows socket error code 10049

Профиль
Группа: Участник
Сообщений: 9
Регистрация: 7.6.2004

Репутация: нет
Всего: нет

Эксперт
pippippippip

Профиль
Группа: Участник Клуба
Сообщений: 8564
Регистрация: 24.6.2003
Где: Europe::Ukraine:: Kiev

Репутация: 5
Всего: 98

Профиль
Группа: Участник
Сообщений: 9
Регистрация: 7.6.2004

Репутация: нет
Всего: нет

Эксперт
pippippippip

Профиль
Группа: Модератор
Сообщений: 11363
Регистрация: 13.10.2004
Где: Питер

Репутация: 53
Всего: 484

Цитата
10049 Невозможно использовать запрошенный адрес для привязки в порту

Попробуй просто обычным телнетом подключиться.
Проверь, пингуется ли сервер, не мешают ли файрволы и т.п.

Что за ошибка 10049:

Цитата
WinSock Error Descriptions
WSAEADDRNOTAVAIL (10049) Cannot assign requested address.
Berkeley description: Normally results from an attempt to create a socket with an address not on this machine.
WinSock description: Partly the same as Berkeley. The «address» it refers to is the remote socket name (protocol, port and address). This error occurs when the sin_port value is zero in a sockaddr_in structure for connect() or sendto().
In Berkeley, this error also occurs when you are trying to name the local socket (assign local address and port number) with bind(), but Windows Sockets doesn’t ascribe this error to bind(), for some unknown reason.
Developer suggestions: Assume bind() will fail with this error. Let the network system assign the default local IP address by referencing INADDR_ANY in the sin_addr field of a sockaddr_in structure input to bind(). Alternately, you can get the local IP address by calling gethostname() followed by gethostbyname().

спроси у яндеска «Socket error 10049».

Профиль
Группа: Участник
Сообщений: 9
Регистрация: 7.6.2004

Репутация: нет
Всего: нет

Брутальный буратина
pippippippip

Профиль
Группа: Участник Клуба
Сообщений: 3497
Регистрация: 31.3.2002
Где: Лес

Репутация: 10
Всего: 115

Эксперт
pippippippip

Профиль
Группа: Модератор
Сообщений: 11363
Регистрация: 13.10.2004
Где: Питер

Репутация: 53
Всего: 484

Профиль
Группа: Участник
Сообщений: 9
Регистрация: 7.6.2004

Репутация: нет
Всего: нет

sceloglauxalbifacies
pippippippip

Профиль
Группа: Экс. модератор
Сообщений: 2929
Регистрация: 16.6.2006

Репутация: 5
Всего: 158

p pm on p email on p www on p im on p icq on p aim on p yim on p msn on p skype on p gtalk on p jabber on p report on p delete on p edit on p quick quote on p quote on p show on p hide on p tofaq on

1. Публиковать ссылки на вскрытые компоненты

2. Обсуждать взлом компонентов и делится вскрытыми компонентами

Если Вам помогли и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, Snowy, Poseidon, MetalFan.

0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Delphi: Сети | Следующая тема »

[ Время генерации скрипта: 0.1200 ] [ Использовано запросов: 21 ] [ GZIP включён ]

Источник

Socket Error Перечисление

Определение

Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.

Определяет коды ошибок для класса Socket.

Предпринята попытка получить доступ к объекту Socket способом, запрещенным его правами доступа.

Обычно разрешается использовать только адрес.

Указанное семейство адресов не поддерживается. Эта ошибка возвращается, если указано семейство IPv6-адресов, а стек протокола IPv6 не установлен на локальном компьютере. Эта ошибка возвращается, если указано семейство IPv4-адресов, а стек протокола IPv4 не установлен на локальном компьютере.

Выбранный IP-адрес является недопустимым в этом контексте.

На незаблокированном сокете Socket уже выполняется операция.

Удаленный узел активно отказывает в подключении.

Подключение сброшено удаленным компьютером.

В операции на сокете Socket пропущен обязательный адрес.

Выполняется правильная последовательность отключения.

Поставщиком основного сокета обнаружен недопустимый указатель адреса.

Ошибка при выполнении операции, вызванная отключением удаленного узла.

Такой узел не существует. Данное имя не является ни официальным именем узла, ни псевдонимом.

Отсутствует сетевой маршрут к указанному узлу.

Выполняется блокирующая операция.

Вызов к заблокированному сокету Socketбыл отменен.

Предоставлен недопустимый аргумент для члена объекта Socket.

Приложение инициировало перекрывающуюся операцию, которая не может быть закончена немедленно.

Объект Socket уже подключен.

У датаграммы слишком большая длина.

Приложение пытается задать значение KeepAlive для подключения, которое уже отключено.

Не существует маршрута к удаленному узлу.

Отсутствует свободное буферное пространство для операции объекта Socket.

Требуемое имя или IP-адрес не найдены на сервере имен.

Неустранимая ошибка, или не удается найти запрошенную базу данных.

Приложение пытается отправить или получить данные, а объект Socket не подключен.

Основной поставщик сокета не инициализирован.

Предпринята попытка выполнить операцию объекта Socket не на сокете.

Перекрывающаяся операция была прервана из-за закрытия объекта Socket.

Семейство адресов не поддерживается семейством протоколов.

Слишком много процессов используется основным поставщиком сокета.

Семейство протоколов не реализовано или не настроено.

Протокол не реализован или не настроен.

Для объекта Socket был использован неизвестный, недопустимый или неподдерживаемый параметр или уровень.

Неверный тип протокола для данного объекта Socket.

Запрос на отправку или получение данных отклонен, так как объект Socket уже закрыт.

Произошла неопознанная ошибка объекта Socket.

Указанный тип сокета не поддерживается в данном семействе адресов.

Операция Socket выполнена успешно.

Подсистема сети недоступна.

Истекло время ожидания попытки подключения, или произошел сбой при отклике подключенного узла.

Слишком много открытых сокетов в основном поставщике сокета.

Не удалось разрешить имя узла. Повторите попытку позже.

Указанный класс не найден.

Версия основного поставщика сокета выходит за пределы допустимого диапазона.

Операция на незаблокированном сокете не может быть закончена немедленно.

Комментарии

Большинство этих ошибок возвращаются базовым поставщиком сокета.

Источник

windows операционные системы ос программы

Adblock
detector

Обновлено: 28.01.2023

Ситуация у коллег. С утра отказался работать сервер 1С. У пользователей при подключении одна и та же ошибка. Общий сбой. Инфраструктура на базе Windows Server — 1С в связке с SQL-сервером.

Ошибка 10049(0х00002741) при подключении к серверу 1С
Ошибка 10049(0х00002741) при подключении к серверу 1С

Рассмотрим, что можно сделать при получении следующего уведомления:

server_addr=tcp://:0 descr=<адрес_ipv6> 10049(0х00002741): Требуемый адрес для своего контекста неверен. ; <адрес_ipv4> 10049(0х00002741): Требуемый адрес для своего контекста неверен. ;

Примечание

Со слов службы технической поддержки — глобальных изменений не было. Ни платформа, ни конфигурация не обновлялись. Все работало стабильно на протяжении 4 лет.

Вопрос на повестке дня: из-за чего это возникло? Остается открытым.

Варианты действий

1. Перезагрузка сервера . Банально, но в редких делах выручает.

2. Отключить или понизить приоритет ipv6 на сервере. Чтобы сервер 1С использовал подключения только ipv4. Особенности и правильный способ отключения через параметр реестра — в статье .

3. Проверка службы «Агент сервера 1С :Предприятия 8.3 (x86-64)» и возможности подключения с помощью консоли.

Если служба остановлена либо появляются другие ошибки (например, « Ошибка получения списка информационных баз »), то проблема на стороне 1С. Требуется анализ журнала/пересоздание кластера.

  • Остановить службу 1С.
  • Удалить папку кластера srvinfo (перед этим сохранить файлы ЖР).
  • Запустить службу 1С;
  • Создать базы на кластере 1С заново.

Опционально — проверка работы MS SQL . В данном событии — сервер СУБД работал, службы были в активном состоянии, базы в порядке.

4. Переустановка сервера 1С . Крайний вариант — переустановите платформу с компонентами сервера.

✅ В описываемом случае помогла переустановка платформы. Сервер 1С стартовал и стал принимать подключения влёгкую. Как и требовалось.

Другие статьи по теме настройки сервера 1С

  1. Периодическая загрузка процессора на сервере 1С .
  2. Если не работает отладка на сервере 1С .
  3. Как очистить кэш сервера 1С .
  4. Если 1С выдает «Ошибка соединения с сервером 1С:Предприятие» .
  5. Что делать, если не запускается агент сервера 1С .

⚡ Подписывайтесь на канал или задавайте вопрос на сайте — постараемся помочь всеми техническими силами. Безопасной и производительной работы в Windows и 1С.

Решение

bind() Функция используется для указания того, какой адрес серверной системы используется для приема соединений от удаленных клиентов, а не для указания, какому удаленному клиенту разрешено подключаться к серверу. bind() Функция может использоваться только с адресами, которые действительны для самого сервера, но не для адресов удаленных устройств или хостов.

Чтобы определить, какому удаленному хосту разрешено подключаться к вашему серверу, вам необходимо принять подключение и подтвердить удаленный адрес в это время. Если адрес не правильный, соединение закрывается.

В общем, вы хотите использовать INADDR_ANY если ваш сервер не является многодомным (более одного физического подключения к нескольким сетям), и только тогда, если вы пытаетесь ограничить подключения к одной из сетей, к которым подключен ваш сервер.

Ошибка Winsock 10049 пытается связать

У меня проблема с подключением к серверу. При попытке привязать сервер к IP-адресу моего внешнего устройства я получил ошибку winsock: 10049 Невозможно назначить запрошенный адрес. Использование локального сервера работает правильно.
Этот IP-адрес: 192.168.0.202 пинг успешно.
Я работал на win8.1. Я отключил брандмауэр и Windows Defender, и это не помогло.

Ошибка 10011 при запуске игры

Утвержденное решение

  • Отметить как новое
  • Закладка
  • Подписаться
  • Электронная почта другу

qHarDwareExs1tE p

@VV4L0D4R
Всё по номерам
1.Установить все доступные обновления Windows.перезагрузка компа.
2.Закрытие программ и оверлеев, работающих в фоновом режиме.
3.в Свойствах игры в Библиотеке Ориджин отключить внутриигровой экран.перезагрузка компа.
4.Восстановите игру в Origin. В клиенте Origin щелкните правой кнопкой мыши Apex Legends и выберите «восстановить».перезагрузка компа.

Другие решения

Winsock возвращает флаг ошибки 10049 (WSAEADDRNOTAVAIL) через свой API WSAGetLastError всякий раз, когда приложение пытается связаться с неверным IP-адресом.

вы получите список адресов ip4 / ip6, затем вы можете выбрать один из них и привязать свой сервер, однако этот метод действительно скучный, поэтому альтернативой является привязка к INADDR_ANY так что вы позволяете системе делать работу за вас.

Утвержденное решение

Зарегистрировал карточку VISA. Пришла СМС, что благополучно списано 60 рублей. При попытке купить Dragon Age 2 для Мак выдает ошибку 10049. Ок — удаляю карточку, добавляю снова — опять списывает 60 рублей. При попытке купить игру — опять двадцать пять, извините, 10049. Проблем с картой нет ни у App Store, ни у Microsoft, ни у Parallels. Я так понимаю, что при списывании 60 рублей (два раза уже) карточка проверяется на валидность. Деньги ушли — значит карта валидна. Так какого, простите, я тогда не могу купить то что мне надо?

  • Отметить как новое
  • Закладка
  • Подписаться
  • Электронная почта другу

LiBever

@KLNHOMEALONE wrote:

Зарегистрировал карточку VISA. Пришла СМС, что благополучно списано 60 рублей. При попытке купить Dragon Age 2 для Мак выдает ошибку 10049. Ок — удаляю карточку, добавляю снова — опять списывает 60 рублей. При попытке купить игру — опять двадцать пять, извините, 10049. Проблем с картой нет ни у App Store, ни у Microsoft, ни у Parallels. Я так понимаю, что при списывании 60 рублей (два раза уже) карточка проверяется на валидность. Деньги ушли — значит карта валидна. Так какого, простите, я тогда не могу купить то что мне надо?

В этой статье вы можете найти свой код ошибки
Код ошибки 9028, 10049
Невозможно обработать заказ из-за проблемы с выбранным способом оплаты.
Убедитесь в правильности введенных данных, воспользуйтесь другим способом оплаты или повторите попытку позднее.

Попробуйте использовать другой способ оплаты, возможно что-то не так с вашым нынешним способом.

Читайте также:

  • Как стать шаманом в реальной жизни
  • Как вырезать часть карты в osu
  • Как сделать ведьмака в dark souls 3
  • Как нарисовать город в майнкрафте
  • Stalker x ray multiplayer extension defence как играть

i wrote a class encapsulating some of the winsock functions to imitate a simple TCP socket for my needs…

When i try to run a simple connect-and-send-data-to-server test the «client» fails on its call to connect with the error code of 10049 (WSAEADDRNOTAVAIL) connect function on MSDN

What I am doing is (code below):
Server:

  1. Create a Server Socket -> Bind it to Port 12345
  2. Put the Socket in listen mode
  3. Call accept

Client

  1. Create a socket -> Bind it to a random port
  2. Call Connect: connect to localhost, port 12345

=> the call to connect fails with Error 10049, as described above

Here is the main function including the «server»:

HANDLE hThread = NULL;
Inc::CSocketTCP ServerSock;
Inc::CSocketTCP ClientSock;

try
{

    ServerSock.Bind(L"", L"12345");
    ServerSock.Listen(10);

    //Spawn the senders-thread
    hThread = (HANDLE)_beginthreadex(nullptr, 0, Procy, nullptr, 0, nullptr);

    //accept
    ServerSock.Accept(ClientSock);


    //Adjust the maximum packet size
    ClientSock.SetPacketSize(100);


    //receive data
    std::wstring Data;
    ClientSock.Receive(Data);

    std::wcout << "Received:t" << Data << std::endl;
}
catch(std::exception& e)
{...

Client thread function

unsigned int WINAPI Procy(void* p)

{

Sleep(1500);
try{
    Inc::CSocketTCP SenderSock;
    SenderSock.Bind(L"", L"123456");

    SenderSock.Connect(L"localhost", L"12345");


    //Adjust packet size
    SenderSock.SetPacketSize(100);

    //Send Data
    std::wstring Data = L"Hello Bello!";
    SenderSock.Send(Data);
}
catch(std::exception& e)
{
    std::wcout << e.what() << std::endl;
}...

The Connect-Function

    int Inc::CSocketTCP::Connect(const std::wstring& IP, const std::wstring& Port)
{
    //NOTE: assert that the socket is valid
    assert(m_Socket != INVALID_SOCKET);

    //for debuggin: convert WStringToString here
    std::string strIP = WStringToString(IP), strPort = WStringToString(Port);

    Incgetaddrinfo AddyResolver;
    addrinfo hints = {}, *pFinal = nullptr;

    hints.ai_family = AF_INET;

    //resolve the ip/port-combination for the connection process
    INT Ret = AddyResolver(strIP.c_str(), strPort.c_str(), &hints, &pFinal);
    if(Ret)
    {
        //error handling: throw an error description
        std::string ErrorString("Resolving Process failed (Connect): ");
        ErrorString.append(Inc::NumberToString<INT>(Ret));
        throw(std::runtime_error(ErrorString.c_str()));
    }


    /*---for debbuging---*/
    sockaddr_in *pP = (sockaddr_in*)(pFinal->ai_addr);
    u_short Porty = ntohs(pP->sin_port);
    char AddBuffer[20] = "";

    InetNtopA(AF_INET, (PVOID)&pP->sin_addr, AddBuffer, 20);
    /*--------------------------------------------------------*/


    if(connect(m_Socket, pFinal->ai_addr, pFinal->ai_addrlen) == SOCKET_ERROR)
    {
        int ErrorCode = WSAGetLastError();
        if((ErrorCode == WSAETIMEDOUT) || (ErrorCode == WSAEHOSTUNREACH) || (ErrorCode == WSAENETUNREACH))
        {
            //Just Unreachable
            return TCP_TARGETUNREACHABLE;
        }

        //real errors now
        std::string ErrorString("Connection Process failed: ");
        ErrorString.append(Inc::NumberToString<int>(ErrorCode));
        throw(std::runtime_error(ErrorString.c_str()));
    }

    return TCP_SUCCESS;
}

Additional Information:
-Incgetaddrinfo is a function object encapuslating getaddrinfo…
-Noone of the server functions return any error and work as expected when stepping through them using the debugger or when letting them run solely…

I’d be glad to hear your suggestions what the rpoblem might be…

Edit: It works when I dont connect to ("localhost","12345"), but to ("",12345)
When look into the address resolution process of getaddrinfo it gives 127.0.0.1 for "localhost" and my real IP for ""

Why doesn’t it work with my loopback-IP?

  • Remove From My Forums
  • Question

  • Hi,

    I’m writing a program to connect to a bluetooth device using Winsock.  In discovery mode, I can find the device, but when I try to connect() I always get the error 10049 (WSAEADDRNOTAVAIL — Address not available). What is the problem?

    		WSADATA wsaData;
    		if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0)
    			return (EXIT_FAILURE);
    		
    		if ((_socket	= socket(AF_BT, SOCK_STREAM, BTHPROTO_RFCOMM)) == INVALID_SOCKET)
    			return (EXIT_FAILURE);
    
    		SOCKADDR_BTH sa;
    		std::memset(&sa, 0, sizeof(sa));
    		int nSizeInput = sizeof(sa);
    		int result = WSAStringToAddress(_address, AF_BTH, NULL, (LPSOCKADDR)&sa, &nSizeInput);
    
    		// To validate the address...
    		char  addressStr[64] = {0};
    		DWORD  dwSizeOfStr = sizeof(addressStr);
    		WSAAddressToStringA((LPSOCKADDR)&sa, nSizeInput, NULL, addressStr, &dwSizeOfStr);
    
    		result = connect(_socket, (SOCKADDR*)&sa, sizeof(sa));
    
    

Answers

  • There’s a sample that covers this in the WM6 SDK:
    Windows Mobile 6 SDKSamplesPocketPCCPPwin32BluetoothBthChat

    Try setting the addressFamily member of SOCKADDR_BTH to AF_BT.

    Also, try setting the btAddr member to one of the devices returned from WSALookupServiceNext.
    http://msdn.microsoft.com/en-us/library/aa916570.aspx

    -PaulH

    • Marked as answer by

      Tuesday, March 1, 2011 8:15 AM

I have a problem with server connection. When I try to bind the server to my external device IP I got a winsock error: 10049 Cannot assign requested address. Using localhost server works correctly.
This IP address: 192.168.0.202 ping successfully.
I worked on win8.1. I turned off firewall and windows defender and it did not help.

Code with server implementation has been taken from http://www.planetchili.net/forum/viewtopic.php?f=3&t=3433

#include "Server.h"

Server::Server(int PORT, bool BroadcastPublically) //Port = port to broadcast on. BroadcastPublically = false if server is not open to the public (people outside of your router), true = server is open to everyone (assumes that the port is properly forwarded on router settings)
{
    //Winsock Startup
    WSAData wsaData;
    WORD DllVersion = MAKEWORD(2, 1);
    if (WSAStartup(DllVersion, &wsaData) != 0) //If WSAStartup returns anything other than 0, then that means an error has occured in the WinSock Startup.
    {
        MessageBoxA(NULL, "WinSock startup failed", "Error", MB_OK | MB_ICONERROR);
        exit(1);
    }


    addr.sin_addr.s_addr = inet_addr("192.168.0.202"); 
    addr.sin_port = htons(1234); //Port
    addr.sin_family = AF_INET; //IPv4 Socket

    sListen = socket(AF_INET, SOCK_STREAM, NULL); //Create socket to listen for new connections
    if (bind(sListen, (SOCKADDR*)&addr, sizeof(addr)) == SOCKET_ERROR) //Bind the address to the socket, if we fail to bind the address..
    {
        std::string ErrorMsg = "Failed to bind the address to our listening socket. Winsock Error:" + std::to_string(WSAGetLastError());
        MessageBoxA(NULL, ErrorMsg.c_str(), "Error", MB_OK | MB_ICONERROR);
        exit(1);
    }
    if (listen(sListen, SOMAXCONN) == SOCKET_ERROR) //Places sListen socket in a state in which it is listening for an incoming connection. Note:SOMAXCONN = Socket Oustanding Max Connections, if we fail to listen on listening socket...
    {
        std::string ErrorMsg = "Failed to listen on listening socket. Winsock Error:" + std::to_string(WSAGetLastError());
        MessageBoxA(NULL, ErrorMsg.c_str(), "Error", MB_OK | MB_ICONERROR);
        exit(1);
    }
    serverptr = this;
}

bool Server::ListenForNewConnection()
{
    SOCKET newConnection = accept(sListen, (SOCKADDR*)&addr, &addrlen); //Accept a new connection
    if (newConnection == 0) //If accepting the client connection failed
    {
        std::cout << "Failed to accept the client's connection." << std::endl;
        return false;
    }
    else //If client connection properly accepted
    {
        std::cout << "Client Connected! ID:" << TotalConnections << std::endl;
        Connections[TotalConnections] = newConnection; //Set socket in array to be the newest connection before creating the thread to handle this client's socket.
        CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)ClientHandlerThread, (LPVOID)(TotalConnections), NULL, NULL); //Create Thread to handle this client. The index in the socket array for this thread is the value (i).
        //std::string MOTD = "MOTD: Welcome! This is the message of the day!.";
        //SendString(TotalConnections, MOTD);
        TotalConnections += 1; //Incremenent total # of clients that have connected
        return true;
    }
}

bool Server::ProcessPacket(int ID, Packet _packettype)
{
    switch (_packettype)
    {
    case P_ChatMessage: //Packet Type: chat message
    {
        std::string Message; //string to store our message we received
        if (!GetString(ID, Message)) //Get the chat message and store it in variable: Message
            return false; //If we do not properly get the chat message, return false
                          //Next we need to send the message out to each user
        for (int i = 0; i < TotalConnections; i++)
        {
            if (i == ID) //If connection is the user who sent the message...
                continue;//Skip to the next user since there is no purpose in sending the message back to the user who sent it.
            if (!SendString(i, Message)) //Send message to connection at index i, if message fails to be sent...
            {
                std::cout << "Failed to send message from client ID: " << ID << " to client ID: " << i << std::endl;
            }
        }
        //std::cout << "Processed chat message packet from user ID: " << ID << std::endl;

        if(Message == "go")
            std::cout << "MESSAGE:GO!"  << std::endl;
        else if(Message == "left")
            std::cout << "MESSAGE: GO LEFT!"  << std::endl;
        else if (Message == "right")
            std::cout << "MESSAGE:GO RIGHT!" << std::endl;
        else
            std::cout << "MESSAGE:DO NOTHING!" << std::endl;
        break;
    }

    default: //If packet type is not accounted for
    {
        std::cout << "Unrecognized packet: " << _packettype << std::endl; //Display that packet was not found
        break;
    }
    }
    return true;
}

void Server::ClientHandlerThread(int ID) //ID = the index in the SOCKET Connections array
{
    Packet PacketType;
    while (true)
    {
        if (!serverptr->GetPacketType(ID, PacketType)) //Get packet type
            break; //If there is an issue getting the packet type, exit this loop
        if (!serverptr->ProcessPacket(ID, PacketType)) //Process packet (packet type)
            break; //If there is an issue processing the packet, exit this loop
    }
    std::cout << "Lost connection to client ID: " << ID << std::endl;
    closesocket(serverptr->Connections[ID]);
    return;
}

Any ideas?

I have a problem with server connection. When I try to bind the server to my external device IP I got a winsock error: 10049 Cannot assign requested address. Using localhost server works correctly.
This IP address: 192.168.0.202 ping successfully.
I worked on win8.1. I turned off firewall and windows defender and it did not help.

Code with server implementation has been taken from http://www.planetchili.net/forum/viewtopic.php?f=3&t=3433

#include "Server.h"

Server::Server(int PORT, bool BroadcastPublically) //Port = port to broadcast on. BroadcastPublically = false if server is not open to the public (people outside of your router), true = server is open to everyone (assumes that the port is properly forwarded on router settings)
{
    //Winsock Startup
    WSAData wsaData;
    WORD DllVersion = MAKEWORD(2, 1);
    if (WSAStartup(DllVersion, &wsaData) != 0) //If WSAStartup returns anything other than 0, then that means an error has occured in the WinSock Startup.
    {
        MessageBoxA(NULL, "WinSock startup failed", "Error", MB_OK | MB_ICONERROR);
        exit(1);
    }


    addr.sin_addr.s_addr = inet_addr("192.168.0.202"); 
    addr.sin_port = htons(1234); //Port
    addr.sin_family = AF_INET; //IPv4 Socket

    sListen = socket(AF_INET, SOCK_STREAM, NULL); //Create socket to listen for new connections
    if (bind(sListen, (SOCKADDR*)&addr, sizeof(addr)) == SOCKET_ERROR) //Bind the address to the socket, if we fail to bind the address..
    {
        std::string ErrorMsg = "Failed to bind the address to our listening socket. Winsock Error:" + std::to_string(WSAGetLastError());
        MessageBoxA(NULL, ErrorMsg.c_str(), "Error", MB_OK | MB_ICONERROR);
        exit(1);
    }
    if (listen(sListen, SOMAXCONN) == SOCKET_ERROR) //Places sListen socket in a state in which it is listening for an incoming connection. Note:SOMAXCONN = Socket Oustanding Max Connections, if we fail to listen on listening socket...
    {
        std::string ErrorMsg = "Failed to listen on listening socket. Winsock Error:" + std::to_string(WSAGetLastError());
        MessageBoxA(NULL, ErrorMsg.c_str(), "Error", MB_OK | MB_ICONERROR);
        exit(1);
    }
    serverptr = this;
}

bool Server::ListenForNewConnection()
{
    SOCKET newConnection = accept(sListen, (SOCKADDR*)&addr, &addrlen); //Accept a new connection
    if (newConnection == 0) //If accepting the client connection failed
    {
        std::cout << "Failed to accept the client's connection." << std::endl;
        return false;
    }
    else //If client connection properly accepted
    {
        std::cout << "Client Connected! ID:" << TotalConnections << std::endl;
        Connections[TotalConnections] = newConnection; //Set socket in array to be the newest connection before creating the thread to handle this client's socket.
        CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)ClientHandlerThread, (LPVOID)(TotalConnections), NULL, NULL); //Create Thread to handle this client. The index in the socket array for this thread is the value (i).
        //std::string MOTD = "MOTD: Welcome! This is the message of the day!.";
        //SendString(TotalConnections, MOTD);
        TotalConnections += 1; //Incremenent total # of clients that have connected
        return true;
    }
}

bool Server::ProcessPacket(int ID, Packet _packettype)
{
    switch (_packettype)
    {
    case P_ChatMessage: //Packet Type: chat message
    {
        std::string Message; //string to store our message we received
        if (!GetString(ID, Message)) //Get the chat message and store it in variable: Message
            return false; //If we do not properly get the chat message, return false
                          //Next we need to send the message out to each user
        for (int i = 0; i < TotalConnections; i++)
        {
            if (i == ID) //If connection is the user who sent the message...
                continue;//Skip to the next user since there is no purpose in sending the message back to the user who sent it.
            if (!SendString(i, Message)) //Send message to connection at index i, if message fails to be sent...
            {
                std::cout << "Failed to send message from client ID: " << ID << " to client ID: " << i << std::endl;
            }
        }
        //std::cout << "Processed chat message packet from user ID: " << ID << std::endl;

        if(Message == "go")
            std::cout << "MESSAGE:GO!"  << std::endl;
        else if(Message == "left")
            std::cout << "MESSAGE: GO LEFT!"  << std::endl;
        else if (Message == "right")
            std::cout << "MESSAGE:GO RIGHT!" << std::endl;
        else
            std::cout << "MESSAGE:DO NOTHING!" << std::endl;
        break;
    }

    default: //If packet type is not accounted for
    {
        std::cout << "Unrecognized packet: " << _packettype << std::endl; //Display that packet was not found
        break;
    }
    }
    return true;
}

void Server::ClientHandlerThread(int ID) //ID = the index in the SOCKET Connections array
{
    Packet PacketType;
    while (true)
    {
        if (!serverptr->GetPacketType(ID, PacketType)) //Get packet type
            break; //If there is an issue getting the packet type, exit this loop
        if (!serverptr->ProcessPacket(ID, PacketType)) //Process packet (packet type)
            break; //If there is an issue processing the packet, exit this loop
    }
    std::cout << "Lost connection to client ID: " << ID << std::endl;
    closesocket(serverptr->Connections[ID]);
    return;
}

Any ideas?

У меня проблема с подключением к серверу. При попытке привязать сервер к IP-адресу моего внешнего устройства я получил ошибку winsock: 10049 Невозможно назначить запрошенный адрес. Использование локального сервера работает правильно.
Этот IP-адрес: 192.168.0.202 пинг успешно.
Я работал на win8.1. Я отключил брандмауэр и Windows Defender, и это не помогло.

Код с серверной реализацией взят из http://www.planetchili.net/forum/viewtopic.php?f=3&т = 3433

#include "Server.h"
Server::Server(int PORT, bool BroadcastPublically) //Port = port to broadcast on. BroadcastPublically = false if server is not open to the public (people outside of your router), true = server is open to everyone (assumes that the port is properly forwarded on router settings)
{
//Winsock Startup
WSAData wsaData;
WORD DllVersion = MAKEWORD(2, 1);
if (WSAStartup(DllVersion, &wsaData) != 0) //If WSAStartup returns anything other than 0, then that means an error has occured in the WinSock Startup.
{
MessageBoxA(NULL, "WinSock startup failed", "Error", MB_OK | MB_ICONERROR);
exit(1);
}addr.sin_addr.s_addr = inet_addr("192.168.0.202");
addr.sin_port = htons(1234); //Port
addr.sin_family = AF_INET; //IPv4 Socket

sListen = socket(AF_INET, SOCK_STREAM, NULL); //Create socket to listen for new connections
if (bind(sListen, (SOCKADDR*)&addr, sizeof(addr)) == SOCKET_ERROR) //Bind the address to the socket, if we fail to bind the address..
{
std::string ErrorMsg = "Failed to bind the address to our listening socket. Winsock Error:" + std::to_string(WSAGetLastError());
MessageBoxA(NULL, ErrorMsg.c_str(), "Error", MB_OK | MB_ICONERROR);
exit(1);
}
if (listen(sListen, SOMAXCONN) == SOCKET_ERROR) //Places sListen socket in a state in which it is listening for an incoming connection. Note:SOMAXCONN = Socket Oustanding Max Connections, if we fail to listen on listening socket...
{
std::string ErrorMsg = "Failed to listen on listening socket. Winsock Error:" + std::to_string(WSAGetLastError());
MessageBoxA(NULL, ErrorMsg.c_str(), "Error", MB_OK | MB_ICONERROR);
exit(1);
}
serverptr = this;
}

bool Server::ListenForNewConnection()
{
SOCKET newConnection = accept(sListen, (SOCKADDR*)&addr, &addrlen); //Accept a new connection
if (newConnection == 0) //If accepting the client connection failed
{
std::cout << "Failed to accept the client's connection." << std::endl;
return false;
}
else //If client connection properly accepted
{
std::cout << "Client Connected! ID:" << TotalConnections << std::endl;
Connections[TotalConnections] = newConnection; //Set socket in array to be the newest connection before creating the thread to handle this client's socket.
CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)ClientHandlerThread, (LPVOID)(TotalConnections), NULL, NULL); //Create Thread to handle this client. The index in the socket array for this thread is the value (i).
//std::string MOTD = "MOTD: Welcome! This is the message of the day!.";
//SendString(TotalConnections, MOTD);
TotalConnections += 1; //Incremenent total # of clients that have connected
return true;
}
}

bool Server::ProcessPacket(int ID, Packet _packettype)
{
switch (_packettype)
{
case P_ChatMessage: //Packet Type: chat message
{
std::string Message; //string to store our message we received
if (!GetString(ID, Message)) //Get the chat message and store it in variable: Message
return false; //If we do not properly get the chat message, return false
//Next we need to send the message out to each user
for (int i = 0; i < TotalConnections; i++)
{
if (i == ID) //If connection is the user who sent the message...
continue;//Skip to the next user since there is no purpose in sending the message back to the user who sent it.
if (!SendString(i, Message)) //Send message to connection at index i, if message fails to be sent...
{
std::cout << "Failed to send message from client ID: " << ID << " to client ID: " << i << std::endl;
}
}
//std::cout << "Processed chat message packet from user ID: " << ID << std::endl;

if(Message == "go")
std::cout << "MESSAGE:GO!"  << std::endl;
else if(Message == "left")
std::cout << "MESSAGE: GO LEFT!"  << std::endl;
else if (Message == "right")
std::cout << "MESSAGE:GO RIGHT!" << std::endl;
else
std::cout << "MESSAGE:DO NOTHING!" << std::endl;
break;
}

default: //If packet type is not accounted for
{
std::cout << "Unrecognized packet: " << _packettype << std::endl; //Display that packet was not found
break;
}
}
return true;
}

void Server::ClientHandlerThread(int ID) //ID = the index in the SOCKET Connections array
{
Packet PacketType;
while (true)
{
if (!serverptr->GetPacketType(ID, PacketType)) //Get packet type
break; //If there is an issue getting the packet type, exit this loop
if (!serverptr->ProcessPacket(ID, PacketType)) //Process packet (packet type)
break; //If there is an issue processing the packet, exit this loop
}
std::cout << "Lost connection to client ID: " << ID << std::endl;
closesocket(serverptr->Connections[ID]);
return;
}

Есть идеи?

0

Решение

bind() Функция используется для указания того, какой адрес серверной системы используется для приема соединений от удаленных клиентов, а не для указания, какому удаленному клиенту разрешено подключаться к серверу. bind() Функция может использоваться только с адресами, которые действительны для самого сервера, но не для адресов удаленных устройств или хостов.

Чтобы определить, какому удаленному хосту разрешено подключаться к вашему серверу, вам необходимо принять подключение и подтвердить удаленный адрес в это время. Если адрес не правильный, соединение закрывается.

В общем, вы хотите использовать INADDR_ANY если ваш сервер не является многодомным (более одного физического подключения к нескольким сетям), и только тогда, если вы пытаетесь ограничить подключения к одной из сетей, к которым подключен ваш сервер.

3

Другие решения

Winsock возвращает флаг ошибки 10049 (WSAEADDRNOTAVAIL) через свой API WSAGetLastError всякий раз, когда приложение пытается связаться с неверным IP-адресом.

привязка к определенному IP-адресу означает, что всякий раз, когда вы запускаете программу (сервер), адрес должен быть действительным (доступным), но, тем не менее, DHCP выдает вам динамические IP-адреса каждый раз, когда вы отключаете / подключаете адаптер, так что вы адрес, который вы связывали с сервером в прошлый раз недопустимо исправить его, откройте cmd и введите:

ipconfig

вы получите список адресов ip4 / ip6, затем вы можете выбрать один из них и привязать свой сервер, однако этот метод действительно скучный, поэтому альтернативой является привязка к INADDR_ANY так что вы позволяете системе делать работу за вас.

вам нужно только с клиента ввести адрес сервера и порт и подключиться.

0

I’m trying to establish a connection with a custom bluetooth device without using COM ports. However, I’m getting an error: [10049] «The requested address is not valid in its context». What am I doing wrong?

static Guid serviceClass= new Guid("4d36e978-e325-11ce-bfc1-08002be10318"); //GUID of device class

static BluetoothAddress addr = BluetoothAddress.Parse("001210160177"); //from device            
BluetoothDeviceInfo device = new BluetoothDeviceInfo(addr); 

device.SetServiceState(serviceClass, true);

Console.WriteLine(BluetoothSecurity.PairRequest(device.DeviceAddress, "0000")); //pairing my device - writes True
BluetoothEndPoint ep = new BluetoothEndPoint(addr, serviceClass);

BluetoothClient conn = new BluetoothClient(ep); //10049 error
conn.Connect(ep);
Console.WriteLine(conn.GetStream());

asked Mar 12, 2014 at 8:45

ammme's user avatar

Its all covered in the project’s documentation. :-)

In short, remove that SetServiceState line it is unnecessary/bad. Doing the pairing each time is also unnecessary and a bit slow but probably not worth changing if its working well.

Docs:

1) http://32feet.codeplex.com/documentation

  • «See section General Bluetooth Data Connections below. The BluetoothClient provides the Stream to read and write on — there is no need to use virtual COM ports»

2) http://32feet.codeplex.com/wikipage?title=General%20Bluetooth%20Data%20Connections

BluetoothAddress addr
  = BluetoothAddress.Parse("001122334455");
Guid serviceClass;
serviceClass = BluetoothService.SerialPort;
// - or - etc
// serviceClass = MyConsts.MyServiceUuid
//
var ep = new BluetoothEndPoint(addr, serviceClass);
var cli = new BluetoothClient();
cli.Connect(ep);
Stream peerStream = cli.GetStream();
peerStream.Write/Read ...

3) http://32feet.codeplex.com/wikipage?title=Errors

  • 10049 «The requested address is not valid in its context.»
  • No Service with given Service Class Id is running on the remote device

i.e. Wrong Service Class Id.

answered Mar 15, 2014 at 10:55

alanjmcf's user avatar

alanjmcfalanjmcf

3,4301 gold badge17 silver badges14 bronze badges

Here’s how it finally rolls.

device.SetServiceState(serviceClass, true); //do it before pairing
...
BluetoothClient conn = new BluetoothClient(); 
conn.Connect(ep);

Also, my mistake here:

static Guid serviceClass = new Guid("4d36e978-e325-11ce-bfc1-08002be10318"); 
//GUID of device class

Should be:

static Guid serviceClass = new Guid("00001101-0000-1000-8000-00805f9b34fb"); 
//GUID of bluetooth service

For seeing the proper GUID, refer to your device’s (not dongle’s) settings/properties. You can see them from Windows.

answered Mar 14, 2014 at 9:23

ammme's user avatar

ammmeammme

331 silver badge4 bronze badges

Я пытаюсь установить соединение с настраиваемым устройством Bluetooth без использования COM-портов. Однако я получаю сообщение об ошибке: [10049] «Запрошенный адрес недействителен в своем контексте». Что я делаю неправильно?

static Guid serviceClass= new Guid("4d36e978-e325-11ce-bfc1-08002be10318"); //GUID of device class

static BluetoothAddress addr = BluetoothAddress.Parse("001210160177"); //from device            
BluetoothDeviceInfo device = new BluetoothDeviceInfo(addr); 

device.SetServiceState(serviceClass, true);

Console.WriteLine(BluetoothSecurity.PairRequest(device.DeviceAddress, "0000")); //pairing my device - writes True
BluetoothEndPoint ep = new BluetoothEndPoint(addr, serviceClass);

BluetoothClient conn = new BluetoothClient(ep); //10049 error
conn.Connect(ep);
Console.WriteLine(conn.GetStream());

2 ответа

Лучший ответ

Все это описано в документации по проекту. :-)

Короче, удалите эту строку SetServiceState, это ненужно / плохо. Выполнять сопряжение каждый раз также необязательно и немного медленно, но, вероятно, не стоит менять, если оно работает хорошо.

Docs :

1) http://32feet.codeplex.com/documentation

  • «См. Раздел« Общие подключения данных Bluetooth »ниже. BluetoothClient предоставляет поток для чтения и записи — нет необходимости использовать виртуальные COM-порты»

2) http://32feet.codeplex.com/wikipage?title=General % 20Bluetooth% 20Data% 20Connections

BluetoothAddress addr
  = BluetoothAddress.Parse("001122334455");
Guid serviceClass;
serviceClass = BluetoothService.SerialPort;
// - or - etc
// serviceClass = MyConsts.MyServiceUuid
//
var ep = new BluetoothEndPoint(addr, serviceClass);
var cli = new BluetoothClient();
cli.Connect(ep);
Stream peerStream = cli.GetStream();
peerStream.Write/Read ...

3) http://32feet.codeplex.com/wikipage?title=Errors

  • 10049 «Запрошенный адрес недействителен в своем контексте.»
  • На удаленном устройстве не работает служба с данным идентификатором класса обслуживания

То есть Неверный идентификатор класса обслуживания.


2

alanjmcf
15 Мар 2014 в 14:55

Вот как наконец катится.

device.SetServiceState(serviceClass, true); //do it before pairing
...
BluetoothClient conn = new BluetoothClient(); 
conn.Connect(ep);

Также моя ошибка здесь:

static Guid serviceClass = new Guid("4d36e978-e325-11ce-bfc1-08002be10318"); 
//GUID of device class

Должно быть:

static Guid serviceClass = new Guid("00001101-0000-1000-8000-00805f9b34fb"); 
//GUID of bluetooth service

Чтобы увидеть правильный GUID, обратитесь к настройкам / свойствам вашего устройства (не ключа). Вы можете увидеть их из Windows.


0

ammme
14 Мар 2014 в 13:23

Я пытаюсь установить соединение с пользовательским устройством Bluetooth без использования COM-портов. Однако я получаю сообщение об ошибке: [10049] «Запрошенный адрес недопустим в своем контексте». Что я делаю неправильно?

static Guid serviceClass= new Guid("4d36e978-e325-11ce-bfc1-08002be10318"); //GUID of device class

static BluetoothAddress addr = BluetoothAddress.Parse("001210160177"); //from device            
BluetoothDeviceInfo device = new BluetoothDeviceInfo(addr); 

device.SetServiceState(serviceClass, true);

Console.WriteLine(BluetoothSecurity.PairRequest(device.DeviceAddress, "0000")); //pairing my device - writes True
BluetoothEndPoint ep = new BluetoothEndPoint(addr, serviceClass);

BluetoothClient conn = new BluetoothClient(ep); //10049 error
conn.Connect(ep);
Console.WriteLine(conn.GetStream());

2014-03-12 08:45

2
ответа

Решение

Все это отражено в документации проекта.:-)

Короче убери что SetServiceState линия это ненужно / плохо. Выполнение сопряжения каждый раз также не является необходимым и немного медленным, но, вероятно, не стоит менять его, если оно работает хорошо.

Docs:

1) http://32feet.codeplex.com/documentation

  • «См. Раздел» Общие соединения Bluetooth для передачи данных «ниже. BluetoothClient предоставляет поток для чтения и записи — нет необходимости использовать виртуальные COM-порты»

2) http://32feet.codeplex.com/wikipage?title=General%20Bluetooth%20Data%20Connections

BluetoothAddress addr
  = BluetoothAddress.Parse("001122334455");
Guid serviceClass;
serviceClass = BluetoothService.SerialPort;
// - or - etc
// serviceClass = MyConsts.MyServiceUuid
//
var ep = new BluetoothEndPoint(addr, serviceClass);
var cli = new BluetoothClient();
cli.Connect(ep);
Stream peerStream = cli.GetStream();
peerStream.Write/Read ...

3) http://32feet.codeplex.com/wikipage?title=Errors

  • 10049 «Запрошенный адрес недопустим в своем контексте.»
  • На удаленном устройстве не запущена служба с данным идентификатором класса обслуживания

т.е. неправильный идентификатор класса обслуживания.


user35049

15 мар ’14 в 10:55
2014-03-15 10:55

2014-03-15 10:55

Вот как это наконец катится.

device.SetServiceState(serviceClass, true); //do it before pairing
...
BluetoothClient conn = new BluetoothClient(); 
conn.Connect(ep);

Также моя ошибка здесь:

static Guid serviceClass = new Guid("4d36e978-e325-11ce-bfc1-08002be10318"); 
//GUID of device class

Должно быть:

static Guid serviceClass = new Guid("00001101-0000-1000-8000-00805f9b34fb"); 
//GUID of bluetooth service

Чтобы увидеть правильный GUID, обратитесь к настройкам / свойствам вашего устройства (не ключа). Вы можете увидеть их из Windows.

2014-03-14 09:23

  • Remove From My Forums
  • Question

  • Hi,

    I’m writing a program to connect to a bluetooth device using Winsock.  In discovery mode, I can find the device, but when I try to connect() I always get the error 10049 (WSAEADDRNOTAVAIL — Address not available). What is the problem?

    		WSADATA wsaData;
    		if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0)
    			return (EXIT_FAILURE);
    		
    		if ((_socket	= socket(AF_BT, SOCK_STREAM, BTHPROTO_RFCOMM)) == INVALID_SOCKET)
    			return (EXIT_FAILURE);
    
    		SOCKADDR_BTH sa;
    		std::memset(&sa, 0, sizeof(sa));
    		int nSizeInput = sizeof(sa);
    		int result = WSAStringToAddress(_address, AF_BTH, NULL, (LPSOCKADDR)&sa, &nSizeInput);
    
    		// To validate the address...
    		char  addressStr[64] = {0};
    		DWORD  dwSizeOfStr = sizeof(addressStr);
    		WSAAddressToStringA((LPSOCKADDR)&sa, nSizeInput, NULL, addressStr, &dwSizeOfStr);
    
    		result = connect(_socket, (SOCKADDR*)&sa, sizeof(sa));
    
    

Answers

  • There’s a sample that covers this in the WM6 SDK:
    Windows Mobile 6 SDKSamplesPocketPCCPPwin32BluetoothBthChat

    Try setting the addressFamily member of SOCKADDR_BTH to AF_BT.

    Also, try setting the btAddr member to one of the devices returned from WSALookupServiceNext.
    http://msdn.microsoft.com/en-us/library/aa916570.aspx

    -PaulH

    • Marked as answer by

      Tuesday, March 1, 2011 8:15 AM

Я разрабатываю dll в visual-С++ для приложения на стороне клиента, чтобы подключить свой компьютер к мобильному телефону через Bluetooth. Я использую эту функцию для поиска моей службы bluetooth на телефоне (см. Код комментария!):

bool BlueRayXVR::findPairedService(GUID* guid, _SOCKET_ADDRESS* ret){
    this->checkStartup();

    HBLUETOOTH_DEVICE_FIND found_devices;

    BLUETOOTH_DEVICE_INFO device_info;
    device_info.dwSize = sizeof(device_info);

    BLUETOOTH_DEVICE_SEARCH_PARAMS search_criteria;
    search_criteria.dwSize = sizeof(BLUETOOTH_DEVICE_SEARCH_PARAMS);
    search_criteria.fReturnAuthenticated = TRUE;
    search_criteria.fReturnRemembered = FALSE;
    search_criteria.fReturnConnected = FALSE;
    search_criteria.fReturnUnknown = FALSE;
    search_criteria.fIssueInquiry = FALSE;
    search_criteria.cTimeoutMultiplier = 0;

    found_devices = BluetoothFindFirstDevice(&search_criteria, &device_info);

    if (found_devices == NULL)
    {
        _tprintf(TEXT("Error: n%sn"), getErrorMessage(WSAGetLastError(), error));
        return false;
    }

    WSAQUERYSET querySet;
    memset(&querySet, 0, sizeof(querySet));
    querySet.dwSize = sizeof(querySet);
    querySet.lpServiceClassId = guid;
    querySet.dwNameSpace = NS_BTH;

    SOCKADDR_BTH sab;
    memset (&sab, 0, sizeof(sab));
    sab.addressFamily  = AF_BTH;

    char addressAsString[1000];
    DWORD addressSize = sizeof(addressAsString);

    bool found = false;

    do
    {
        sab.btAddr = device_info.Address.ullLong;
        if (0 != WSAAddressToString((LPSOCKADDR)&sab, sizeof(sab), NULL, (LPWSTR)addressAsString, &addressSize)){
            _tprintf(TEXT("Error get the mac of the device %sn.Going to the next device."), device_info.szName);
        }
        else{
            _tprintf(TEXT("Check on device %s%s for the service.n"), device_info.szName, addressAsString);
            querySet.lpszContext =(LPWSTR) addressAsString;
            HANDLE service_lookup_handle;
            DWORD flags = LUP_FLUSHCACHE |LUP_RETURN_NAME | LUP_RETURN_ADDR | LUP_RETURN_BLOB;

            int result = WSALookupServiceBegin(&querySet, flags, &service_lookup_handle);

            if (0 == result)
            {
                BYTE buffer[2000];
                DWORD bufferLength = sizeof(buffer);
                WSAQUERYSET *pResults = (WSAQUERYSET*)&buffer;
                if(0 == WSALookupServiceNext(service_lookup_handle, flags, &bufferLength, pResults))
                {
                    _tprintf(TEXT("Service : %sn"), pResults->lpszServiceInstanceName);
                    _tprintf(TEXT("Comment : %sn"), pResults->lpszComment);
                    *ret = pResults->lpcsaBuffer->RemoteAddr;
                    found = true;

                /*  this->sock = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);                      
                    if (0 == ::connect(sock, ret->lpSockaddr, ret->iSockaddrLength))
                    {
                        printf("connected");
                        //closesocket (*sock);
                        //return TRUE;
                    }
                    wprintf(L"errore %d: %s", WSAGetLastError(), this->getErrorMessage(WSAGetLastError(), this->error));
                    */
                }
                result = WSALookupServiceEnd(service_lookup_handle);
            }
            else
                _tprintf(TEXT("%snGoing to the next device..n"), getErrorMessage(GetLastError(), error));
        }
    } while (BluetoothFindNextDevice(found_devices, &device_info) && !found);

    if(found_devices)
        BluetoothFindDeviceClose(found_devices);

    _tprintf(TEXT("No more device.n"));
    return found;
}

И этот для подключения к телефону:

bool BlueRayXVR::connect(_SOCKET_ADDRESS* host)
{
    this->sock = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM); 
    if (this->sock == INVALID_SOCKET)
    {
        _tprintf(TEXT("Failed to get bluetooth socket! %sn"), getErrorMessage(WSAGetLastError(), error));
        exit(1);
    }

    if (0 == ::connect(sock, host->lpSockaddr, host->iSockaddrLength))
    {
        printf("connectedn");
        return TRUE;
    }
    wprintf(L"errore %d: %s", WSAGetLastError(), this->getErrorMessage(WSAGetLastError(), this->error));
    return FALSE;
}

В моем приложении консоли тестирования я делаю:

       _SOCKET_ADDRESS address;
    memset (&address, 0, sizeof(address));
    if(blue->findPairedService(&blue->getDefaultGUID4XVR(), &address)){
        printf("service founded..try to connect..n");
        if(blue->connect(&address))
            blue->read();
    }

Проблема в том, что если я запускаю свой код, я всегда получаю ошибку 10049.

странно, что если я раскомментирую строки кода в функции findPairedService, и я просто делаю

       _SOCKET_ADDRESS address;
    memset (&address, 0, sizeof(address));
    if(blue->findPairedService(&blue->getDefaultGUID4XVR(), &address)){

он успешно подключается к телефону….

что не так?

Спасибо!

Я пытаюсь установить соединение с пользовательским устройством Bluetooth без использования COM-портов. Однако я получаю сообщение об ошибке: [10049] «Запрошенный адрес недопустим в своем контексте». Что я делаю неправильно?

static Guid serviceClass= new Guid("4d36e978-e325-11ce-bfc1-08002be10318"); //GUID of device class

static BluetoothAddress addr = BluetoothAddress.Parse("001210160177"); //from device            
BluetoothDeviceInfo device = new BluetoothDeviceInfo(addr); 

device.SetServiceState(serviceClass, true);

Console.WriteLine(BluetoothSecurity.PairRequest(device.DeviceAddress, "0000")); //pairing my device - writes True
BluetoothEndPoint ep = new BluetoothEndPoint(addr, serviceClass);

BluetoothClient conn = new BluetoothClient(ep); //10049 error
conn.Connect(ep);
Console.WriteLine(conn.GetStream());

2014-03-12 08:45

2
ответа

Решение

Все это отражено в документации проекта.:-)

Короче убери что SetServiceState линия это ненужно / плохо. Выполнение сопряжения каждый раз также не является необходимым и немного медленным, но, вероятно, не стоит менять его, если оно работает хорошо.

Docs:

1) http://32feet.codeplex.com/documentation

  • «См. Раздел» Общие соединения Bluetooth для передачи данных «ниже. BluetoothClient предоставляет поток для чтения и записи — нет необходимости использовать виртуальные COM-порты»

2) http://32feet.codeplex.com/wikipage?title=General%20Bluetooth%20Data%20Connections

BluetoothAddress addr
  = BluetoothAddress.Parse("001122334455");
Guid serviceClass;
serviceClass = BluetoothService.SerialPort;
// - or - etc
// serviceClass = MyConsts.MyServiceUuid
//
var ep = new BluetoothEndPoint(addr, serviceClass);
var cli = new BluetoothClient();
cli.Connect(ep);
Stream peerStream = cli.GetStream();
peerStream.Write/Read ...

3) http://32feet.codeplex.com/wikipage?title=Errors

  • 10049 «Запрошенный адрес недопустим в своем контексте.»
  • На удаленном устройстве не запущена служба с данным идентификатором класса обслуживания

т.е. неправильный идентификатор класса обслуживания.


user35049

15 мар ’14 в 10:55
2014-03-15 10:55

2014-03-15 10:55

Вот как это наконец катится.

device.SetServiceState(serviceClass, true); //do it before pairing
...
BluetoothClient conn = new BluetoothClient(); 
conn.Connect(ep);

Также моя ошибка здесь:

static Guid serviceClass = new Guid("4d36e978-e325-11ce-bfc1-08002be10318"); 
//GUID of device class

Должно быть:

static Guid serviceClass = new Guid("00001101-0000-1000-8000-00805f9b34fb"); 
//GUID of bluetooth service

Чтобы увидеть правильный GUID, обратитесь к настройкам / свойствам вашего устройства (не ключа). Вы можете увидеть их из Windows.

2014-03-14 09:23

Понравилась статья? Поделить с друзьями:
  • Код ошибки 10034 url local активация программного ключа
  • Код ошибки 10048
  • Код ошибки 10042
  • Код ошибки 10033
  • Код ошибки 1004 окко что это