c/c++ 网络编程 UDP up/down 网卡

网络编程 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;
}

github源代码

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;

}

github源代码

在命令行里也可以down和up网卡(需要root权限)

down网卡:

sudo ifconfig enp0s3 down

up网卡:

sudo ifconfig enp0s3 up

c/c++ 学习互助QQ群:877684253

本人微信:xiaoshitou5854

原文地址:https://www.cnblogs.com/xiaoshiwang/p/9795817.html