[Popular technology] Winsock searches for Bluetooth devices

Source: Internet
Author: User

Http://blog.csdn.net/JamesXing/article/details/1700338 there are various Bluetooth-related articles

How can we search for Bluetooth devices on a computer? We use Winsock to search for Bluetooth devices. For more information, see code analysis.

# Include "stdafx. H"

# Include <winsock2.h>
# Include <ws2bth. h>

# Pragma comment (Lib, "ws2_32.lib ")

Int _ tmain (INT argc, _ tchar * argv [])
{
// Initialize Winsock
Wsadata;
If (wsastartup (makeword (2, 2), & wsadata )! = 0)
{
_ Tprintf (_ T ("wsastartup failed with error code: % d \ n"), wsagetlasterror ());
Return 1;
}

// Initialize the Bluetooth enumeration Structure
DWORD dwwsaqslen = sizeof (wsaqueryset );
Lpwsaqueryset lpwsaqs = (lpwsaqueryset) heapalloc (getprocessheap (), heap_zero_memory, dwwsaqslen );
Lpwsaqs-> dwsize = sizeof (wsaqueryset );
Lpwsaqs-> dwnamespace = ns_bth;

// Start to enumerate Bluetooth devices
DWORD dwwsaqsflags = lup_containers | lup_flushcache | lup_return_name | lup_return_addr;
Handle hservice;

If (wsalookupservicebegin (lpwsaqs, dwwsaqsflags, & hservice )! = Socket_error)
{
Bool bfinished = false;
While (! Bfinished)
{
If (wsalookupservicenext (hservice, dwwsaqsflags, & dwwsaqslen, lpwsaqs) = no_error)
{
Sockaddr_bth * sabth = (sockaddr_bth *) lpwsaqs-> lpcsabuffer-> remoteaddr. lpsockaddr;
Bth_addr bthaddr = sabth-> btaddr;

_ Tprintf (_ T ("\ n bluetooth device found: \ n "));
_ Tprintf (_ T ("------------------------ \ n "));
_ Tprintf (_ T ("NAP: 0x % 04x SAP: 0x % 08x device name: % s \ n"), get_nap (bthaddr), get_sap (bthaddr ), lpwsaqs-> lpszserviceinstancename );
}
Else
{
// Handle errors
Switch (wsagetlasterror ())
{
// If the given buffer is too small, apply again
Case wsaefault:
Heapfree (getprocessheap (), 0, lpwsaqs );
Lpwsaqs = (lpwsaqueryset) heapalloc (getprocessheap (), heap_zero_memory, dwwsaqslen );
Break;

// No more Bluetooth devices
Case wsa_e_no_more:
Bfinished = true;
Break;

Default:
// Bfinished = true;
Break;
}
}
}
Wsalookupserviceend (hservice );
}

// Release resources
Heapfree (getprocessheap (), 0, lpwsaqs );
Wsacleanup ();

Return 0;
}

Connect to a remote Bluetooth device using WinSock

You can connect two bluetooth devices by creating a socket between the server and the client. The server socket must be set to listen for incoming connections and accept client sockets. The client socket must know the address of the device to be connected before sending a connection request. You can also use serial port simulation on Microsoft Windows CE to easily create a connection. For more information, see "connect to a remote device through virtual serial ports" Note:For clarity, we ignore error handling. Before creating a connection, you must first obtain the following information: ø the address of the remote device to be queried. The bt_addr type is defined in ws2bth. in H: typedef ulonglong bt_addr, * pbt_addr, bt_addr, * pbt_addr; Note:This is only required by the client. The service identifier of a guid type variable, or RFCOMM channel (1 to 31 ). Create client socket1. Provide the Winsock version and detailed implementation data to initialize the caller application. You can call the wsastartup function to obtain the data. Wsadata WSD; wsastartup (makeword (1, 0), & WSD); 2. Call the socket function to create a Bluetooth socket. Socket client_socket = socket (af_bt, sock_stream, bthproto_rfcomm); the socket function parameter value sets the socket as a Bluetooth service. 3. Set the sockaddr_bth struct to store the information of the remote device that the client wants to connect. A. Create and initialize the sockaddr_bth variable. Sockaddr_bth SA; memset (& SA, 0, sizeof (SA); B. Assign the btaddr member to the bt_addr variable containing the target device address. SA. btaddr = B; // B is Bt_addrVariable your program can accept string-type device addresses, but must be converted and stored as a bt_addr type variable. C. If the service identifier is valid, set the serviceclassid member to the guid of the rfcomm-based service. In this case, the client executes the SDP query and then uses the obtained server channel. Or, if you want to use a hard-coded channel number, set the port member variable to the server channel number. SA. Port = channel & 0xff; 4. Call the connect function to connect to the Bluetooth socket. If (connect (client_socket, (sockaddr *) & SA, sizeof (SA) {// perform error handling. closesocket (client_socket); Return 0;} transmits the sockaddr_bth set in step 1 to specify the properties of the target device. After the connection is established, you can send and receive data to communicate with the target device. 5. To disable the connection to the target device, call the closesocket function to disable the Bluetooth socket, and ensure that the closehandle function is used to release the socket. Closesocket (client_socket); closehandle (lpvoid) client_socket); 6. to end the use of the Winsock service, call the wsacleanup function. In the program, wsacleanup must be called for each successfully called wsastartup. To create a server socket1. Provide the Winsock version and detailed implementation data to initialize the caller application. You can call the wsastartup function to obtain the data. Wsadata WSD; wsastartup (makeword (1, 0), & WSD); 2. Call the socket function to create a Bluetooth socket. Socket server_socket = socket (af_bt, sock_stream, bthproto_rfcomm); the socket function parameter value sets the socket as a Bluetooth service. 3. Set the sockaddr_bth struct to store the information of the server device. Sockaddr_bth SA; memset (& SA, 0, sizeof (SA); SA. addressfamily = af_bt; SA. Port = channel & 0xff; Note:To avoid conflicts, we recommend that you set the channel to 0 when selecting a server channel so that RFCOMM will automatically use the next valid channel. The information in the struct is used to bind the socket to the local address of the server device. 4. Call the BIND function to bind the server_socket created in step 2, and input the reference of the SA created in step 3 to the specified device information. If (BIND (server_socket, (sockaddr *) & SA, sizeof (SA ))){... // perform error handling closesocket (server_socket); Return 0 ;}5. use the listen function to listen to connection requests sent by the client's bluetooth device. If (Listen (server_socket, 5) {... // perform error handling closesocket (server_socket); Return 0 ;}6. Use the accept function to accept incoming connection requests. Sockaddr_bth SA2; int size = sizeof (SA2); socket S2 = accept (server_socket, (sockaddr *) & SA2, & size); if you call accept, the client address of scokaddr_bth type is returned. 7. Call the closecocket function to close the socket. Closesocket (server_socket );

To end the use of the Winsock service, call the wsacleanup function. In the program, wsacleanup must be called for each successfully called wsastartup.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.