我需要创建一条消息并通过unix套接字发送。
我有一个定义如下的套接字:socket(AF_UNIX, SOCK_RAW, 0)
我想发送的消息/数据包的头结构如下:
struct map_msghdr {
uint8_t map_msglen; /* to skip over non-understood messages */
uint8_t map_version; /* future binary compatibility */
uint16_t map_type; /* message type */
uint32_t map_flags; /* flags, incl. kern & message, e.g. DONE */
uint16_t map_addrs; /* bitmask identifying sockaddrs in msg */
uint16_t map_versioning;/* Mapping Version Number */
int map_rloc_count;/* Number of rlocs appended to the msg */
pid_t map_pid; /* identify sender */
int map_seq; /* for sender to identify action */
int map_errno; /* why failed */
};
我需要构建一个包含map_msghdr{}
结构后跟socket address structure
的缓冲区。套接字地址结构将具有IP地址。我该怎么做呢?你能告诉我一个例子吗?谢谢。
答案 0 :(得分:1)
分配(静态或动态)sizeof(struct map_msghdr) + sizeof(sockaddr_storage)
个字节。将map_msghdr
复制到分配的内存的开头,并将套接字地址结构复制到头结构之后的缓冲区(即buffer + sizeof(map_msghdr)
)。发送缓冲区。
简单的伪代码:
struct map_msghdr hdr;
struct sockaddr_storage addr;
fill_in_header(&hdr); // You need to write this
fill_in_sockaddr(&addr); // You need to write this
// Create a buffer to send the header and address
int8_t buffer[sizeof hdr + sizeof addr] = { 0 };
memcpy(buffer, &hdr, sizeof hdr); // Copy header to beginning of buffer
memcpy(buffer + sizeof(hdr), &addr, sizeof addr); // Copy address after header
write(your_socket, buffer, sizeof buffer); // Write buffer to socket