blob: 35c4ee12ed68cdc439e324f2f00491fa3b9356b9 [file] [log] [blame]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include "wefota_socket.h"
#include "wefota_main.h"
#include <errno.h>
#define WEFOTA_RECV_TIMEOUT_SEC 3
int create_udp_socket(void) {
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) {
perror("socket create failed");
return -1;
}
return sock;
}
void close_udp_socket(int sock) {
if (sock >= 0) {
close(sock);
}
}
int init_server_addr(struct sockaddr_in* addr, const char* ip, int port) {
if (addr == NULL || ip == NULL || port <= 0) {
return -1;
}
memset(addr, 0, sizeof(*addr));
addr->sin_family = AF_INET;
if (inet_pton(AF_INET, ip, &(addr->sin_addr)) <= 0) {
perror("wrong ip address");
return -1;
}
addr->sin_port = htons(port);
return 0;
}
int send_message(int sock, const void* msg, size_t len, struct sockaddr_in* server_addr) {
int sent = sendto(sock, msg, len, 0,
(struct sockaddr*)server_addr, sizeof(*server_addr));
if (sent < 0) {
perror("send message failed");
return -1;
}
printf("send message end, sent=%d\n", sent);
return 0;
}
int receive_message(int sock, void* response, size_t response_size, struct sockaddr_in* server_addr) {
set_recv_timeout(sock, WEFOTA_RECV_TIMEOUT_SEC);
socklen_t addr_len = sizeof(*server_addr);
int received = recvfrom(sock, response, response_size, 0,
(struct sockaddr*)server_addr, &addr_len);
if (received < 0)
{
printf("error num:%d\n", errno);
perror("recvfrom");
}
printf("recv message end, received=%d\n", received);
return received;
}
int set_recv_timeout(int sock, int timeout_sec) {
struct timeval tv;
tv.tv_sec = timeout_sec;
tv.tv_usec = 0;
if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) {
perror("set socket timeout failed");
return -1;
}
return 0;
}