I want to delete the IP header in a data packet and add a custom network layer header, how can I do it? For example, a data packet header contains mac, ipv4, tcp, and now I want to delete the ipv4 header and replace it with a custom header sip, and the final output header format is mac, sip, tcp.
Hi @Duang ,
Welcome to the forum.
Removing a header is as easy as:
hdr.ipv4.setInvalid();
If you want to add another header, you just setValid()
that header, that you needed to define beforehand and then add the values to the fields. Make sure you also emit
the new header as depicted below:
header new_l3_header_t {
addr_t dstAddr;
}
struct headers {
ipv4_t ipv4;
new_l3_header_t new_l3_header;
}
//define yourself the parser
control Whatevergress (inout headers hdr,
inout metadata meta,
inout standard_metadata_t standard_metadata){
apply(){
hdr.ipv4.setInvalid();
hdr.new_l3_header.setValid();
hdr.new_l3_header.dstAddr = (addr_t) some_value;
}
}
// Deparse the packet
control YourDeparser(packet_out packet,
in headers hdr) {
apply {
// Other headers
packet.emit(hdr.ipv4);
packet.emit(hdr.new_l3_header);
}
}
You can learn these concepts if you try all the exercises from the P4 tutorial: GitHub - p4lang/tutorials: P4 language tutorials
Cheers,
One minor additional point, but not only must you call setValid() on a header in order to add it, but it must also appear in your deparser code with an emit call. Doing setValid() on a header that is NOT emit’ed in the deparser will NOT cause it to appear in the output packet.
Modified my answer. Thanks @andyfingerhut
Thank you for your help, it worked great for me.
Thanks a lot for your advice and help。