7

I am trying write program in C to send/receive data over bluetooth. I got a reference to a book by Albert Huang which has sample programs and also good source of information. Link: https://people.csail.mit.edu/albert/bluez-intro/index.html The example 4.2 in (https://people.csail.mit.edu/albert/bluez-intro/x502.html) shows the RFCOMM connection using socket programming. Also is there a way to connect using Bluetooth name of the device instead of BD address ? Here I dont see how to set up PIN or authentication for the communication over bluetooth connection. Is there a way to implement it. Also is the socket connection secured enough as there is no authentication process?

I am using debian machine and Bluez package for my development. Topology I am trying to achieve is - 1 Master/server connected to N(max 7 as per bluetooth protocol spec) clients which may be any embeded simple chip computer and should be able to communicate untill the connection is terminated by either one(source or client).

Has anyone done something similar or may be any reference/s.

I found few refernces on SO but everything pointed me back to the same as described in the book.I couldn't find anything similar to what I was looking for.

Any help is appreciated.

Thanks for you time and help.

sachin
  • 665
  • 3
  • 8
  • 15
  • https://stackoverflow.com/questions/6494006/how-to-send-and-receive-data-in-android-programming-using-bluetooth-without-pair – EsmaeelE Jul 14 '17 at 10:51
  • https://electronics.stackexchange.com/questions/47273/is-bluetooth-communication-possible-without-pairing – EsmaeelE Jul 14 '17 at 10:56
  • http://pages.iu.edu/~rwisman/c490/html/pythonandbluetooth.htm https://stackoverflow.com/questions/14820004/bluetooth-pairing-in-c-bluez-on-linux – EsmaeelE Jul 14 '17 at 11:04

2 Answers2

4

There are a few more resources which you could check:

Bluetooth Protocol Stack for Linux developed by Nokia Research Center.

Using Bluetooth - DrDobbs.

Bluetooth programming for Linux.

sg7
  • 6,108
  • 2
  • 32
  • 40
4

First you must do a search for all BT devices.

Second check is the Name of any funded devices match to your specific name or not.

If true perform send to server codes.

Client

#include <stdio.h>
// POSIX sys lib: fork, pipe, I/O (read, write)
#include <unistd.h>
// superset of unistd, same
#include <stdlib.h>

//Bluetooth
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>
#include <bluetooth/sdp.h>
#include <bluetooth/sdp_lib.h>
#include <bluetooth/sco.h>

//socket
#include <sys/socket.h>


int main(int argc, char **argv)
{
        int flag=0;

    struct sockaddr_rc addrress = { 0 };
    int s, status;

    char dest[18]="";// = "B0:10:41:3F:6E:80";//My destination address Laptop
    char namelaptop[20]="ss";


    // allocate a socket
    s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
    ///create a socket

    // set the connection parameters (who to connect to)
    addrress.rc_family = AF_BLUETOOTH;
    addrress.rc_channel = (uint8_t) 1;//must use sdp to work in real devices
    //may this channel not ready


    printf("Search for BT Devices...\n");

///search   

    inquiry_info *ii = NULL;
    int max_rsp, num_rsp;
    int dev_id, sock, len, flags;
    int i;

    char addr[18] = { 0 };
    char name[248] = { 0 };

    dev_id = hci_get_route(NULL);
    sock = hci_open_dev( dev_id );
    if (dev_id < 0 || sock < 0) {
        perror("opening socket");
        exit(1);
    }

    len = 8;
    max_rsp = 2;
    flags = IREQ_CACHE_FLUSH;
    ii = (inquiry_info*)malloc(max_rsp * sizeof(inquiry_info));

    num_rsp = hci_inquiry(dev_id, len, max_rsp, NULL, &ii, flags);
    if( num_rsp < 0 ) {
        perror("hci_inquiry");
    }

    for (i = 0; i < num_rsp; i++) {
        ba2str(&(ii+i)->bdaddr, addr);
        memset(name, 0, sizeof(name));
        if (hci_read_remote_name(sock, &(ii+i)->bdaddr, sizeof(name),
            name, 0) < 0)
        strcpy(name, "[unknown]");

        else{
        printf("\nFind #%d\n",i);

        printf("Addr:%s    Name:%s\n", addr, name);

        int a=strcmp(name, namelaptop);
        //printf("compare:%d\n",a);

        if (!a){   // if name mached 
            str2ba( addr, &addrress.rc_bdaddr );//copy dest-->addr.rc_bdaddr    
            flag =1;
        }
        }

    }


/// End Search 



///Connect and send

    if (flag==0){
        printf("Not find dest: %s\n",name);
        exit(0);
    }

    // connect to server, throw socket s
    status = connect(s, (struct sockaddr *)&addrress, sizeof(addrress));
    //successful, connect() returns 0.

    printf("connection status: %d\n\n",status);//0 show OK

    // send a message to server
    if( status == 0 ) {
        status = write(s, "hello!", 6);
        if (status == 6){
            printf("Send data to server done\n");
        }
    }
    else 
        if( status < 0 ){ 
            perror("send message to server Failed\n");
    }

    printf("Closing socket\n");

    ///close the socket
    close(s);

///End connect and send


    free( ii );
    close( sock );

    return 0;
}

