当前位置: 移动技术网 > IT编程>开发语言>C/C++ > c/c++ 网络编程 UDP up/down 网卡

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

2018年10月16日  | 移动技术网IT编程  | 我要评论

科学家的故事手抄报,彩虹心石首饰盒,孟真图片

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

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

本人微信:xiaoshitou5854

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网