I am writing a code to communicate via the SOCK_RAW
sockets with a process on another computer.
I know the IP address of the other machine.
I am aware that filling up the sockaddr_ll.sll_addr
values one byte at a time will solve the problem ie something like
socket_address.sll_addr[0] = 0x00;
socket_address.sll_addr[1] = 0x04;
socket_address.sll_addr[2] = 0x75;
socket_address.sll_addr[3] = 0xC8;
socket_address.sll_addr[4] = 0x28;
socket_address.sll_addr[5] = 0xE5;
But I don't know how to do the same thing when I have character array of 6 bytes having the hexadecimal address of the other machine.
I am able to print the hex address in ':' format using
printf("%.2x",*ptr++ & 0xff);
where ptr
is an array to the character array.
But how to use these values to fill the sll_addr
bytes?
You could use the sscanf()
function to do this, like so:
#include <stdio.h>
#include <linux/if_packet.h>
const char sMac[] = "01:02:03:04:05:ff";
int main()
{
struct sockaddr_ll sa = {0};
sscanf(sMac, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",
&sa.sll_addr[0],
&sa.sll_addr[1],
&sa.sll_addr[2],
&sa.sll_addr[3],
&sa.sll_addr[4],
&sa.sll_addr[5]
);
return 0;
}
The magic is the format string passed to sscanf()
.
It tells the scanner where to find what in which range.
x
tells it to expect hexadecimal notation hh
specifies 8bit values.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.