C/C++ MacOS X 添加/删除路由(内核API调用方式)

用例:

    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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值