xs_socket.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /* copyright (c) 2022 grunfink - MIT license */
  2. #ifndef _XS_SOCKET_H
  3. #define _XS_SOCKET_H
  4. int xs_socket_timeout(int s, float rto, float sto);
  5. int xs_socket_server(char *addr, int port);
  6. FILE *xs_socket_accept(int rs);
  7. #ifdef XS_IMPLEMENTATION
  8. #include <sys/socket.h>
  9. #include <netdb.h>
  10. #include <netinet/in.h>
  11. int xs_socket_timeout(int s, float rto, float sto)
  12. /* sets the socket timeout in seconds */
  13. {
  14. struct timeval tv;
  15. int ret = 0;
  16. if (rto > 0.0) {
  17. tv.tv_sec = (int)rto;
  18. tv.tv_usec = (int)((rto - (float)(int)rto) * 1000000.0);
  19. ret = setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv));
  20. }
  21. if (sto > 0.0) {
  22. tv.tv_sec = (int)sto;
  23. tv.tv_usec = (int)((sto - (float)(int)sto) * 1000000.0);
  24. ret = setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv));
  25. }
  26. return ret;
  27. }
  28. int xs_socket_server(char *addr, int port)
  29. /* opens a server socket */
  30. {
  31. int rs = -1;
  32. struct sockaddr_in host;
  33. memset(&host, '\0', sizeof(host));
  34. if (addr != NULL) {
  35. struct hostent *he;
  36. if ((he = gethostbyname(addr)) != NULL)
  37. memcpy(&host.sin_addr, he->h_addr_list[0], he->h_length);
  38. else
  39. goto end;
  40. }
  41. host.sin_family = AF_INET;
  42. host.sin_port = htons(port);
  43. if ((rs = socket(AF_INET, SOCK_STREAM, 0)) != -1) {
  44. /* reuse addr */
  45. int i = 1;
  46. setsockopt(rs, SOL_SOCKET, SO_REUSEADDR, (char *)&i, sizeof(i));
  47. if (bind(rs, (struct sockaddr *)&host, sizeof(host)) == -1) {
  48. close(rs);
  49. rs = -1;
  50. }
  51. else
  52. listen(rs, SOMAXCONN);
  53. }
  54. end:
  55. return rs;
  56. }
  57. FILE *xs_socket_accept(int rs)
  58. /* accepts an incoming connection */
  59. {
  60. int cs = -1;
  61. struct sockaddr_in host;
  62. socklen_t l = sizeof(host);
  63. cs = accept(rs, (struct sockaddr *)&host, &l);
  64. return cs == -1 ? NULL : fdopen(cs, "r+");
  65. }
  66. #endif /* XS_IMPLEMENTATION */
  67. #endif /* _XS_SOCKET_H */