58 lines
1.3 KiB
C
58 lines
1.3 KiB
C
//
|
|
// IP gethostname
|
|
//
|
|
|
|
#include "netlib.h"
|
|
|
|
int ip_host2addr( const char *host, const char *service, struct sockaddr_storage *sa, socklen_t *len )
|
|
{
|
|
struct hostent *ent;
|
|
|
|
/* do host lookup matching family (this is not POSIX) */
|
|
if ( (ent = gethostbyname2( host, AF_INET6 )) == NULL )
|
|
{
|
|
if ( (ent = gethostbyname2( host, AF_INET )) == NULL )
|
|
{
|
|
log_error( "gethostbyname" );
|
|
return -1;
|
|
}
|
|
}
|
|
int family = ent->h_addrtype;
|
|
|
|
// service
|
|
int port = ip_service2port( service, atoi(service), NULL );
|
|
|
|
/* clear and initialize address structure */
|
|
if ( sa )
|
|
bzero(sa, sizeof(struct sockaddr_storage) );
|
|
|
|
if ( family == AF_INET6 )
|
|
{
|
|
if ( sa )
|
|
{
|
|
struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)sa;
|
|
sa6->sin6_family = family;
|
|
sa6->sin6_port = port;
|
|
sa6->sin6_addr = *((struct in6_addr *)ent->h_addr);
|
|
}
|
|
if ( len )
|
|
*len = sizeof(struct sockaddr_in6);
|
|
}
|
|
else if ( family == AF_INET )
|
|
{
|
|
if ( sa )
|
|
{
|
|
struct sockaddr_in *sa4 = (struct sockaddr_in *)sa;
|
|
sa4->sin_family = family;
|
|
sa4->sin_port = port;
|
|
sa4->sin_addr = *((struct in_addr *)ent->h_addr);
|
|
}
|
|
if ( len )
|
|
*len = sizeof(struct sockaddr_in);
|
|
}
|
|
else
|
|
return -1;
|
|
|
|
return family;
|
|
}
|