Keyboard firmwares for Atmel AVR and Cortex-M
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TCPSocketServer.cpp 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /* Copyright (C) 2012 mbed.org, MIT License
  2. *
  3. * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
  4. * and associated documentation files (the "Software"), to deal in the Software without restriction,
  5. * including without limitation the rights to use, copy, modify, merge, publish, distribute,
  6. * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
  7. * furnished to do so, subject to the following conditions:
  8. *
  9. * The above copyright notice and this permission notice shall be included in all copies or
  10. * substantial portions of the Software.
  11. *
  12. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
  13. * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  14. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  15. * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  17. */
  18. #include "TCPSocketServer.h"
  19. #include <cstring>
  20. using std::memset;
  21. using std::memcpy;
  22. TCPSocketServer::TCPSocketServer() {
  23. }
  24. int TCPSocketServer::bind(int port) {
  25. if (init_socket(SOCK_STREAM) < 0)
  26. return -1;
  27. struct sockaddr_in localHost;
  28. memset(&localHost, 0, sizeof(localHost));
  29. localHost.sin_family = AF_INET;
  30. localHost.sin_port = htons(port);
  31. localHost.sin_addr.s_addr = INADDR_ANY;
  32. if (lwip_bind(_sock_fd, (const struct sockaddr *) &localHost, sizeof(localHost)) < 0) {
  33. close();
  34. return -1;
  35. }
  36. return 0;
  37. }
  38. int TCPSocketServer::listen(int max) {
  39. if (_sock_fd < 0)
  40. return -1;
  41. if (lwip_listen(_sock_fd, max) < 0) {
  42. close();
  43. return -1;
  44. }
  45. return 0;
  46. }
  47. int TCPSocketServer::accept(TCPSocketConnection& connection) {
  48. if (_sock_fd < 0)
  49. return -1;
  50. if (!_blocking) {
  51. TimeInterval timeout(_timeout);
  52. if (wait_readable(timeout) != 0)
  53. return -1;
  54. }
  55. connection.reset_address();
  56. socklen_t newSockRemoteHostLen = sizeof(connection._remoteHost);
  57. int fd = lwip_accept(_sock_fd, (struct sockaddr*) &connection._remoteHost, &newSockRemoteHostLen);
  58. if (fd < 0)
  59. return -1; //Accept failed
  60. connection._sock_fd = fd;
  61. connection._is_connected = true;
  62. return 0;
  63. }