sic

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

util.c (1348B)


      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 	struct addrinfo hints;
     22 	struct addrinfo *res, *r;
     23 	int fd;
     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((fd = socket(r->ai_family, r->ai_socktype, r->ai_protocol)) == -1)
     32 			continue;
     33 		if(connect(fd, r->ai_addr, r->ai_addrlen) == 0)
     34 			break;
     35 		close(fd);
     36 	}
     37 	freeaddrinfo(res);
     38 	if(!r)
     39 		eprint("error: cannot connect to host '%s'\n", host);
     40 	return fd;
     41 }
     42 
     43 static char *
     44 eat(char *s, int (*p)(int), int r) {
     45 	while(*s != '\0' && p((unsigned char)*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 	for (e = s + strlen(s); e > s && isspace((unsigned char)*(e - 1)); e--)
     64 		;
     65 	*e = '\0';
     66 }