ctrl_sock.c
1 // Copyright 2018 Espressif Systems (Shanghai) PTE LTD 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #include <string.h> 16 #include <unistd.h> 17 18 #include <sys/socket.h> 19 #include <netinet/in.h> 20 #include <arpa/inet.h> 21 22 #include "ctrl_sock.h" 23 24 /* Control socket, because in some network stacks select can't be woken up any 25 * other way 26 */ 27 int cs_create_ctrl_sock(int port) 28 { 29 int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); 30 if (fd < 0) { 31 return -1; 32 } 33 34 int ret; 35 struct sockaddr_in addr; 36 memset(&addr, 0, sizeof(addr)); 37 addr.sin_family = AF_INET; 38 addr.sin_port = htons(port); 39 inet_aton("127.0.0.1", &addr.sin_addr); 40 ret = bind(fd, (struct sockaddr *)&addr, sizeof(addr)); 41 if (ret < 0) { 42 close(fd); 43 return -1; 44 } 45 return fd; 46 } 47 48 void cs_free_ctrl_sock(int fd) 49 { 50 close(fd); 51 } 52 53 int cs_send_to_ctrl_sock(int send_fd, int port, void *data, unsigned int data_len) 54 { 55 int ret; 56 struct sockaddr_in to_addr; 57 to_addr.sin_family = AF_INET; 58 to_addr.sin_port = htons(port); 59 inet_aton("127.0.0.1", &to_addr.sin_addr); 60 ret = sendto(send_fd, data, data_len, 0, (struct sockaddr *)&to_addr, sizeof(to_addr)); 61 62 if (ret < 0) { 63 return -1; 64 } 65 return ret; 66 } 67 68 int cs_recv_from_ctrl_sock(int fd, void *data, unsigned int data_len) 69 { 70 int ret; 71 ret = recvfrom(fd, data, data_len, 0, NULL, NULL); 72 73 if (ret < 0) { 74 return -1; 75 } 76 return ret; 77 }