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 *stringcopy(char *s, int len) {
54 errx("stringcopy: malloc failed");
60 char *addr2string(struct sockaddr *addr, socklen_t len) {
61 struct sockaddr_in6 *sa6;
62 struct sockaddr_in sa4;
63 static char addr_buf[2][INET6_ADDRSTRLEN];
66 if (addr->sa_family == AF_INET6) {
67 sa6 = (struct sockaddr_in6 *)addr;
68 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
69 memset(&sa4, 0, sizeof(sa4));
70 sa4.sin_family = AF_INET;
71 sa4.sin_port = sa6->sin6_port;
72 memcpy(&sa4.sin_addr, &sa6->sin6_addr.s6_addr[12], 4);
73 addr = (struct sockaddr *)&sa4;
76 if (getnameinfo(addr, len, addr_buf[i], sizeof(addr_buf[i]),
77 NULL, 0, NI_NUMERICHOST)) {
84 int bindport(int type, char *port) {
85 struct addrinfo hints, *res0, *res;
88 memset(&hints, 0, sizeof(hints));
89 hints.ai_socktype = type;
90 hints.ai_family = AF_UNSPEC;
91 hints.ai_flags = AI_PASSIVE;
93 if (getaddrinfo(NULL, port, &hints, &res0) != 0) {
94 err("bindport: can't resolve port %s", port);
97 for (res = res0; res; res = res->ai_next) {
98 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
100 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
101 if (bind(s, res->ai_addr, res->ai_addrlen) == 0)
111 int connectport(int type, char *host, char *port) {
112 struct addrinfo hints, *res0, *res;
115 memset(&hints, 0, sizeof(hints));
116 hints.ai_socktype = type;
117 hints.ai_family = AF_UNSPEC;
119 if (getaddrinfo(host, port, &hints, &res0) != 0) {
120 err("connectport: can't resolve host %s port %s", host, port);
124 for (res = res0; res; res = res->ai_next) {
125 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
127 err("connectport: socket failed");
130 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
132 err("connectport: connect failed");