用例:
SetRouteToMacOSX(RTM_ADD, inet_addr("192.168.0.24"), UINT32_MAX, inet_addr("192.168.0.1"));
SetRouteToMacOSX(RTM_DELETE, inet_addr("192.168.0.24"), UINT32_MAX, inet_addr("192.168.0.1"));
实现:
#include <net/route.h>
bool SetRouteToMacOSX(int action, uint32_t dst, uint32_t mask, uint32_t nexthop) noexcept {
#pragma pack(push, 1)
struct {
struct rt_msghdr msghdr;
struct sockaddr_in addr[3];
} packet{};
#pragma pack(pop)
packet.msghdr.rtm_msglen = sizeof(packet);
packet.msghdr.rtm_version = RTM_VERSION;
packet.msghdr.rtm_type = action;
packet.msghdr.rtm_addrs = RTA_DST | RTA_GATEWAY | RTA_NETMASK;
packet.msghdr.rtm_flags = RTF_UP | RTA_GATEWAY;
for (int i = 0; i < arraysizeof(packet.addr); i++) {
auto& r = packet.addr[i];
r.sin_len = sizeof(*packet.addr);
r.sin_family = AF_INET;
}
packet.addr[0].sin_addr.s_addr = dst;
packet.addr[1].sin_addr.s_addr = nexthop;
packet.addr[2].sin_addr.s_addr = mask;
int route_fd = socket(AF_ROUTE, SOCK_RAW, 0);
if (route_fd < 0) {
return false;
}
int message_flags = 0;
#if defined(MSG_NOSIGNAL)
message_flags = MSG_NOSIGNAL;
#endif
int err = send(route_fd, &packet, sizeof(packet), message_flags);
close(route_fd);
return err != -1;
}