mac 与 IP 地址字符串 转 整型 或 数组

背景
项目中,需将设备IP及Mac地址 填充到UDP数据包中,原始数据为字符串。
实现

测试代码

#include <iostream>
#include <fstream>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>

using namespace std;
#define IP "192.168.1.10"
#define MAC "00:11:22:33:44:55"

int main() {

	
u_char ip[4];
memset(ip,0,4);		
u_char mac[6];
memset(mac,0,6);

//将IP地址字符串转为uint32,再按大小端填充对应字节
uint32_t my_ip = inet_addr(IP); //调用inet_addr函数,返回u32整型数据
ip[3] = my_ip & 0xff;              
ip[2] = (my_ip >> 8) & 0xff;	
ip[1] = (my_ip >> 16) & 0xff;
ip[0] = (my_ip >> 24) & 0xff;
	
//将mac地址从字符串读取格式化输入
sscanf(MAC, "%x:%x:%x:%x:%x:%x", &mac[0],&mac[1],&mac[2],&mac[3],&mac[4],&mac[5]);
return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值