This repository has been archived on 2025-09-14. You can view files and clone it, but cannot push or open issues or pull requests.
Files
stellar-stellar/src/packet/udp_utils.h
2024-06-19 15:06:14 +08:00

91 lines
2.5 KiB
C

#pragma once
#ifdef __cplusplus
extern "C"
{
#endif
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#define __FAVOR_BSD 1
#include <netinet/udp.h>
/*
* User Datagram Header Format
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Source Port | Destination Port |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Length | Checksum |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Data |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
/******************************************************************************
* get
******************************************************************************/
static inline uint16_t udp_hdr_get_src_port(const struct udphdr *hdr)
{
return ntohs(hdr->uh_sport);
}
static inline uint16_t udp_hdr_get_dst_port(const struct udphdr *hdr)
{
return ntohs(hdr->uh_dport);
}
static inline uint16_t udp_hdr_get_total_len(const struct udphdr *hdr)
{
return ntohs(hdr->uh_ulen);
}
static inline uint16_t udp_hdr_get_checksum(const struct udphdr *hdr)
{
return ntohs(hdr->uh_sum);
}
/******************************************************************************
* set
******************************************************************************/
static inline void udp_hdr_set_src_port(struct udphdr *hdr, uint16_t port)
{
hdr->uh_sport = htons(port);
}
static inline void udp_hdr_set_dst_port(struct udphdr *hdr, uint16_t port)
{
hdr->uh_dport = htons(port);
}
static inline void udp_hdr_set_total_len(struct udphdr *hdr, uint16_t len)
{
hdr->uh_ulen = htons(len);
}
static inline void udp_hdr_set_checksum(struct udphdr *hdr, uint16_t sum)
{
hdr->uh_sum = htons(sum);
}
/******************************************************************************
* print
******************************************************************************/
static inline int udp_hdr_to_str(const struct udphdr *hdr, char *buf, size_t size)
{
memset(buf, 0, size);
return snprintf(buf, size, "UDP: src_port=%u dst_port=%u total_len=%u checksum=0x%x",
udp_hdr_get_src_port(hdr), udp_hdr_get_dst_port(hdr),
udp_hdr_get_total_len(hdr), udp_hdr_get_checksum(hdr));
}
#ifdef __cplusplus
}
#endif