当我连接到网络时,我可以struct rt_msghdr*
向内核发送并接收相应的路由。但是,当我断开网络连接并尝试发送相同的路由消息标头时,套接字失败,并send()
显示errno = ESRCH (3) No such process
.
通用代码:(在 MacOS 上测试)
int sd = create_socket(AF_ROUTE, IPPROTO_RAW, AF_UNSPEC);
memset(&buffer[0], 0, buffer.size());
struct rt_msghdr* rmh = (struct rt_msghdr*)(&buffer[0]);
rmh->rtm_msglen = sizeof(struct rt_msghdr) + sizeof(struct sockaddr_in);
rmh->rtm_version = RTM_VERSION;
rmh->rtm_type = RTM_GET;
rmh->rtm_addrs = RTA_DST;
rmh->rtm_pid = getpid();
rmh->rtm_seq = 1;
struct sockaddr_in* sa_in = (struct sockaddr_in*)(rmh + 1);
sa_in->sin_len = sizeof(struct sockaddr_in);
sa_in->sin_family = AF_INET;
int status;
if ((status = send(sd, rmh, rmh->rtm_msglen, 0) < 0) {
// process errno
// * issue happens here when not connected to a network
}
// receive kernel response(s)
// process responses
close(sd);
我确认进程 ID (pid) 在标头中设置正确。netstat -nr
未连接到网络时返回默认路由不会出现问题。我无法理解为什么此代码依赖于网络连接。