1. 程式人生 > >c/c++ 網絡編程 UDP 改變網卡的硬件地址

c/c++ 網絡編程 UDP 改變網卡的硬件地址

socket gif http ram mil net sign strncpy hang

網絡編程 UDP 改變網卡的硬件地址

在程序裏動態改變網卡的硬件地址

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);
  if(ioctl(fd, SIOCGIFHWADDR, &ifr) != 0){
    perror("ioctl");
    return 1;
  }
  close(fd);

  printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n",
     (unsigned char)ifr.ifr_hwaddr.sa_data[0],
     (unsigned char)ifr.ifr_hwaddr.sa_data[1],
     (unsigned char)ifr.ifr_hwaddr.sa_data[2],
     (unsigned char)ifr.ifr_hwaddr.sa_data[3],
     (unsigned char)ifr.ifr_hwaddr.sa_data[4],
     (unsigned char)ifr.ifr_hwaddr.sa_data[5]);
}

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>
#include <net/if_arp.h>

int main(){
  int fd;
  ifreq ifr;

  fd = socket(AF_INET, SOCK_DGRAM, 0);

  ifr.ifr_hwaddr.sa_family = ARPHRD_ETHER;

  ifr.ifr_hwaddr.sa_data[0] = 0xAA;
  ifr.ifr_hwaddr.sa_data[1] = 0xBB;
  ifr.ifr_hwaddr.sa_data[2] = 0xCC;
  ifr.ifr_hwaddr.sa_data[3] = 0xDD;
  ifr.ifr_hwaddr.sa_data[4] = 0xEE;
  ifr.ifr_hwaddr.sa_data[5] = 0xFF;
  
  strncpy(ifr.ifr_name, "enp0s3", IFNAMSIZ - 1);
  if(ioctl(fd, SIOCSIFHWADDR, &ifr) != 0){
    perror("ioctl");
    return 1;
  }
}

github源代碼

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

技術分享圖片

本人微信:xiaoshitou5854

c/c++ 網絡編程 UDP 改變網卡的硬件地址