1 /*****************************************************************************
2 * getaddrinfo.c: getaddrinfo/getnameinfo replacement functions
3 *****************************************************************************
4 * Copyright (C) 2005 VLC authors and VideoLAN
5 * Copyright (C) 2002-2007 Rémi Denis-Courmont
8 * Author: Rémi Denis-Courmont <rem # videolan.org>
10 * This program is free software; you can redistribute it and/or modify it
11 * under the terms of the GNU Lesser General Public License as published by
12 * the Free Software Foundation; either version 2.1 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with this program; if not, write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23 *****************************************************************************/
29 #include <vlc_common.h>
31 #include <stddef.h> /* size_t */
32 #include <string.h> /* strlen(), memcpy(), memset(), strchr() */
33 #include <stdlib.h> /* malloc(), free(), strtoul() */
37 #include <sys/types.h>
38 #include <vlc_network.h>
44 int vlc_getnameinfo( const struct sockaddr *sa, int salen,
45 char *host, int hostlen, int *portnum, int flags )
47 char psz_servbuf[6], *psz_serv;
50 flags |= NI_NUMERICSERV;
53 psz_serv = psz_servbuf;
54 i_servlen = sizeof( psz_servbuf );
62 i_val = getnameinfo(sa, salen, host, hostlen, psz_serv, i_servlen, flags);
65 *portnum = atoi( psz_serv );
72 * Resolves a host name to a list of socket addresses (like getaddrinfo()).
74 * @param node host name to resolve (encoded as UTF-8), or NULL
75 * @param i_port port number for the socket addresses
76 * @param p_hints parameters (see getaddrinfo() manual page)
77 * @param res pointer set to the resulting chained list.
78 * @return 0 on success, a getaddrinfo() error otherwise.
79 * On failure, *res is undefined. On success, it must be freed with
82 int vlc_getaddrinfo (const char *node, unsigned port,
83 const struct addrinfo *hints, struct addrinfo **res)
85 char hostbuf[NI_MAXHOST], portbuf[6], *servname;
88 * In VLC, we always use port number as integer rather than strings
89 * for historical reasons (and portability).
96 snprintf (portbuf, sizeof (portbuf), "%u", port);
104 * - accept the empty string as unspecified host (i.e. NULL)
105 * - ignore square brackets (for IPv6 numerals)
111 size_t len = strlen (node + 1);
112 if ((len <= sizeof (hostbuf)) && (node[len] == ']'))
115 memcpy (hostbuf, node + 1, len - 1);
116 hostbuf[len - 1] = '\0';
124 return getaddrinfo (node, servname, hints, res);