查看网络信息指令
ifconfig
修改网络 mac 地址,指令
ifconfig 网卡名 hw ether mac地址
例如:
ifconfig eth0 hw ether 08:00:27:00:01:96
1.使用 ioctl 和 SIOCSIFHWADDR 来设置MAC地址,示例代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <net/if_arp.h>
int main(int argc,char *argv[])
{
int sockfd;
struct ifreq ifr;
unsigned char new_mac[6] = {0x08, 0x00, 0xc0, 0xa8, 0xec, 0x97}; // 新的MAC地址
// 创建一个socket用于ioctl调用
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("socket");
exit(EXIT_FAILURE);
}
// 清除ifr结构并设置接口名称
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1); // 设置网络接口名称,比如eth0
// 设置新的MAC地址
ifr.ifr_hwaddr.sa_family = ARPHRD_ETHER;
memcpy(ifr.ifr_hwaddr.sa_data, new_mac, 6);
// 使用ioctl调用设置MAC地址
if (ioctl(sockfd, SIOCSIFHWADDR, &ifr) < 0)
{
perror("ioctl(SIOCSIFHWADDR)");
close(sockfd);
exit(EXIT_FAILURE);
}
// 关闭socket
close(sockfd);
printf("MAC address changed successfully.n");
return 0;
}
测试效果:
2.使用 shell 指令 进行
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char ethIfconfigCmd[128]={0};
char *ip="192.168.1.151";
int a,b,c,d;
int main()
{
int ret;
sscanf (ip,"%d.%d.%d.%d",&a,&b,&c,&d);
printf ("%d.%d.%d.%dn",a,b,c,d);
memset(ethIfconfigCmd,0,sizeof(ethIfconfigCmd));
sprintf(ethIfconfigCmd,"ifconfig eth0 hw ether %02x:%02x:%02x:%02x:%02x:%02x",0x08,0x00,0x27,0x00,0x01,0x96);
ret=system(ethIfconfigCmd);
//printf("ret=%dn",ret);
if (ret != 0)
{
//printf("%d:%sn",errno,strerror(errno));
printf("ret:%d,filename:%s,function:%s,lineNum:%dn",ret,__FILE__,__FUNCTION__,__LINE__);
//return -1;
}
return 0;
}
测试结果如下:
或者
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char ethIfconfigCmd[128]={0};
char *ip="192.168.1.151";
int a,b,c,d;
char str[2][128]={0};
static int eth_mac_write(char *cmd)
{
unsigned char i=0;
FILE *fstream=NULL;
char str[2][128]={0};
if(NULL==(fstream=popen(cmd,"r")))
{
fprintf(stderr,"execute command failed: %s",strerror(perror));
return -1;
}
if(NULL==fgets(str[0], sizeof(str[0]), fstream))
{
}
else
{
printf("%srn",str[0]);
}
if(NULL==fgets(str[1], sizeof(str[1]), fstream))
{
}
else
{
printf("%srn",str[1]);
}
pclose(fstream); //关闭 popen
return 0;
}
int main()
{
int ret;
sscanf (ip,"%d.%d.%d.%d",&a,&b,&c,&d);
printf ("%d.%d.%d.%dn",a,b,c,d);
memset(ethIfconfigCmd,0,sizeof(ethIfconfigCmd));
sprintf(ethIfconfigCmd,"ifconfig eth0 hw ether %02x:%02x:%02x:%02x:%02x:%02x",0x08,0x00,0x27,0x00,0x01,0x98);
ret=eth_mac_write(ethIfconfigCmd);
//printf("ret=%dn",ret);
if (ret != 0)
{
//printf("%d:%sn",errno,strerror(errno));
printf("ret:%d,filename:%s,function:%s,lineNum:%dn",ret,__FILE__,__FUNCTION__,__LINE__);
//return -1;
}
return 0;
}
执行前
执行后
本文发布于:2025-04-07 03:36:00,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/1743968214584829.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |