udp_send.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include "udp_send.h"
  2. #include "main.h"
  3. #include <string.h>
  4. #include <stdio.h>
  5. #include "stm32f2xx.h"
  6. #include "lwip/opt.h"
  7. #include "lwip/tcp.h"
  8. #include "lwip/sys.h"
  9. #include "lwip/memp.h"
  10. #include "lwip/api.h"
  11. #include "lwip/sockets.h"
  12. volatile int8_t sockfd=-1;
  13. #define UDP_LOCAL_PORT 12345
  14. #define UDP_REMOTE_PORT 54321
  15. #define SERCER_IP_ADDRESS "192.168.2.211" //接收服务器ip
  16. struct sockaddr_in remote_addr;
  17. int udp_log_start()
  18. {
  19. int ret;
  20. struct sockaddr_in local_addr;
  21. // 创建UDP套接字
  22. sockfd = socket(AF_INET, SOCK_DGRAM, 0);
  23. if (sockfd < -1) {
  24. perror("Error creating socket");
  25. goto exit;
  26. }
  27. local_addr.sin_family=AF_INET;
  28. local_addr.sin_port=htons(UDP_LOCAL_PORT);
  29. local_addr.sin_addr.s_addr=INADDR_ANY;
  30. ret = bind(sockfd, (struct sockaddr *)&local_addr, sizeof(local_addr));
  31. if(ret < 0)
  32. {
  33. lwip_close(sockfd);
  34. sockfd = -1;
  35. goto exit;
  36. }
  37. //设置远程服务器地址 TODO:服务器地址配置后自动获取
  38. remote_addr.sin_family=AF_INET;
  39. remote_addr.sin_port=htons(UDP_REMOTE_PORT);
  40. inet_aton(SERCER_IP_ADDRESS,&(remote_addr.sin_addr));
  41. return 1;
  42. exit:
  43. return -1;
  44. }
  45. void udp_log_close()
  46. {
  47. lwip_close(sockfd);
  48. sockfd=-1;
  49. }
  50. int fputc(int ch, FILE *f)
  51. {
  52. if(sockfd>=0)
  53. {
  54. sendto(sockfd, &ch, 1, 0, (struct sockaddr *)&remote_addr,sizeof(remote_addr));
  55. return ch;
  56. }
  57. return 1;
  58. }
  59. int udp_send_printf(char *p)
  60. {
  61. if(sockfd>=0)
  62. {
  63. sendto(sockfd, p, strlen(p), 0, (struct sockaddr *)&remote_addr,sizeof(remote_addr));
  64. }
  65. return 1;
  66. }