| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
#include <arpa/inet.h> |
| 27 |
#include <netinet/ip.h> |
| 28 |
|
| 29 |
#include <sys/socket.h> |
| 30 |
|
| 31 |
#include <linux/netlink.h> |
| 32 |
#include <linux/rtnetlink.h> |
| 33 |
|
| 34 |
#include <string.h> |
| 35 |
#include <stdlib.h> |
| 36 |
#include <stdio.h> |
| 37 |
#include <unistd.h> |
| 38 |
|
| 39 |
#define NLMSG_TAIL(nmsg) \ |
| 40 |
((struct rtattr *) (((void *) (nmsg)) + NLMSG_ALIGN((nmsg)->nlmsg_len))) |
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
int source_for_dest(const struct in_addr *dest, struct in_addr *loc_source) |
| 48 |
{ |
| 49 |
int fd, rc; |
| 50 |
struct rtmsg *r; |
| 51 |
struct rtattr *rta; |
| 52 |
struct { |
| 53 |
struct nlmsghdr n; |
| 54 |
struct rtmsg r; |
| 55 |
char buf[1024]; |
| 56 |
} req; |
| 57 |
|
| 58 |
memset(&req, 0, sizeof(req)); |
| 59 |
|
| 60 |
fd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, NETLINK_ROUTE); |
| 61 |
if (fd < 0) { |
| 62 |
perror("nl socket"); |
| 63 |
return -1; |
| 64 |
} |
| 65 |
|
| 66 |
|
| 67 |
req.n.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg)); |
| 68 |
req.n.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK; |
| 69 |
req.n.nlmsg_type = RTM_GETROUTE; |
| 70 |
req.n.nlmsg_seq = 1; |
| 71 |
|
| 72 |
|
| 73 |
req.r.rtm_family = AF_INET; |
| 74 |
|
| 75 |
|
| 76 |
rta = NLMSG_TAIL(&req.n); |
| 77 |
rta->rta_type = RTA_DST; |
| 78 |
rta->rta_len = RTA_LENGTH(sizeof(*dest)); |
| 79 |
memcpy(RTA_DATA(rta), dest, sizeof(*dest)); |
| 80 |
|
| 81 |
|
| 82 |
req.r.rtm_dst_len = sizeof(*dest) * 8; |
| 83 |
req.n.nlmsg_len = NLMSG_ALIGN(req.n.nlmsg_len) + RTA_ALIGN(rta->rta_len); |
| 84 |
|
| 85 |
rc = send(fd, &req, req.n.nlmsg_len, 0); |
| 86 |
if (rc != req.n.nlmsg_len) { |
| 87 |
perror("short write"); |
| 88 |
close(fd); |
| 89 |
return -2; |
| 90 |
} |
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
rc = recv(fd, &req, sizeof(req), 0); |
| 95 |
if (rc <= 0) { |
| 96 |
perror("short read"); |
| 97 |
close(fd); |
| 98 |
return -3; |
| 99 |
} |
| 100 |
|
| 101 |
if (!NLMSG_OK(&req.n, rc) || req.n.nlmsg_type != RTM_NEWROUTE) { |
| 102 |
close(fd); |
| 103 |
return -4; |
| 104 |
} |
| 105 |
|
| 106 |
r = NLMSG_DATA(&req.n); |
| 107 |
rc -= NLMSG_LENGTH(sizeof(*r)); |
| 108 |
rta = RTM_RTA(r); |
| 109 |
while (RTA_OK(rta, rc)) { |
| 110 |
if (rta->rta_type != RTA_PREFSRC) { |
| 111 |
rta = RTA_NEXT(rta, rc); |
| 112 |
continue; |
| 113 |
} |
| 114 |
|
| 115 |
|
| 116 |
memcpy(loc_source, RTA_DATA(rta), RTA_PAYLOAD(rta)); |
| 117 |
close(fd); |
| 118 |
return 0; |
| 119 |
} |
| 120 |
|
| 121 |
close(fd); |
| 122 |
return -5; |
| 123 |
} |