test_track_devices.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /* a simple test program, connects to ADB server, and opens a track-devices session */
  2. #include <netdb.h>
  3. #include <sys/socket.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <errno.h>
  7. #include <memory.h>
  8. static void
  9. panic( const char* msg )
  10. {
  11. fprintf(stderr, "PANIC: %s: %s\n", msg, strerror(errno));
  12. exit(1);
  13. }
  14. static int
  15. unix_write( int fd, const char* buf, int len )
  16. {
  17. int result = 0;
  18. while (len > 0) {
  19. int len2 = write(fd, buf, len);
  20. if (len2 < 0) {
  21. if (errno == EINTR || errno == EAGAIN)
  22. continue;
  23. return -1;
  24. }
  25. result += len2;
  26. len -= len2;
  27. buf += len2;
  28. }
  29. return result;
  30. }
  31. static int
  32. unix_read( int fd, char* buf, int len )
  33. {
  34. int result = 0;
  35. while (len > 0) {
  36. int len2 = read(fd, buf, len);
  37. if (len2 < 0) {
  38. if (errno == EINTR || errno == EAGAIN)
  39. continue;
  40. return -1;
  41. }
  42. result += len2;
  43. len -= len2;
  44. buf += len2;
  45. }
  46. return result;
  47. }
  48. int main( void )
  49. {
  50. int ret, s;
  51. struct sockaddr_in server;
  52. char buffer[1024];
  53. const char* request = "host:track-devices";
  54. int len;
  55. memset( &server, 0, sizeof(server) );
  56. server.sin_family = AF_INET;
  57. server.sin_port = htons(5037);
  58. server.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  59. s = socket( PF_INET, SOCK_STREAM, 0 );
  60. ret = connect( s, (struct sockaddr*) &server, sizeof(server) );
  61. if (ret < 0) panic( "could not connect to server" );
  62. /* send the request */
  63. len = snprintf( buffer, sizeof buffer, "%04x%s", strlen(request), request );
  64. if (unix_write(s, buffer, len) < 0)
  65. panic( "could not send request" );
  66. /* read the OKAY answer */
  67. if (unix_read(s, buffer, 4) != 4)
  68. panic( "could not read request" );
  69. printf( "server answer: %.*s\n", 4, buffer );
  70. /* now loop */
  71. for (;;) {
  72. char head[5] = "0000";
  73. if (unix_read(s, head, 4) < 0)
  74. panic("could not read length");
  75. if ( sscanf( head, "%04x", &len ) != 1 )
  76. panic("could not decode length");
  77. if (unix_read(s, buffer, len) != len)
  78. panic("could not read data");
  79. printf( "received header %.*s (%d bytes):\n%.*s", 4, head, len, len, buffer );
  80. }
  81. close(s);
  82. }