socket_inaddr_any_server.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /* libs/cutils/socket_inaddr_any_server.c
  2. **
  3. ** Copyright 2006, The Android Open Source Project
  4. **
  5. ** Licensed under the Apache License, Version 2.0 (the "License");
  6. ** you may not use this file except in compliance with the License.
  7. ** You may obtain a copy of the License at
  8. **
  9. ** http://www.apache.org/licenses/LICENSE-2.0
  10. **
  11. ** Unless required by applicable law or agreed to in writing, software
  12. ** distributed under the License is distributed on an "AS IS" BASIS,
  13. ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. ** See the License for the specific language governing permissions and
  15. ** limitations under the License.
  16. */
  17. #include <cutils/sockets.h>
  18. #include <stdlib.h>
  19. #include <string.h>
  20. #include <unistd.h>
  21. #include <errno.h>
  22. #include <stddef.h>
  23. #ifndef HAVE_WINSOCK
  24. #include <sys/socket.h>
  25. #include <sys/select.h>
  26. #include <sys/types.h>
  27. #include <netinet/in.h>
  28. #endif
  29. #define LISTEN_BACKLOG 4
  30. /* open listen() port on any interface */
  31. int socket_inaddr_any_server(int port, int type)
  32. {
  33. struct sockaddr_in addr;
  34. size_t alen;
  35. int s, n;
  36. memset(&addr, 0, sizeof(addr));
  37. addr.sin_family = AF_INET;
  38. addr.sin_port = htons(port);
  39. addr.sin_addr.s_addr = htonl(INADDR_ANY);
  40. s = socket(AF_INET, type, 0);
  41. if(s < 0) return -1;
  42. n = 1;
  43. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n));
  44. if(bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
  45. close(s);
  46. return -1;
  47. }
  48. if (type == SOCK_STREAM) {
  49. int ret;
  50. ret = listen(s, LISTEN_BACKLOG);
  51. if (ret < 0) {
  52. close(s);
  53. return -1;
  54. }
  55. }
  56. return s;
  57. }