网络编程 UDP up/down 网卡
在程序里动态改变网卡的状态。注意:程序运行需要root权限。
程序运行的方法:
sudo ./a.out
1,关闭网卡
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
int main(){
int fd;
ifreq ifr;
fd = socket(AF_INET, SOCK_DGRAM, 0);
strncpy(ifr.ifr_name, \"enp0s3\", IFNAMSIZ - 1);
//get current status
if(ioctl(fd, SIOCGIFFLAGS, &ifr) != 0){
perror(\"ioctl\");
return 1;
}
//let net work down
ifr.ifr_flags &= ~IFF_UP;
//change status
if(ioctl(fd, SIOCSIFFLAGS, &ifr) != 0){
perror(\"ioctl\");
return 1;
}
close(fd);
return 0;
}
2,打开网卡
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
int main(){
int fd;
ifreq ifr;
fd = socket(AF_INET, SOCK_DGRAM, 0);
strncpy(ifr.ifr_name, \"enp0s3\", IFNAMSIZ - 1);
//get current status
if(ioctl(fd, SIOCGIFFLAGS, &ifr) != 0){
perror(\"ioctl\");
return 1;
}
//let net work up
ifr.ifr_flags |= IFF_UP | IFF_RUNNING;
//change status
if(ioctl(fd, SIOCSIFFLAGS, &ifr) != 0){
perror(\"ioctl\");
return 1;
}
close(fd);
return 0;
}
在命令行里也可以down和up网卡(需要root权限)
down网卡:
sudo ifconfig enp0s3 down
up网卡:
sudo ifconfig enp0s3 up
继续阅读与本文标签相同的文章
上一篇 :
为什么要用深度学习?
下一篇 :
5分钟搞懂什么是深度学习
-
基础c4d教程:简单的木质吊灯建模,小白也能学会
2026-05-18栏目: 教程
-
大族激光:智能装备LION系列光纤激光切割机发布仪式在湘隆重召开
2026-05-18栏目: 教程
-
实拍上汽首个“无人”仓库,本月正式运行
2026-05-18栏目: 教程
-
自动驾驶光车以外的硬件就7万 滴滴想让你不买车就能先坐上
2026-05-18栏目: 教程
-
滴滴迎来大整顿!1000万罚单认清现实,8万司机被开除
2026-05-18栏目: 教程
