summaryrefslogtreecommitdiff
path: root/src/socket.c
blob: 82fee8c1dcb2c1909bed924794b86df096df1107 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>		/* close() */
#include <sys/types.h>		/* AF_INET, SOCK_STREAM */
#include <sys/socket.h>		/* socket() */
#include <arpa/inet.h>		/* htons(), hotnl() */
#include <netdb.h>		/* gethostbyname(), getaddrinfo() */

#include "socket.h"

int sock_connect(const char *host, const char *port)
{
	int sd, ret;
//	struct sockaddr_in *sa;
	struct addrinfo *ai, *ptr;
	struct addrinfo hint;

	if ((host == NULL) || (*host == 0)) {
		return -1;
	}
	memset(&hint, 0, sizeof(hint));
	hint.ai_flags = AI_ADDRCONFIG|AI_NUMERICSERV;
	hint.ai_family = AF_INET6;
	hint.ai_socktype = SOCK_STREAM;
	if ((ret=getaddrinfo(host, port, &hint, &ai)) != 0) {
		printf("%s: getaddrinfo returned %i\n", __FUNCTION__, ret);
		return -1;
	}
	for (ptr=ai; ptr != NULL; ptr=ptr->ai_next) {
		if ((sd=socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol)) == -1) {
			continue;
		}
		if (connect(sd, ptr->ai_addr, ptr->ai_addrlen) == -1) {
			close(sd);
			continue;
		}
//		sa=(struct sockaddr_in *)ptr->ai_addr;
		break;	/* if we get here, we have connected successfully */
	}
	if (ptr == NULL) {	/* end reached with no connect */
		return -1;
	}
	freeaddrinfo(ai);
	return sd;
}

/* --------------------------------------------------------------------
	Write to a socket
   -------------------------------------------------------------------- */
ssize_t sock_write(int sd, const char *buf, size_t len)
{
	ssize_t n, wrlen = 0;

	while (len) {
		n = write(sd, buf, len);
		if (n <= 0)
			return -1;
		len -= (size_t)n;
		wrlen += n;
		buf += n;
	}
	return wrlen;
}

/* --------------------------------------------------------------------
	Read a \n terminated line from a socket
   -------------------------------------------------------------------- */

ssize_t sock_readln(int sd, char *buf, size_t len)
{
	char *newline, *bp = buf;
	ssize_t n;

	if (--len < 1) {
		return -1;
	}
	do {
		/*
		* The reason for these gymnastics is that we want two things:
		* (1) to read \n-terminated lines,
		* (2) to return the true length of data read, even if the
		*     data coming in has embedded NULs.
		*/
		if ((n = recv(sd, bp, len, MSG_PEEK)) <= 0) {
			return -1;
		}
		if ((newline = memchr(bp, '\n', (size_t)n)) != NULL) {
			n = newline - bp + 1;
		}
		if ((n = read(sd, bp, n)) == -1) {
			return -1;
		}
		bp += n;
		len -= n;
	} while (!newline && len);
	*bp = '\0';
	return bp - buf;
}