背景
项目中,需将设备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;
}