/*
 * Copyright (c) 2004 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: netsockconnipv4.c,v 1.1 2004/07/20 17:40:18 ca Exp $")
#include "sm/assert.h"
#include "sm/error.h"
#include "sm/memops.h"
#include "sm/fcntl.h"
#include "sm/net.h"

/*
**  NET_CLIENT_CONNECTIPV4 -- Create a socket and connect it to a server.
**
**	Parameters:
**		ipv4 -- 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_connectipv4(ipv4_T ipv4, int port, int *pfd)
{
	int sockfd, err;
	struct sockaddr_in servaddr;

	SM_REQUIRE(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);
	sm_memcpy(&servaddr.sin_addr, &ipv4, sizeof(ipv4));
	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