xref: /haiku/src/bin/network/traceroute/findsaddr-haiku.c (revision 1deede7388b04dbeec5af85cae7164735ea9e70d)
1 /*
2  * Copyright 2007, Haiku Inc. All rights reserved.
3  * Distributed under the terms of the MIT License.
4  *
5  * Authors:
6  *		Hugo Santos <hugosantos@gmail.com>
7  */
8 
9 
10 #include <stdint.h>
11 #include <string.h>
12 #include <unistd.h>
13 #include <net/route.h>
14 #include <netinet/in.h>
15 #include <sys/ioctl.h>
16 #include <sys/socket.h>
17 #include <sys/sockio.h>
18 
19 #include "findsaddr.h"
20 	// is not self containing...
21 
22 
23 const char *
24 findsaddr(const struct sockaddr_in *to, struct sockaddr_in *from)
25 {
26 	uint8_t buffer[256];
27 	struct route_entry *request = (struct route_entry *)buffer;
28 
29 	int sock = socket(AF_INET, SOCK_DGRAM, 0);
30 	if (sock < 0)
31 		return "socket() failed";
32 
33 	memset(request, 0, sizeof(struct route_entry));
34 	request->destination = (struct sockaddr *)to;
35 
36 	if (ioctl(sock, SIOCGETRT, buffer, sizeof(buffer)) < 0) {
37 		close(sock);
38 		return "ioctl(SIOCGETRT) failed";
39 	}
40 
41 	if (request->source != NULL && request->source->sa_family == AF_INET)
42 		memcpy(from, request->source, sizeof(struct sockaddr_in));
43 
44 	close(sock);
45 
46 	if (request->source == NULL || request->source->sa_family != AF_INET)
47 		return "No address available";
48 
49 	return NULL;
50 }
51