2002-07-03 17:21:44 +05:30
|
|
|
/* vi: set sw=4 ts=4: */
|
|
|
|
/*
|
|
|
|
* Utility routines.
|
|
|
|
*
|
|
|
|
* Connect to host at port using address resolusion from getaddrinfo
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
|
|
|
|
#include <unistd.h>
|
|
|
|
#include <string.h>
|
2002-07-11 16:10:43 +05:30
|
|
|
#include <stdlib.h>
|
2002-07-03 17:21:44 +05:30
|
|
|
#include <sys/types.h>
|
|
|
|
#include <sys/socket.h>
|
2003-10-31 15:01:46 +05:30
|
|
|
#include <errno.h>
|
2002-07-03 17:21:44 +05:30
|
|
|
#include <netdb.h>
|
2003-10-31 15:01:46 +05:30
|
|
|
#include <sys/socket.h>
|
2002-07-11 16:10:43 +05:30
|
|
|
#include <netinet/in.h>
|
2003-10-31 15:01:46 +05:30
|
|
|
#include <arpa/inet.h>
|
2002-07-03 17:21:44 +05:30
|
|
|
#include "libbb.h"
|
|
|
|
|
2003-11-04 02:50:18 +05:30
|
|
|
int bb_getport(const char *port)
|
2002-07-03 17:21:44 +05:30
|
|
|
{
|
2003-10-31 15:01:46 +05:30
|
|
|
int port_nr;
|
|
|
|
char *endptr;
|
|
|
|
struct servent *tserv;
|
2002-07-03 17:21:44 +05:30
|
|
|
|
2003-10-31 15:01:46 +05:30
|
|
|
if (!port) {
|
|
|
|
return -1;
|
2002-07-03 17:21:44 +05:30
|
|
|
}
|
2003-10-31 15:01:46 +05:30
|
|
|
port_nr=strtol(port, &endptr, 10);
|
|
|
|
if (errno != 0 || *endptr!='\0' || endptr==port || port_nr < 1 || port_nr > 65536)
|
2002-07-03 17:21:44 +05:30
|
|
|
{
|
2003-10-31 15:01:46 +05:30
|
|
|
if (port_nr==0 && (tserv = getservbyname(port, "tcp")) != NULL) {
|
|
|
|
port_nr = tserv->s_port;
|
|
|
|
} else {
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
port_nr = htons(port_nr);
|
2002-07-03 17:21:44 +05:30
|
|
|
}
|
2003-10-31 15:01:46 +05:30
|
|
|
return port_nr;
|
|
|
|
}
|
2002-07-03 17:21:44 +05:30
|
|
|
|
2003-11-04 02:50:18 +05:30
|
|
|
void bb_lookup_host(struct sockaddr_in *s_in, const char *host, const char *port)
|
2003-10-31 15:01:46 +05:30
|
|
|
{
|
|
|
|
struct hostent *he;
|
2002-07-03 17:21:44 +05:30
|
|
|
|
2003-10-31 15:01:46 +05:30
|
|
|
memset(s_in, 0, sizeof(struct sockaddr_in));
|
|
|
|
s_in->sin_family = AF_INET;
|
2002-07-03 17:21:44 +05:30
|
|
|
he = xgethostbyname(host);
|
2003-10-31 15:01:46 +05:30
|
|
|
memcpy(&(s_in->sin_addr), he->h_addr_list[0], he->h_length);
|
2002-07-03 17:21:44 +05:30
|
|
|
|
2003-10-31 15:01:46 +05:30
|
|
|
if (port) {
|
|
|
|
s_in->sin_port=bb_getport(port);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
int xconnect(struct sockaddr_in *s_addr)
|
|
|
|
{
|
|
|
|
int s = socket(AF_INET, SOCK_STREAM, 0);
|
|
|
|
if (connect(s, (struct sockaddr_in *)s_addr, sizeof(struct sockaddr_in)) < 0)
|
2002-07-03 17:21:44 +05:30
|
|
|
{
|
2003-10-31 15:01:46 +05:30
|
|
|
bb_perror_msg_and_die("Unable to connect to remote host (%s)",
|
|
|
|
inet_ntoa(s_addr->sin_addr));
|
2002-07-03 17:21:44 +05:30
|
|
|
}
|
|
|
|
return s;
|
|
|
|
}
|