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

  • 相关阅读:
    Java多线程 ReadWriteLock、StampedLock用法
    Java多线程基础
    Java中创建多线程
    Java中多线程同步
    Java多线程 synchronized与ReentrantLock用法
    Linux6配置bond链路聚合
    Bash Shell命令流程
    location uri 添加 / 和不添加 / 的区别?
    Nginx负载均衡健康检查nginx_upstream_check_module
    Zabbix4.0源码安装基于LNMP
  • 原文地址:https://www.cnblogs.com/xiaoshiwang/p/9795817.html
Copyright © 2011-2022 走看看