/*
 * Copyright (c) 2002, 2004, 2005 Sendmail, Inc. and its suppliers.
 *	All rights reserved.
 *
 * By using this file, you agree to the terms and conditions set
 * forth in the LICENSE file which can be found at the top level of
 * the sendmail distribution.
 */

#include "sm/generic.h"
SM_RCSID("@(#)$Id: netsockconn.c,v 1.6 2005/01/18 00:07:58 ca Exp $")
#include "sm/assert.h"
#include "sm/error.h"
#include "sm/memops.h"
#include "sm/fcntl.h"
#include "sm/net.h"

/*
**  NET_CLIENT_CONNECT -- Create a socket and connect it to a server.
**
**	Only takes an IP address, see below for hostname
**
**	Parameters:
**		ip -- IP to connect to
**		port -- port on host to connect to
**		pfd -- (pointer to) file descriptor (output)
**
**	Returns:
**		usual sm_error code
*/

sm_ret_T
net_client_connect(const char *ip, int port, int *pfd)
{
	int sockfd, err;
	struct sockaddr_in servaddr;
	ulong hostaddr;

	SM_ASSERT(ip != NULL);
	SM_ASSERT(port > 0);
	SM_REQUIRE(pfd != NULL);

	*pfd = INVALID_SOCKET;
	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
		return sm_error_perm(SM_EM_NET, errno);
	sm_memzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(port);
	if ((hostaddr = inet_addr(ip)) == INADDR_NONE)
		return sm_error_perm(SM_EM_NET, errno);
	sm_memcpy(&servaddr.sin_addr, &hostaddr, sizeof(hostaddr));
	if ((connect(sockfd, (struct sockaddr *) &servaddr,
		     sizeof(servaddr))) == -1)
	{
		err = sm_error_perm(SM_EM_NET, errno);
		(void) close(sockfd);
		return err;
	}
	*pfd = sockfd;
	return SM_SUCCESS;
}


syntax highlighted by Code2HTML, v. 0.9.1