c/c++ 網絡編程 UDP 改變網關和網卡名字

網絡編程 UDP 改變網關和網卡名字

在程序裏動態改變網關和網卡名字

<font color="green">

1,改變網卡名字

</font>

#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, "lo", IFNAMSIZ - 1);
  strncpy(ifr.ifr_newname, "newloname", IFNAMSIZ - 1);
  if(ioctl(fd, SIOCSIFNAME, &ifr) != 0){
    perror("ioctl");
    return 1;
  }
  close(fd);
  return 0;
}

github源代碼c++

<font color="green">

2,改變網關

</font>

#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>
#include <arpa/inet.h>

int main(){
  int fd;
  ifreq ifr;
  sockaddr_in *s_in;

  fd = socket(AF_INET, SOCK_DGRAM, 0);

  s_in = (sockaddr_in*)&ifr.ifr_addr;

  s_in->sin_family = AF_INET;
  inet_pton(AF_INET, "255.0.0.0", &s_in->sin_addr);

  strncpy(ifr.ifr_name, "enp0s3", IFNAMSIZ - 1);

  if(ioctl(fd, SIOCSIFNETMASK, &ifr) != 0){
    perror("ioctl");
    return 1;
  }
  close(fd);
  return 0;
}

github源代碼git

<font color="green">github

c/c++ 學習互助QQ羣:877684253

本人微信:xiaoshitou5854

</font>編程

相關文章
相關標籤/搜索