Код ошибки 10049 bluetooth

Connection Failed Error Code 10049 Bluetooth We have collected for you the most relevant information on Connection Failed Error Code 10049 Bluetooth, as well as possible solutions to this problem. Take a look at the links provided and find the solution that works. Other people have encountered Connection Failed Error Code 10049 Bluetooth before […]

Содержание

  1. Connection Failed Error Code 10049 Bluetooth
  2. c++ — bluetooth winsock error 10049 on connect() — Stack .
  3. Bluetooth stopped working after updating to 10049 .
  4. Bluetooth winsock connection fail with error 10049?
  5. Connection failure 10049?? — XIM Community
  6. Connection Failed (error Code 10049) Bluetooth .Connection .
  7. How To Repair How To Fix Error 10049 (Solved)
  8. How To Repair Connect Failed Error Code 10049 Tutorial
  9. Bluetooth paired but not connected on Windows 10 — Driver Easy
  10. Connection Failure Error Code = 10049 L2 Vanir — L2 server
  11. Connection Failed Error Code 10049 Bluetooth Fixes & Solutions
  12. Error Code 10049 Bluetooth
  13. c++ — bluetooth winsock error 10049 on connect() — Stack .
  14. Bluetooth winsock connection fail with error 10049?
  15. Connection Failed (error Code 10049) Bluetooth .Connection .
  16. Connection failure 10049??
  17. How To Repair How To Fix Error 10049 (Solved)
  18. How To Repair Connect Failed Error Code 10049 Tutorial
  19. Winsock error 10049 connect() call failed
  20. Unable to connect 10049 : MapleStory2
  21. a connection is not possible code = 10049 : MapleStory2
  22. Connection Failure Error Code = 10049 L2 Vanir — L2 server
  23. Error Code 10049 Bluetooth Fixes & Solutions
  24. Error code 10049 bluetooth
  25. Asked by:
  26. Question
  27. All replies
  28. Ошибка Winsock 10049 пытается связать
  29. Решение
  30. Другие решения
  31. Как исправить проблемы с сопряжением по Bluetooth

Connection Failed Error Code 10049 Bluetooth

We have collected for you the most relevant information on Connection Failed Error Code 10049 Bluetooth, as well as possible solutions to this problem. Take a look at the links provided and find the solution that works. Other people have encountered Connection Failed Error Code 10049 Bluetooth before you, so use the ready-made solutions.

c++ — bluetooth winsock error 10049 on connect() — Stack .

    https://stackoverflow.com/questions/2859029/bluetooth-winsock-error-10049-on-connect
    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!):

Bluetooth stopped working after updating to 10049 .

    https://answers.microsoft.com/en-us/insider/forum/insider_wintp-insider_devices-insiderplat_pc/bluetooth-stopped-working-after-updating-to-10049/2276620d-f51a-4af8-a554-511867820575
    Apr 23, 2015 · 1. Running Windows 10 TP build 10049 x64, with Bluetooth adapter drivers installed. 2. Place the Bluetooth device in pairing mode, and click «Pair» under the device in the Bluetooth Settings panel. 3. Observe the pairing process complete. The device will show as «Connected» for a few seconds. 4. The device disconnects, reverting to «Paired .

Bluetooth winsock connection fail with error 10049?

    https://social.msdn.microsoft.com/forums/en-US/e6fa6277-9a5b-49af-baa8-0c6dd5dbbb52/bluetooth-winsock-connection-fail-with-error-10049
    Oct 06, 2017 · There’s a sample that covers this in the WM6 SDK: Windows Mobile 6 SDKSamplesPocketPCCPPwin32BluetoothBthChat Try setting the addressFamily member of SOCKADDR .
    https://community.xim.tech/index.php?topic=31341.0
    Go to run in windows 7 or search in windows 8 and type «services.msc» scroll down till you see «Bluetooth Support Service» open that service and set it to automatic and then start the service. That’s how I fixed my connection issues.

