From 2d3efdb6ee40832f3830293788132790b3e20a4a Mon Sep 17 00:00:00 2001 From: Felix Ruess Date: Wed, 4 Mar 2015 12:10:53 +0100 Subject: [PATCH] [arch/linu] udp_socket: possibility to use hostname --- sw/airborne/arch/linux/udp_socket.c | 30 ++++++++++++++++++++++++++--- sw/airborne/arch/linux/udp_socket.h | 3 ++- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/sw/airborne/arch/linux/udp_socket.c b/sw/airborne/arch/linux/udp_socket.c index ebc98a80b8..e6c5141b6c 100644 --- a/sw/airborne/arch/linux/udp_socket.c +++ b/sw/airborne/arch/linux/udp_socket.c @@ -27,9 +27,11 @@ #include "udp_socket.h" #include #include +#include #include #include #include +#include //#define TRACE(type,fmt,args...) fprintf(stderr, fmt, args) #define TRACE(type,fmt,args...) @@ -42,11 +44,32 @@ * @param[in] port_out output port * @param[in] port_in input port (set to < 0 to disable) * @param[in] broadcast if TRUE enable broadcasting + * @return -1 on error, otherwise 0 */ -void udp_socket_create(struct UdpNetwork *network, char *host, int port_out, int port_in, bool_t broadcast) +int udp_socket_create(struct UdpNetwork *network, char *host, int port_out, int port_in, bool_t broadcast) { if (network == NULL) { - return; + return -1; + } + + /* try to convert host ipv4 address to binary format */ + struct in_addr host_ip; + if (!inet_aton(host, &host_ip)) { + /* not an IP address, try to resolve hostname */ + struct hostent *hp; + hp = gethostbyname(host); + if (!hp) { + fprintf(stderr, "could not obtain address of %s\n", host); + return -1; + } + /* check if IPv4 address */ + if (hp->h_addrtype == AF_INET && hp->h_length == 4) { + /* simply use first address */ + memcpy(&host_ip.s_addr, hp->h_addr_list[0], hp->h_length); + } + else { + return -1; + } } // Create the socket with the correct protocl @@ -73,7 +96,8 @@ void udp_socket_create(struct UdpNetwork *network, char *host, int port_out, int // set the output/destination address for use in sendto later network->addr_out.sin_family = PF_INET; network->addr_out.sin_port = htons(port_out); - network->addr_out.sin_addr.s_addr = inet_addr(host); + network->addr_out.sin_addr.s_addr = host_ip.s_addr; + return 0; } /** diff --git a/sw/airborne/arch/linux/udp_socket.h b/sw/airborne/arch/linux/udp_socket.h index 5a9b89005a..179a86a090 100644 --- a/sw/airborne/arch/linux/udp_socket.h +++ b/sw/airborne/arch/linux/udp_socket.h @@ -44,8 +44,9 @@ struct UdpNetwork { * @param[in] port_out output port * @param[in] port_in input port (set to < 0 to disable) * @param[in] broadcast if TRUE enable broadcasting + * @return -1 on error, otherwise 0 */ -extern void udp_socket_create(struct UdpNetwork *network, char *host, int port_out, int port_in, bool_t broadcast); +extern int udp_socket_create(struct UdpNetwork *network, char *host, int port_out, int port_in, bool_t broadcast); /** * Send a packet from buffer, blocking.