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 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 (bind(sock, (struct sockaddr *)&l2sa, size) < 0) { 44 perror ("bind"); 45 exit (EXIT_FAILURE); 46 } 47 48 printf("Connecting socket for %s\n", bdaddrUtils::ToString(*bdaddr)); 49 if ((error = connect(sock, (struct sockaddr *)&l2sa, sizeof(l2sa))) < 0) { 50 perror ("connect"); 51 exit (EXIT_FAILURE); 52 } 53 54 printf("Return status of the connection is %ld \n", error ); 55 56 return sock; 57 } 58 59 int main(int argc, char **argv) 60 { 61 struct sockaddr_l2cap l2sa; 62 char string[512]; 63 size_t len; 64 uint16 psm = 1; 65 66 if (argc < 2 ) { 67 printf("I need a bdaddr!\nUsage:\n\t%s bluetooth_address [psm]\n", 68 argv[0]); 69 return 0; 70 } 71 72 if (argc > 2) { 73 psm = atoi(argv[2]); 74 printf("PSM requested %d\n", psm); 75 } 76 77 if ((psm & 1) == 0) 78 printf("WARNING: PSM requested is not pair\n"); 79 80 const bdaddr_t bdaddr = bdaddrUtils::FromString(argv[1]); 81 82 int sock = CreateL2capSocket(&bdaddr, l2sa, psm); 83 84 while (strcmp(string,"bye") != 0) { 85 86 fscanf(stdin, "%s", string); 87 len = sendto(sock, string, strlen(string) + 1 /*\0*/, 0, 88 (struct sockaddr*) &l2sa, sizeof(struct sockaddr_l2cap)); 89 90 91 printf("Sent %ld bytes\n", len); 92 93 // len = send(sock, string + 1 /*\0*/, strlen(string), 0); 94 // recvfrom(sock, buff, 4096-1, 0, (struct sockaddr *) &l2, &len); 95 } 96 97 printf("Transmission done ... (press key to close socket)\n"); 98 getchar(); 99 getchar(); 100 printf("Closing ... \n"); 101 close(sock); 102 } 103