Linux--网络层IP
在Linux系统中,IP层的相关操作通常通过netlink
套接字进行,这是一种允许进程向内核发送请求和接收内核消息的方式。以下是一个简单的示例,展示如何使用netlink
套接字在用户空间中获取和设置IP地址。
#include <asm/types.h>
#include <sys/socket.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define BUFSIZE 8192
#define MAX_ADDRS 32
struct nlmsghdr *recv_nlmsg(int nl, struct nlmsghdr *h) {
int len;
while ((len = recv(nl, h, sizeof(struct nlmsghdr), 0)) > 0) {
if (len == sizeof(struct nlmsghdr)) {
if ((h->nlmsg_flags & NLM_F_MULTI) == 0) {
return h;
}
} else {
fprintf(stderr, "recv(): %s\n", strerror(errno));
exit(1);
}
}
return NULL;
}
int main() {
struct {
struct nlmsghdr nlmsg;
struct rtgenmsg rtgen;
} req;
struct sockaddr_nl nls;
struct iovec iov;
struct msghdr msg;
struct nlmsghdr *respptr;
char buf[BUFSIZE];
int len;
memset(&req, 0, sizeof(req));
memset(&nls, 0, sizeof(nls));
memset(&iov, 0, sizeof(iov));
memset(&msg, 0, sizeof(msg));
// 创建netlink套接字
int nl = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (nl < 0) {
perror("socket()");
exit(1);
}
// 准备请求
req.nlmsg.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg));
req.nlmsg.nlmsg_type = RTM_GETADDR;
req.nlmsg.nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST;
req.nlmsg.nlmsg_pid = getpid();
req.nlmsg.nlmsg_seq = 123;
// 发送请求
iov.iov_base = (void *)&req;
iov.iov_len = req.nlmsg.nlmsg_len;
msg.msg_name = (void *)&nls;
msg.msg_namelen = sizeof(nls);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
sendmsg(nl, &msg, 0);
// 接收响应
respptr = (struct nlmsghdr *)buf;
while ((respptr = recv_nlmsg(nl, respptr)) != NULL) {
struct ifaddrmsg *ifaddr;
struct rtattr *rta;
int rtl;
if (respptr->nlmsg_type == NLMSG_ERROR) {
fprintf(stderr, "Received NLMSG_ERROR.\n");
break;
}
if (respptr->nlmsg_type != RTM_NEWADDR) {
continue;
}
ifaddr = (struct ifaddrmsg *)NLMSG_DATA(respptr);
printf("Interface index: %d\n", ifaddr->ifindex);
rta = (struct rtattr *)RTM_RTA(ifaddr);
评论已关闭