zygo

ncurses gopher client
git clone https://hhvn.uk/zygo
git clone git://hhvn.uk/zygo
Log | Files | Refs

plain.c (1606B)


      1 /*
      2  * zygo/plain.c
      3  *
      4  * Copyright (c) 2022 hhvn <dev@hhvn.uk>
      5  *
      6  * Permission to use, copy, modify, and distribute this software for any
      7  * purpose with or without fee is hereby granted, provided that the above
      8  * copyright notice and this permission notice appear in all copies.
      9  *
     10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
     11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
     12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
     13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
     15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
     16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     17  *
     18  */
     19 
     20 #include <unistd.h>
     21 #include <netdb.h>
     22 #include <sys/socket.h>
     23 #include "zygo.h"
     24 
     25 static int fd;
     26 static struct addrinfo *ai = NULL;
     27 
     28 int
     29 net_connect(Elem *e, int silent) {
     30 	int ret;
     31 
     32 	if (ai)
     33 		freeaddrinfo(ai);
     34 
     35 	if ((ret = getaddrinfo(e->server, e->port, NULL, &ai)) != 0 || ai == NULL) {
     36 		if (!silent)
     37 			error("could not lookup %s:%s", e->server, e->port);
     38 		return -1;
     39 	}
     40 
     41 	if ((fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) == -1 ||
     42 			connect(fd, ai->ai_addr, ai->ai_addrlen) == -1) {
     43 		if (!silent)
     44 			error("could not connect to %s:%s", e->server, e->port);
     45 		return -1;
     46 	}
     47 
     48 	return 0;
     49 }
     50 
     51 int
     52 net_read(void *buf, size_t count) {
     53 	return read(fd, buf, count);
     54 }
     55 
     56 int
     57 net_write(void *buf, size_t count) {
     58 	return write(fd, buf, count);
     59 }
     60 
     61 int
     62 net_close(void) {
     63 	return close(fd);
     64 }