bluetooth/bluetooth.c
changeset 165 f551b78c3eee
equal deleted inserted replaced
164:e1f4bba1097a 165:f551b78c3eee
       
     1 /**
       
     2  * bluetooth.c
       
     3  * Copyright (C) 2010 Markus Bröker
       
     4  */
       
     5 
       
     6 #include <stdio.h>
       
     7 #include <stdlib.h>
       
     8 #include <unistd.h>
       
     9 #include <sys/socket.h>
       
    10 #include <bluetooth/bluetooth.h>
       
    11 #include <bluetooth/rfcomm.h>
       
    12 
       
    13 int main (int argc, char **argv)
       
    14 {
       
    15     struct sockaddr_rc loc_addr = { 0 }, rem_addr = {
       
    16     0};
       
    17     char buf[1024] = { 0 };
       
    18     int s, client, bytes_read;
       
    19     socklen_t opt = sizeof (rem_addr);
       
    20 
       
    21     // allocate socket
       
    22     s = socket (AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
       
    23 
       
    24     // bind socket to port 1 of the first available
       
    25     // local bluetooth adapter
       
    26     loc_addr.rc_family = AF_BLUETOOTH;
       
    27     loc_addr.rc_bdaddr = *BDADDR_ANY;
       
    28     loc_addr.rc_channel = (uint8_t) 1;
       
    29     bind (s, (struct sockaddr *)&loc_addr, sizeof (loc_addr));
       
    30 
       
    31     // put socket into listening mode
       
    32     listen (s, 1);
       
    33 
       
    34     // accept one connection
       
    35     client = accept (s, (struct sockaddr *)&rem_addr, &opt);
       
    36 
       
    37     ba2str (&rem_addr.rc_bdaddr, buf);
       
    38     fprintf (stderr, "accepted connection from %s\n", buf);
       
    39     memset (buf, 0, sizeof (buf));
       
    40 
       
    41     // read data from the client
       
    42     bytes_read = read (client, buf, sizeof (buf));
       
    43     if (bytes_read > 0) {
       
    44         printf ("received [%s]\n", buf);
       
    45     }
       
    46     // close connection
       
    47     close (client);
       
    48     close (s);
       
    49 
       
    50     return EXIT_SUCCESS;
       
    51 }