server_udp.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * File: server_udp.c
  3. * Author: Arthur Brandao
  4. *
  5. * Created on 14 novembre 2018
  6. */
  7. #include "error.h"
  8. #include "server.h"
  9. /* --- Fonctions privées --- */
  10. void server_bind(Server this, int port) {
  11. /* Declaration variable */
  12. int tmp;
  13. /* Bind */
  14. this->serv.sin_family = AF_INET;
  15. this->serv.sin_port = htons(port);
  16. this->serv.sin_addr.s_addr = htonl(INADDR_ANY);
  17. tmp = bind(this->socket, (struct sockaddr*) &this->serv, sizeof (struct sockaddr_in));
  18. if (tmp == ERR) {
  19. free(this);
  20. neterror(BIND_ERROR)
  21. }
  22. }
  23. ssize_t server_receive_udp(Server this, char* buf, size_t size) {
  24. /* Declaration variable */
  25. int tmp;
  26. /* Reception */
  27. tmp = recvfrom(this->socket, buf, size, 0, (struct sockaddr*) &this->client, &this->addr);
  28. if (tmp == ERR) {
  29. free(this);
  30. syserror("Erreur lors de la reception ", 3)
  31. }
  32. /* Retour */
  33. return tmp;
  34. }
  35. void server_send_udp(Server this, char* msg) {
  36. /* Declaration variable */
  37. int tmp;
  38. /* Envoi */
  39. tmp = sendto(this->socket, msg, strlen(msg) * sizeof (char), 0, (struct sockaddr*) &this->client, sizeof (struct sockaddr_in));
  40. if (tmp == ERR) {
  41. free(this);
  42. syserror("Erreur lors de l'envoi ", 3)
  43. }
  44. }
  45. /* --- Fonctions publiques --- */
  46. Server server_create_udp() {
  47. /* Declaration variable */
  48. Server this;
  49. /* Creation socket */
  50. this = malloc(sizeof (struct server));
  51. this->socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  52. if (this->socket == ERR) {
  53. free(this);
  54. neterror(SOCKET_ERROR)
  55. }
  56. this->addr = sizeof (struct sockaddr_in);
  57. memset(&this->serv, 0, sizeof (struct sockaddr_in));
  58. /* Lien fonctions */
  59. this->server_bind = server_bind;
  60. this->server_receive = server_receive_udp;
  61. this->server_send = server_send_udp;
  62. this->server_accept = NULL;
  63. /* Type de serveur */
  64. this->type = SERV_UDP;
  65. /* Retour */
  66. return this;
  67. }
  68. void server_close_and_free(Server this) {
  69. /* Declaration variable */
  70. int tmp;
  71. /* Ferme */
  72. tmp = close(this->socket);
  73. if (tmp == -1) {
  74. free(this);
  75. syserror("Erreur lors de la fermeture de la socket ", 3)
  76. }
  77. /* Supprime */
  78. free(this);
  79. }