iptables -j MARK --set-xmark 解析

查看man和命令帮助,还有网上搜到的解释不是很清晰,所以验证了一下,并尽量将其解释的通俗易懂。

MARK的作用
MARK标记用于将特定的数据包打上标签,供Iptables配合TC做QOS流量限制或应用策略路由。
这里只说 --set-xmark

格式

--set-xmark value[/mask] 

操作结果:
ctmark = (ctmark AND NOT mask) XOR value

重点(解释)
就是先将 ctmark(原包)中的那些 mask标志出来的位设置为零(mask值为1的位,当然这里是转换为二进制后的位),然后再与给的value做异或运算(1 XOR 1 = 0; 0 XOR 0 = 0, 1 XOR 0 = 1)。注意,这里的设置为零和异或操作都与原来ctmark中的mask没关系。

举例

以下可以通过iptables命令验证,加 log可以显示出MARK值
# 初始 set-xmark  0x1f/0x10 (对应二进制:11111/10000)
 -j MARK --set-xmark 0x1f/0x10
# 之后 set-xmark 0x10/0x8 (对应二进制:10000/1000)
 -j MARK --set-xmark 0x10/0x8

1. 根据上边描述的计算规则,首先将ctmark(11111)中mask(1000)标志出来的位设置为0(即正数第2位,倒数第4位),结果为10111。
2. 再用10111与value(10000)做异或。根据异或规则两个位相同结果为0,不同则结果为1。计算结果为111(2进制),也就是计算后ctmark为0x7(16进制)

再来看一个例子
# 初始 --set-xmark 0x4000/0x4000 (这里就不转2进制了)
# 之后 --set-xmark 0x4000/0x0
先看掩码0x0,等于没有。所以第一步计算完还是0x4000
第二步,0x4000与0x4000异或,两个值所有位都相等。所以异或完的结果是全0,全0就代表没有mark。
所以 --set-xmark 0x4000/0x0这个配置相当于把第一步设置的ctmark  (0x4000/0x4000)清除了。

man文档:
https://ipset.netfilter.org/iptables-extensions.man.html

MARK
This target is used to set the Netfilter mark value associated with the packet. It can, for example, be used in conjunction with routing based on fwmark (needs iproute2). If you plan on doing so, note that the mark needs to be set in the PREROUTING chain of the mangle table to affect routing. The mark field is 32 bits wide.
--set-xmark value[/mask]
	Zeroes out the bits given by mask and XORs value into the packet mark ("nfmark"). If mask is omitted, 0xFFFFFFFF is assumed.
--set-mark value[/mask]
	Zeroes out the bits given by mask and ORs value into the packet mark. If mask is omitted, 0xFFFFFFFF is assumed.

The following mnemonics are available:
--and-mark bits
	Binary AND the nfmark with bits. (Mnemonic for --set-xmark 0/invbits, where invbits is the binary negation of bits.)
--or-mark bits
	Binary OR the nfmark with bits. (Mnemonic for --set-xmark bits/bits.)
--xor-mark bits
	Binary XOR the nfmark with bits. (Mnemonic for --set-xmark bits/0.)

命令帮助

# iptables -j MARK --help
......
MARK target options:
  --set-xmark value[/mask]  Clear bits in mask and XOR value into nfmark
  --set-mark value[/mask]   Clear bits in mask and OR value into nfmark
  --and-mark bits           Binary AND the nfmark with bits
  --or-mark bits            Binary OR the nfmark with bits
  --xor-mask bits           Binary XOR the nfmark with bits
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值