1 /*
2 * Copyright 2010 Oliver Ruiz Dorantes, oliver.ruiz.dorantes_at_gmail.com
3 * All rights reserved. Distributed under the terms of the MIT License.
4 *
5 */
6 #include <stddef.h>
7 #include <stdio.h>
8 #include <unistd.h>
9 #include <errno.h>
10 #include <stdlib.h>
11 #include <sys/socket.h>
12
13 #include <bluetooth/bluetooth.h>
14 #include <bluetooth/bdaddrUtils.h>
15 #include <bluetooth/L2CAP/btL2CAP.h>
16
17 int
CreateL2capSocket(const bdaddr_t * bdaddr,struct sockaddr_l2cap & l2sa,uint16 psm)18 CreateL2capSocket(const bdaddr_t* bdaddr, struct sockaddr_l2cap& l2sa, uint16 psm)
19 {
20 int sock;
21 size_t size;
22 status_t error;
23
24 /* Create the socket. */
25 printf("Creating socket ...\n");
26
27 sock = socket(PF_BLUETOOTH, SOCK_STREAM, BLUETOOTH_PROTO_L2CAP);
28 if (sock < 0) {
29 perror ("socket");
30 exit (EXIT_FAILURE);
31 }
32
33 /* Bind a name to the socket. */
34 //printf("Binding socket ...\n");
35
36 size = sizeof(struct sockaddr_l2cap);
37
38 l2sa.l2cap_family = PF_BLUETOOTH;
39 l2sa.l2cap_len = size;
40 memcpy(&l2sa.l2cap_bdaddr, bdaddr, sizeof(bdaddr_t));
41 l2sa.l2cap_psm = psm;
42
43 #if 0
44 if (bind(sock, (struct sockaddr *)&l2sa, size) < 0) {
45 perror ("bind");
46 exit (EXIT_FAILURE);
47 }
48 #endif
49
50 printf("Connecting socket for %s\n", bdaddrUtils::ToString(*bdaddr));
51 if ((error = connect(sock, (struct sockaddr *)&l2sa, sizeof(l2sa))) < 0) {
52 perror ("connect");
53 exit (EXIT_FAILURE);
54 }
55
56 printf("Return status of the connection is %ld \n", error );
57
58 return sock;
59 }
60
main(int argc,char ** argv)61 int main(int argc, char **argv)
62 {
63 struct sockaddr_l2cap l2sa;
64 char string[512];
65 size_t len;
66 uint16 psm = 1;
67
68 if (argc < 2 ) {
69 printf("I need a bdaddr!\nUsage:\n\t%s bluetooth_address [psm]\n",
70 argv[0]);
71 return 0;
72 }
73
74 if (argc > 2) {
75 psm = atoi(argv[2]);
76 printf("PSM requested %d\n", psm);
77 }
78
79 if ((psm & 1) == 0)
80 printf("WARNING: PSM requested is not pair\n");
81
82 const bdaddr_t bdaddr = bdaddrUtils::FromString(argv[1]);
83
84 int sock = CreateL2capSocket(&bdaddr, l2sa, psm);
85
86 while (strcmp(string,"bye") != 0) {
87
88 fscanf(stdin, "%s", string);
89 len = sendto(sock, string, strlen(string) + 1 /*\0*/, 0,
90 (struct sockaddr*) &l2sa, sizeof(struct sockaddr_l2cap));
91
92
93 printf("Sent %ld bytes\n", len);
94
95 // len = send(sock, string + 1 /*\0*/, strlen(string), 0);
96 // recvfrom(sock, buff, 4096-1, 0, (struct sockaddr *) &l2, &len);
97 }
98
99 printf("Transmission done ... (press key to close socket)\n");
100 getchar();
101 getchar();
102 printf("Closing ... \n");
103 close(sock);
104 }
105