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.
9 #include <sys/socket.h>
10 #include <netinet/in.h>
19 void errx(char *format, ...) {
24 vfprintf(stderr, format, ap);
27 fprintf(stderr, ": ");
29 fprintf(stderr, "errno=%d\n", errno);
31 fprintf(stderr, "\n");
35 void err(char *format, ...) {
40 vfprintf(stderr, format, ap);
43 fprintf(stderr, ": ");
45 fprintf(stderr, "errno=%d\n", errno);
47 fprintf(stderr, "\n");
50 char *stringcopy(char *s, int len) {
56 errx("stringcopy: malloc failed");
62 char *addr2string(struct sockaddr *addr, socklen_t len) {
63 struct sockaddr_in6 *sa6;
64 struct sockaddr_in sa4;
65 static char addr_buf[2][INET6_ADDRSTRLEN];
68 if (addr->sa_family == AF_INET6) {
69 sa6 = (struct sockaddr_in6 *)addr;
70 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
71 memset(&sa4, 0, sizeof(sa4));
72 sa4.sin_family = AF_INET;
73 sa4.sin_port = sa6->sin6_port;
74 memcpy(&sa4.sin_addr, &sa6->sin6_addr.s6_addr[12], 4);
75 addr = (struct sockaddr *)&sa4;
78 if (getnameinfo(addr, len, addr_buf[i], sizeof(addr_buf[i]),
79 NULL, 0, NI_NUMERICHOST)) {
86 int bindport(int type, char *port) {
87 struct addrinfo hints, *res0, *res;
90 memset(&hints, 0, sizeof(hints));
91 hints.ai_socktype = type;
92 hints.ai_family = AF_UNSPEC;
93 hints.ai_flags = AI_PASSIVE;
95 if (getaddrinfo(NULL, port, &hints, &res0) != 0) {
96 err("bindport: can't resolve port %s", port);
99 for (res = res0; res; res = res->ai_next) {
100 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
102 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
103 if (bind(s, res->ai_addr, res->ai_addrlen) == 0)
113 int connectport(int type, char *host, char *port) {
114 struct addrinfo hints, *res0, *res;
117 memset(&hints, 0, sizeof(hints));
118 hints.ai_socktype = type;
119 hints.ai_family = AF_UNSPEC;
121 if (getaddrinfo(host, port, &hints, &res0) != 0) {
122 err("connectport: can't resolve host %s port %s", host, port);
126 for (res = res0; res; res = res->ai_next) {
127 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
129 err("connectport: socket failed");
132 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
134 err("connectport: connect failed");