用c语言写一个将linux的网卡shutdown的程序
时间: 2023-12-05 07:04:19 浏览: 30
由于涉及到系统调用和权限问题,需要使用root权限运行程序。以下是一个简单的示例程序:
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <interface>\n", argv[0]);
exit(1);
}
char *iface = argv[1];
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("socket");
exit(1);
}
struct ifreq ifr;
strncpy(ifr.ifr_name, iface, IFNAMSIZ);
if (ioctl(sockfd, SIOCGIFFLAGS, &ifr) < 0) {
perror("ioctl");
close(sockfd);
exit(1);
}
ifr.ifr_flags &= ~IFF_UP;
if (ioctl(sockfd, SIOCSIFFLAGS, &ifr) < 0) {
perror("ioctl");
close(sockfd);
exit(1);
}
printf("Interface %s has been shut down.\n", iface);
close(sockfd);
return 0;
}
```
运行程序时需要给定一个参数,即要shutdown的网卡名称。程序会使用socket和ioctl系统调用来获取和修改网卡的状态,将其标记为down。程序执行成功后会输出一条消息。