2 * Copyright (C) 2006 Stig Venaas <venaas@uninett.no>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
17 void errx(char *format, ...) {
22 vfprintf(stderr, format, ap);
25 fprintf(stderr, ": ");
27 fprintf(stderr, "errno=%d\n", errno);
29 fprintf(stderr, "\n");
33 void err(char *format, ...) {
38 vfprintf(stderr, format, ap);
41 fprintf(stderr, ": ");
43 fprintf(stderr, "errno=%d\n", errno);
45 fprintf(stderr, "\n");
48 char *addr2string(struct sockaddr *addr, socklen_t len) {
49 struct sockaddr_in6 *sa6;
50 struct sockaddr_in sa4;
51 static char addr_buf[2][INET6_ADDRSTRLEN];
54 if (addr->sa_family == AF_INET6) {
55 sa6 = (struct sockaddr_in6 *)addr;
56 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
57 memset(&sa4, 0, sizeof(sa4));
58 sa4.sin_family = AF_INET;
59 sa4.sin_port = sa6->sin6_port;
60 memcpy(&sa4.sin_addr, &sa6->sin6_addr.s6_addr[12], 4);
61 addr = (struct sockaddr *)&sa4;
64 if (getnameinfo(addr, len, addr_buf[i], sizeof(addr_buf[i]),
65 NULL, 0, NI_NUMERICHOST)) {
72 int bindport(int type, char *port) {
73 struct addrinfo hints, *res0, *res;
76 memset(&hints, 0, sizeof(hints));
77 hints.ai_socktype = type;
78 hints.ai_family = AF_UNSPEC;
79 hints.ai_flags = AI_PASSIVE;
81 if (getaddrinfo(NULL, port, &hints, &res0) != 0) {
82 err("bindport: can't resolve port %s", port);
85 for (res = res0; res; res = res->ai_next) {
86 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
88 if (bind(s, res->ai_addr, res->ai_addrlen) == 0)
98 int connectport(int type, char *host, char *port) {
99 struct addrinfo hints, *res0, *res;
102 memset(&hints, 0, sizeof(hints));
103 hints.ai_socktype = type;
104 hints.ai_family = AF_UNSPEC;
106 if (getaddrinfo(host, port, &hints, &res0) != 0) {
107 err("connectport: can't resolve host %s port %s", host, port);
111 for (res = res0; res; res = res->ai_next) {
112 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
114 err("connectport: socket failed");
117 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
119 err("connectport: connect failed");