Connection Failed (error Code 10049) Bluetooth .Connection .

    https://vdocuments.mx/connection-failed-error-code-10049-bluetooth-connection-failed-error-code.html
    Aug 29, 2018 · Connection Failed (error Code 10049) Bluetooth Bluetooth USB/VID_13D3&PID_3362&REV_0001 error code 43 :(. 1. 2 months Fixed screen rotation issue on Yoga 2 (wouldn’t…

How To Repair How To Fix Error 10049 (Solved)

    http://winload.org/how-to-fix-error-10049.html
    Colorado Springs, CO USA Click here to download error 10049 Repair problem, then proceed with the next solution. You will then have your options available, such as .

How To Repair Connect Failed Error Code 10049 Tutorial

    http://iembra.org/error-code/connect-failed-error-code-10049.php
    Connection Failure Error Code 10049 WSAEINPROGRESS 10036 Operation now in progress. For example, this error is returned if sendto is called with the remote address of ADDR_ANY.

Bluetooth paired but not connected on Windows 10 — Driver Easy

    https://www.drivereasy.com/knowledge/fix-bluetooth-paired-but-not-connected-error-on-windows-10/
    Jun 23, 2017 · Solution 1: Restart your Bluetooth service On your keyboard, press the Windows logo key and R at the same time to invoke the Run box. Type services.msc and press Enter. Right-click on Bluetooth related services (like Bluetooth Handsfree Service, Bluetooth Support Service) and click Restart.Author: April Cai

Connection Failure Error Code = 10049 L2 Vanir — L2 server

    https://www.l2vanir.com/forum/connection-failure-error-code-10049
    Re: Connection Failure Error Code = 10049 Are you trying to update? You must double click the l2.exe file from the system folder. Could you attach an screenshot and tell us what exe or file are you clicking please?

Connection Failed Error Code 10049 Bluetooth Fixes & Solutions

We are confident that the above descriptions of Connection Failed Error Code 10049 Bluetooth and how to fix it will be useful to you. If you have another solution to Connection Failed Error Code 10049 Bluetooth or some notes on the existing ways to solve it, then please drop us an email.

Источник

Error Code 10049 Bluetooth

We have collected for you the most relevant information on Error Code 10049 Bluetooth, as well as possible solutions to this problem. Take a look at the links provided and find the solution that works. Other people have encountered Error Code 10049 Bluetooth before you, so use the ready-made solutions.

c++ — bluetooth winsock error 10049 on connect() — Stack .

    https://stackoverflow.com/questions/2859029/bluetooth-winsock-error-10049-on-connect
    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!):

Bluetooth winsock connection fail with error 10049?

    https://social.msdn.microsoft.com/forums/en-US/e6fa6277-9a5b-49af-baa8-0c6dd5dbbb52/bluetooth-winsock-connection-fail-with-error-10049
    Oct 06, 2017 · There’s a sample that covers this in the WM6 SDK: Windows Mobile 6 SDKSamplesPocketPCCPPwin32BluetoothBthChat Try setting the addressFamily member of …

Connection Failed (error Code 10049) Bluetooth .Connection .

    https://vdocuments.mx/connection-failed-error-code-10049-bluetooth-connection-failed-error-code.html
    Aug 29, 2018 · Connection Failed (error Code 10049) Bluetooth Bluetooth USB/VID_13D3&PID_3362&REV_0001 error code 43 :(. 1. 2 months Fixed screen rotation issue on Yoga 2 (wouldn’t…

Connection failure 10049??

    https://community.xim.tech/index.php?topic=31341.0
    Go to run in windows 7 or search in windows 8 and type «services.msc» scroll down till you see «Bluetooth Support Service» open that service and set it to automatic and then start the service. That’s how I fixed my connection issues.

How To Repair How To Fix Error 10049 (Solved)

    http://winload.org/how-to-fix-error-10049.html
    Socket Error Codes WSAECONNABORTED 10053 Software http://forum.teamspeak.com/threads/38303-how-to-fix-socket-error-10049 progress fail with WSAENETRESET. WSAENETUNREACH 10051 WSAENETUNREACH 10051 Socket Error 10049 Cause An attempt was made to access a What Is A Socket Error the number of applications that can …

How To Repair Connect Failed Error Code 10049 Tutorial

    http://iembra.org/error-code/connect-failed-error-code-10049.php
    I recognize that as the code I modified for another thread (from 2008), based on the SDK example. This is on Android. So i guess its the windows BT stack. What more .

Winsock error 10049 connect() call failed

    http://forums.codeguru.com/showthread.php?519055-Winsock-error-10049-connect()-call-failed
    Dec 12, 2011 · If so, then before you run in the client mode (which is the thing that calls connect() with failure code 10049), you must first be running a separate instance in the server mode. And when running in the client mode, you must pass in the IPv6 loopback address of 0:0:0:0:0:0:0:1

Unable to connect 10049 : MapleStory2

    https://www.reddit.com/r/MapleStory2/comments/9vcxbg/unable_to_connect_10049/
    Aug 20, 2012 · A fan community for MapleStory 2. We support KMS2, CMS2 and GMS2 (RIP).

a connection is not possible code = 10049 : MapleStory2

    https://www.reddit.com/r/MapleStory2/comments/8zxgu4/a_connection_is_not_possible_code_10049/
    A fan community for MapleStory 2. We support KMS2, CMS2 and GMS2 (RIP).

Connection Failure Error Code = 10049 L2 Vanir — L2 server

    https://www.l2vanir.com/forum/connection-failure-error-code-10049
    as in topic when i try to run louncher downloaded game last nyt , than l2vanir patch — n thats what comming when i want run the game plz help thx in advance

Error Code 10049 Bluetooth Fixes & Solutions

We are confident that the above descriptions of Error Code 10049 Bluetooth and how to fix it will be useful to you. If you have another solution to Error Code 10049 Bluetooth or some notes on the existing ways to solve it, then please drop us an email.

Источник

Error code 10049 bluetooth

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Asked by:

Question

— Windows Embedded Compact 2013 w. Bluetooth Support

i want to bind the created socket to use Bluetooth connection

s = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM); —> OK

bind(s, (SOCKADDR *)&sab, sizeof(sab)) —> Error 10049

ZeroMemory(&sab, sizeof(sab));
sab.addressFamily = AF_BTH;
sab.port = BT_PORT_ANY;
sab.serviceClassId = nguiD; // GUID_NULL
sab.btAddr = 0;

Has someone an idea ?

You would do well to download Platform Builder for WEC2013 and review the sample code, especially the control panel code.

With that said, I am not sure that it is available other than through an MSDN subscription. The trial doesn’t seem have a way to get an installation key anymore.

Источник

Ошибка 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 так что вы позволяете системе делать работу за вас.

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

Источник

Как исправить проблемы с сопряжением по Bluetooth

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

В целом, Bluetooth имеет обратную совместимость: устройства, поддерживающие стандарт Bluetooth 5.0, по-прежнему могут сопрягаться с устройствами, использующими, скажем, древний Bluetooth 2.1, вышедший еще в 2007 году.

Исключение составляют гаджеты, которые используют версию с низким энергопотреблением под названием Bluetooth Low Energy, которая работает по другому протоколу, нежели старые или «классические» устройства Bluetooth. Устройства с BLE не обладают обратной совместимостью и не распознают старые устройства, поддерживающие классический Bluetooth. Обычно BLE-девайсы — это метки, фитнес-браслеты и пр.

Если устройство поддерживает Bluetooth 4.0, 4.2 или 5.0, оно должно распознавать в том числе и Bluetooth LE

Что можно сделать, если соединение по Bluetooth не работает?

1. Убедиться, что Bluetooth активен, а устройства сопряжены и находятся на близком расстоянии друг от друга. Иногда для сопряжения требуется ввести код в смартфоне или ПК.

2. Включить режим видимости. Часто это касается фитнес-браслетов и информационно-развлекательной системы автомобиля — пользователи забывают активировать режим видимости.

3. Выключить и снова включить оба устройства либо соединение Bluetooth — как ни странно, но это до сих пор один из самых работающих методов.

4. Удалить старые подключения. Иногда гаджеты поддерживают только одно подключение — особенно часто это касается беспроводных колонок. Так что вы можете пытаться подключить динамик к планшету, в то время как он успешно сопрягается с устройством, с которым соединился в последний раз, например, со смартфоном. Выключите на время этот девайс или удалите у него подключение.

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

6. Удалить устройство со смартфона и найти заново. В настройках iOS вы можете удалить устройство, нажав на его имя, а затем «Забыть это устройство». На Android коснитесь имени устройства и затем «Разорвите пару». Если речь идет о системе автомобиля, может потребоваться выключить зажигание, открыть и закрыть дверь авто и подождать пару минут, прежде чем пытаться снова выполнить сопряжение.

7. Отойти от источников помех. Очень редко, но могут мешать сигналы от других устройств, например, Wi-Fi-роутера, порта USB 3.0. Помехой может стать даже усиленный чехол для смартфона.

8. Обновить драйверы и прошивку оборудования.

9. Очистить кэш Bluetooth. Иногда приложения могут мешать работе Bluetooth и очистка кэша может решить проблему. В Android-устройствах этот раздел находится в настройках системы: «Система» — «Дополнительно» — «Сбросить параметры» — «Сбросить настройки Wi-Fi, мобильного телефона и Bluetooth». На iOS понадобится разорвать пару со всеми устройствами (перейдите в «Настройки» — 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

Я пытаюсь установить соединение с настраиваемым устройством 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

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

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

В целом, Bluetooth имеет обратную совместимость: устройства, поддерживающие стандарт Bluetooth 5.0, по-прежнему могут сопрягаться с устройствами, использующими, скажем, древний Bluetooth 2.1, вышедший еще в 2007 году.

Исключение составляют гаджеты, которые используют версию с низким энергопотреблением под названием Bluetooth Low Energy, которая работает по другому протоколу, нежели старые или «классические» устройства Bluetooth. Устройства с BLE не обладают обратной совместимостью и не распознают старые устройства, поддерживающие классический Bluetooth. Обычно BLE-девайсы — это метки, фитнес-браслеты и пр.

Если устройство поддерживает Bluetooth 4.0, 4.2 или 5.0, оно должно распознавать в том числе и Bluetooth LE

Что можно сделать, если соединение по Bluetooth не работает?

1. Убедиться, что Bluetooth активен, а устройства сопряжены и находятся на близком расстоянии друг от друга. Иногда для сопряжения требуется ввести код в смартфоне или ПК.

2. Включить режим видимости. Часто это касается фитнес-браслетов и информационно-развлекательной системы автомобиля — пользователи забывают активировать режим видимости.

3. Выключить и снова включить оба устройства либо соединение Bluetooth — как ни странно, но это до сих пор один из самых работающих методов.

4. Удалить старые подключения. Иногда гаджеты поддерживают только одно подключение — особенно часто это касается беспроводных колонок. Так что вы можете пытаться подключить динамик к планшету, в то время как он успешно сопрягается с устройством, с которым соединился в последний раз, например, со смартфоном. Выключите на время этот девайс или удалите у него подключение.

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

6. Удалить устройство со смартфона и найти заново. В настройках iOS вы можете удалить устройство, нажав на его имя, а затем «Забыть это устройство». На Android коснитесь имени устройства и затем «Разорвите пару». Если речь идет о системе автомобиля, может потребоваться выключить зажигание, открыть и закрыть дверь авто и подождать пару минут, прежде чем пытаться снова выполнить сопряжение.

7. Отойти от источников помех. Очень редко, но могут мешать сигналы от других устройств, например, Wi-Fi-роутера, порта USB 3.0. Помехой может стать даже усиленный чехол для смартфона.

8. Обновить драйверы и прошивку оборудования.

9. Очистить кэш Bluetooth. Иногда приложения могут мешать работе Bluetooth и очистка кэша может решить проблему. В Android-устройствах этот раздел находится в настройках системы: «Система» — «Дополнительно» — «Сбросить параметры» — «Сбросить настройки Wi-Fi, мобильного телефона и Bluetooth». На iOS понадобится разорвать пару со всеми устройствами (перейдите в «Настройки» — Bluetooth, выберите значок информации и «Забыть это устройство» для каждого девайса), затем перезагрузить гаджет.

Источник: //zoom.cnews.ru/b/post/tehnoblog/75973

Данный материал является частной записью члена сообщества Club.CNews.
Редакция CNews не несет ответственности за его содержание.

Понравилась статья? Поделить с друзьями:

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

  • Код ошибки 1004 сбербанк
  • Код ошибки 1 tlauncher
  • Код ошибки 1004 окко что это
  • Код ошибки 1004 окко на телевизоре
  • Код ошибки 1004 вконтакте при регистрации

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии