Guest User

Untitled

a guest
Dec 16th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. typedef struct{
  2. uint8_t ver : 2;
  3. uint8_t t : 2;
  4. uint8_t tkl : 4;
  5. uint8_t code;
  6. uint16_t id;
  7. } coap_header;
  8.  
  9. typedef struct{
  10. coap_header hdr;
  11. coap_buffer tok; //coap_buffer is another struct
  12. uint8_t numopt;
  13. coap_option opt[MAXOPT]; /coap_option is another struct
  14. coap_buffer payload;
  15. } coap_packet;
  16.  
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <unistd.h>
  20. #include <string.h>
  21. #include <sys/types.h>
  22. #include <sys/socket.h>
  23. #include <arpa/inet.h>
  24. #include <netinet/in.h>
  25. #include "coapHead.h"
  26.  
  27. #define PORT 8080
  28. #define MAXLINE 1024
  29.  
  30. int main(){
  31. int sockfd;
  32. char buffer[MAXLINE];
  33. char *hello = "Hello from server. Packet Received.";
  34. struct sockaddr_in servaddr, cliaddr;
  35. struct coap_packet *temp = malloc(sizeof(coap_packet));
  36.  
  37. //Creating socket file descriptor
  38. if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0){
  39. perror("Socket creation failed");
  40. exit(EXIT_FAILURE);
  41. }
  42.  
  43. memset(&servaddr, 0, sizeof(servaddr));
  44. memset(&cliaddr, 0, sizeof(cliaddr));
  45.  
  46. //Filling information
  47. servaddr.sin_family = AF_INET;
  48. servaddr.sin_addr.s_addr = INADDR_ANY;
  49. servaddr.sin_port = htons(PORT);
  50.  
  51. //Binding socket with server address
  52. if(bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr)) < 0){
  53. perror("Binding Failed!");
  54. exit(EXIT_FAILURE);
  55. }
  56.  
  57. int i=0;
  58. while(i<6){
  59. int n, len;
  60. n = recvfrom(sockfd, temp, sizeof(temp), MSG_WAITALL, (struct sockaddr *)&cliaddr, &len);
  61. // buffer[n] = '';
  62. printf("Client Packet received.nMessage ID: %dnMessage Type: %dn", (temp->hdr).id, (temp->hdr).t);
  63. sendto(sockfd, (const char*)hello, strlen(hello), MSG_CONFIRM, (const struct sockaddr *)&cliaddr, len);
  64. printf("Hello message sent.n");
  65. i+=1;
  66. }
  67.  
  68. return 0;
  69. }
Add Comment
Please, Sign In to add comment