1/*	$OpenBSD: srcaddr.c,v 1.1 2020/04/13 03:09:29 pamela Exp $	*/
2
3/*
4 * Copyright (c) 2020 Pamela Mosiejczuk <pamela@openbsd.org>
5 * Copyright (c) 2020 Florian Obser <florian@openbsd.org>
6 *
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 */
19
20#include <sys/types.h>
21#include <sys/socket.h>
22
23#include <err.h>
24#include <netdb.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
28#include <unistd.h>
29
30__dead void	usage(void);
31
32/* given an IPv6 destination address, return the source address selected */
33int
34main(int argc, char *argv[])
35{
36	struct addrinfo		 hints, *res;
37	struct sockaddr_storage	 ss;
38	socklen_t		 len;
39	int			 ch, error, s;
40	char			*target, src[NI_MAXHOST];
41
42	while ((ch = getopt(argc, argv, "")) != -1) {
43		switch (ch) {
44		default:
45			usage();
46		}
47	}
48	argc -= optind;
49	argv += optind;
50
51	if (argc != 1)
52		usage();
53
54	target = *argv;
55
56	memset(&hints, 0, sizeof(hints));
57	hints.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;
58	hints.ai_family = AF_INET6;
59	hints.ai_socktype = SOCK_DGRAM;
60
61	if ((error = getaddrinfo(target, "8888", &hints, &res)))
62		errx(1, "%s", gai_strerror(error));
63
64	s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
65	if (s == -1)
66		err(1, "socket");
67
68	if (connect(s, res->ai_addr, res->ai_addrlen) == -1)
69		err(1, "connect");
70	freeaddrinfo(res);
71
72	len = sizeof(ss);
73	if (getsockname(s, (struct sockaddr *)&ss, &len) == -1)
74		err(1, "getsockname");
75
76	if ((error = getnameinfo((struct sockaddr *)&ss, ss.ss_len, src,
77	    sizeof(src), NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)))
78		errx(1, "%s", gai_strerror(error));
79
80	printf("%s\n", src);
81
82	return (0);
83}
84
85__dead void
86usage(void)
87{
88	fprintf(stderr, "usage: srcaddr destination\n");
89	exit (1);
90}
91