linux c语言修改ens33 ip指令
时间: 2023-07-27 22:16:01 浏览: 143
linux修改ip
要修改Linux系统中ens33网卡的IP地址,可以使用以下C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[]) {
int sockfd;
struct ifreq ifr;
struct sockaddr_in *sin;
char *iface = "ens33";
char *ipaddr = "192.168.0.100";
char *netmask = "255.255.255.0";
char *broadcast = "192.168.0.255";
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("socket");
exit(1);
}
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, iface, IFNAMSIZ);
sin = (struct sockaddr_in *)&ifr.ifr_addr;
sin->sin_family = AF_INET;
sin->sin_addr.s_addr = inet_addr(ipaddr);
if (ioctl(sockfd, SIOCSIFADDR, &ifr) < 0) {
perror("ioctl SIOCSIFADDR");
exit(1);
}
sin = (struct sockaddr_in *)&ifr.ifr_netmask;
sin->sin_family = AF_INET;
sin->sin_addr.s_addr = inet_addr(netmask);
if (ioctl(sockfd, SIOCSIFNETMASK, &ifr) < 0) {
perror("ioctl SIOCSIFNETMASK");
exit(1);
}
sin = (struct sockaddr_in *)&ifr.ifr_broadaddr;
sin->sin_family = AF_INET;
sin->sin_addr.s_addr = inet_addr(broadcast);
if (ioctl(sockfd, SIOCSIFBRDADDR, &ifr) < 0) {
perror("ioctl SIOCSIFBRDADDR");
exit(1);
}
close(sockfd);
printf("IP address of %s has been set to %s\n", iface, ipaddr);
return 0;
}
```
这段代码使用了系统调用 `ioctl()` 来设置网卡的IP地址、子网掩码和广播地址。需要注意的是,你需要以root权限运行这个程序,否则可能会无法执行 `ioctl()` 调用。
阅读全文