zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    C语言 常用单词
    导航菜单
    css3中的过渡(transition)
    HTML CSS 常用英语单词
    css基础
    XHTML基础
    MongoDB作为windows服务来安装-2
    MongoDB安装成windows 服务
    .NET平台MongoDB下使用JobStore存储Quartz.Net的Job,Trigger数据
    C# mongodb 类库
  • 原文地址:https://www.cnblogs.com/xiaoshiwang/p/9795817.html
Copyright © 2011-2022 走看看