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 <unistd.h> 12 #include <net/route.h> 13 #include <netinet/in.h> 14 #include <sys/ioctl.h> 15 #include <sys/socket.h> 16 #include <sys/sockio.h> 17 18 #include "findsaddr.h" 19 // is not self containing... 20 21 22 const char * 23 findsaddr(const struct sockaddr_in *to, struct sockaddr_in *from) 24 { 25 uint8_t buffer[256]; 26 struct route_entry *request = (struct route_entry *)buffer; 27 28 int sock = socket(AF_INET, SOCK_DGRAM, 0); 29 if (sock < 0) 30 return "socket() failed"; 31 32 memset(request, 0, sizeof(struct route_entry)); 33 request->destination = (struct sockaddr *)to; 34 35 if (ioctl(sock, SIOCGETRT, buffer, sizeof(buffer)) < 0) { 36 close(sock); 37 return "ioctl(SIOCGETRT) failed"; 38 } 39 40 if (request->source != NULL && request->source->sa_family == AF_INET) 41 memcpy(from, request->source, sizeof(struct sockaddr_in)); 42 43 close(sock); 44 45 if (request->source == NULL || request->source->sa_family != AF_INET) 46 return "No address available"; 47 48 return NULL; 49 } 50