blob: 35c4ee12ed68cdc439e324f2f00491fa3b9356b9 [file] [log] [blame]
mj.quf47abdc2025-01-14 17:23:20 -08001#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4#include <unistd.h>
5#include <sys/socket.h>
6#include "wefota_socket.h"
7#include "wefota_main.h"
8#include <errno.h>
9
10#define WEFOTA_RECV_TIMEOUT_SEC 3
11
12int create_udp_socket(void) {
13 int sock = socket(AF_INET, SOCK_DGRAM, 0);
14 if (sock < 0) {
15 perror("socket create failed");
16 return -1;
17 }
18 return sock;
19}
20
21void close_udp_socket(int sock) {
22 if (sock >= 0) {
23 close(sock);
24 }
25}
26
27int init_server_addr(struct sockaddr_in* addr, const char* ip, int port) {
28 if (addr == NULL || ip == NULL || port <= 0) {
29 return -1;
30 }
31
32 memset(addr, 0, sizeof(*addr));
33 addr->sin_family = AF_INET;
34 if (inet_pton(AF_INET, ip, &(addr->sin_addr)) <= 0) {
35 perror("wrong ip address");
36 return -1;
37 }
38 addr->sin_port = htons(port);
39 return 0;
40}
41
42int send_message(int sock, const void* msg, size_t len, struct sockaddr_in* server_addr) {
43 int sent = sendto(sock, msg, len, 0,
44 (struct sockaddr*)server_addr, sizeof(*server_addr));
45 if (sent < 0) {
46 perror("send message failed");
47 return -1;
48 }
49 printf("send message end, sent=%d\n", sent);
50 return 0;
51}
52
53int receive_message(int sock, void* response, size_t response_size, struct sockaddr_in* server_addr) {
54 set_recv_timeout(sock, WEFOTA_RECV_TIMEOUT_SEC);
55 socklen_t addr_len = sizeof(*server_addr);
56 int received = recvfrom(sock, response, response_size, 0,
57 (struct sockaddr*)server_addr, &addr_len);
58 if (received < 0)
59 {
60 printf("error num:%d\n", errno);
61 perror("recvfrom");
62 }
63 printf("recv message end, received=%d\n", received);
64 return received;
65}
66
67int set_recv_timeout(int sock, int timeout_sec) {
68 struct timeval tv;
69 tv.tv_sec = timeout_sec;
70 tv.tv_usec = 0;
71
72 if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) {
73 perror("set socket timeout failed");
74 return -1;
75 }
76 return 0;
77}