sic

simple irc client
git clone git://git.suckless.org/sic
Log | Files | Refs | README | LICENSE

util.c (1334B)


      1 /* See LICENSE file for license details. */
      2 #include <netdb.h>
      3 #include <netinet/in.h>
      4 #include <sys/socket.h>
      5 
      6 static void
      7 eprint(const char *fmt, ...) {
      8 	va_list ap;
      9 
     10 	va_start(ap, fmt);
     11 	vsnprintf(bufout, sizeof bufout, fmt, ap);
     12 	va_end(ap);
     13 	fprintf(stderr, "%s", bufout);
     14 	if(fmt[0] && fmt[strlen(fmt) - 1] == ':')
     15 		fprintf(stderr, " %s\n", strerror(errno));
     16 	exit(1);
     17 }
     18 
     19 static int
     20 dial(char *host, char *port) {
     21 	static struct addrinfo hints;
     22 	int srv;
     23 	struct addrinfo *res, *r;
     24 
     25 	memset(&hints, 0, sizeof hints);
     26 	hints.ai_family = AF_UNSPEC;
     27 	hints.ai_socktype = SOCK_STREAM;
     28 	if(getaddrinfo(host, port, &hints, &res) != 0)
     29 		eprint("error: cannot resolve hostname '%s':", host);
     30 	for(r = res; r; r = r->ai_next) {
     31 		if((srv = socket(r->ai_family, r->ai_socktype, r->ai_protocol)) == -1)
     32 			continue;
     33 		if(connect(srv, r->ai_addr, r->ai_addrlen) == 0)
     34 			break;
     35 		close(srv);
     36 	}
     37 	freeaddrinfo(res);
     38 	if(!r)
     39 		eprint("error: cannot connect to host '%s'\n", host);
     40 	return srv;
     41 }
     42 
     43 static char *
     44 eat(char *s, int (*p)(int), int r) {
     45 	while(*s != '\0' && p(*s) == r)
     46 		s++;
     47 	return s;
     48 }
     49 
     50 static char*
     51 skip(char *s, char c) {
     52 	while(*s != c && *s != '\0')
     53 		s++;
     54 	if(*s != '\0')
     55 		*s++ = '\0';
     56 	return s;
     57 }
     58 
     59 static void
     60 trim(char *s) {
     61 	char *e;
     62 
     63 	e = s + strlen(s) - 1;
     64 	while(isspace(*e) && e > s)
     65 		e--;
     66 	*(e + 1) = '\0';
     67 }