网络编程 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]);
}
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;
}
}
c/c++ 学习互助QQ群:877684253
本人微信:xiaoshitou5854
原文地址:https://www.cnblogs.com/xiaoshiwang/p/9795791.html
时间: 2024-10-13 01:04:22