如何为IP/CIDR创建LPM trie记录的切片?

huangapple go评论90阅读模式
英文:

How to create slice of LPM trie record for IPs/CIDRs

问题

我正在尝试使用来自https://github.com/cilium/ebpf/blob/master/map.go#L952-L1038的BatchUpdateBatchDelete API。据我理解,我需要创建一个IP/CIRD的LPM trie切片,例如:如果我有denyIPs := []string{"10.11.15.114/32", "127.0.0.1/32"},我需要将denyIPs转换为LPM trie切片。我在谷歌上搜索了一下,但没有找到可以学习的示例(我对Golang还是新手)。我的意图是用批量更新和删除替换我的https://github.com/vincentmli/xdp-firewall/blob/main/main.go#L78-L102。

英文:

I am trying to use the BatchUpdate and BatchDelete API from https://github.com/cilium/ebpf/blob/master/map.go#L952-L1038. from my understanding, I need to create slice of LPM trie of IPs/CIRDs, for example: if I have denyIPs := []string{"10.11.15.114/32", "127.0.0.1/32"}, I need to convert the denyIPs to slice of LPM trie, I google searched and unable to find example I can learn (still newbie to Golang). my intention is to replace my
https://github.com/vincentmli/xdp-firewall/blob/main/main.go#L78-L102 with batch update and delete.

答案1

得分: 1

您正在提供未解析格式的Go字符串。LPM trie的键必须始终遵循以下格式:

struct bpf_lpm_trie_key {
	__u32	prefixlen;	/* 对于AF_INET最多为32,对于AF_INET6最多为128 */
	__u8	data[0];	/* 任意大小 */
};

因此,前4个字节必须包含您的前缀作为32位无符号整数。然后是您的IPv4地址的4个字节。因此,您需要对字符串进行一些解析。

eBPF库可以对结构进行编组,因此最简单的方法是为您的键定义一个结构:

type MapKey struct {
  Prefix  uint32
  Address [4]byte
}

然后将这些地图键的切片[]MapKey提供给批处理函数。

英文:

You are supplying Go strings in unparsed format. The key of an LPM trie must always follow

struct bpf_lpm_trie_key {
	__u32	prefixlen;	/* up to 32 for AF_INET, 128 for AF_INET6 */
	__u8	data[0];	/* Arbitrary size */
};

So the first 4 bytes must contain your prefix as a 32-bit unsigned integer. Followed by in your case the 4 bytes of your IPv4 address. So you will have to do some parsing of your strings.

The eBPF library can marshal structs, so the easiest way to go is to define a struct for your key:

type MapKey struct {
  Prefix  uint32
  Address [4]byte
}

Then provide a slice of these map keys []MapKey to the batch functions.

huangapple
  • 本文由 发表于 2023年3月9日 01:04:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75676075.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定