Server

just only use

rfcomm-server.c

in Albert Huang Good BT tutorial

#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>

int 
main(int argc, char **argv)
{
    struct sockaddr_rc loc_addr = { 0 }, rem_addr = { 0 };
    char buf[1024] = { 0 };
    int s, client, bytes_read;
    socklen_t opt = sizeof(rem_addr);

    // allocate socket
    s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);

    // bind socket to port 1 of the first available 
    // local bluetooth adapter
    loc_addr.rc_family = AF_BLUETOOTH;
    loc_addr.rc_bdaddr = *BDADDR_ANY;
    loc_addr.rc_channel = (uint8_t) 1;
    bind(s, (struct sockaddr *)&loc_addr, sizeof(loc_addr));

    //get local address ?
    //~ ba2str( &loc_addr.rc_bdaddr, buf );
    //~ fprintf(stdout, "local %s\n", buf);

    // put socket into listening mode
    listen(s, 1);

    // accept one connection
    client = accept(s, (struct sockaddr *)&rem_addr, &opt);


    ba2str( &rem_addr.rc_bdaddr, buf );
    fprintf(stderr, "accepted connection from %s\n", buf);


    memset(buf, 0, sizeof(buf));

    // read data from the client
    bytes_read = read(client, buf, sizeof(buf));

    if( bytes_read > 0 ) {
        printf("received [%s]\n", buf);
    }

    // close connection
    close(client);
    close(s);
    return 0;
}

These two code work for me.

I run rfcomm-client.c in my PC, and rfcomm-server.c on A laptop. my laptop BT name is "ss" that i hard coded it on rfcomm-client.c

client send a hello massage and server show it if receives.

EsmaeelE
  • 2,331
  • 6
  • 22
  • 31
  • 1
    Thanks for you response. you answered a part of my confusion but the other part i am concerned is authentication for the connection. You too are using socket programming here right ? Is socket programming the only way to implement bluetooth connection? I dont know if its secure as there are no authentication and thats my main concern. – sachin Jul 12 '17 at 13:31
  • Yes i just use socket programming for bluetooth communication [Bluetooth socket programming]. Before run these code i paired two system with Ubuntu setting > bluetooth menu. Authentication performed manually not by codes. – EsmaeelE Jul 14 '17 at 09:47
  • Yes we have other option for bluetooth programming. use especial packages instead of socket programming. see http://blog.kevindoran.co/bluetooth-programming-with-python-3/ but i think this package also use sockets. – EsmaeelE Jul 14 '17 at 10:45
  • 1
    I need the same work for Windows 10, Can anyone provide me ? – Akhzar Nazir Sep 15 '18 at 16:26
  • @AkhzarNazir ِYou can google some combination like this: "Bluetooth programming in C windows". – EsmaeelE Sep 24 '18 at 07:05
  • @AkhzarNazir : [Windows BT device finding](https://www.winsocketdotnetworkprogramming.com/winsock2programming/winsock2advancedotherprotocol4j.html) – EsmaeelE Sep 24 '18 at 07:06
  • @AkhzarNazir [Windows documentation ob BT](https://learn.microsoft.com/en-us/windows/desktop/bluetooth/bluetooth-programming-with-windows-sockets) – EsmaeelE Sep 24 '18 at 07:12
  • @AkhzarNazir [example](https://www.winsocketdotnetworkprogramming.com/winsock2programming/winsock2advancedotherprotocol4g.html) [example2](https://www.winsocketdotnetworkprogramming.com/winsock2programming/winsock2advancedotherprotocol4k.html) – EsmaeelE Sep 24 '18 at 07:14
  • @AkhzarNazir [C++ code](https://code.msdn.microsoft.com/windowsdesktop/Bluetooth-Connection-e3263296) – EsmaeelE Sep 24 '18 at 07:23
  • @EsmaeelE Awesome answer! Can you please tell me if it is possible to connect to run both the rfcomm server and client code in the same computer itself. I cannot connect from client if the server is on the same machine. – Vivekanand V Jul 10 '23 at 18:38
  • 1
    @VivekanandV, I think you can use two different BT module for that. i.e use laptop internal BT module and connect another one with usb dongle. – EsmaeelE Jul 11 '23 at 06:18
  • @EsmaeelE Thankyou very much for the reply. I send my implementation to my friend who has two laptops running Linux and he told me that the server is blocked at accept() , but ironically the connect() system call works and sends some bytes to the socket, but unfortunately it's really frustrating because the server has not accepted our connection yet! – Vivekanand V Jul 11 '23 at 17:20