Tuesday, December 9, 2025

port generation

 Question:

You have a SystemVerilog class that represents a network packet, with the following properties:

  • src_port: a 16-bit integer representing the source port number
  • dst_port: a 16-bit integer representing the destination port number
  • packet_size: a 32-bit integer representing the size of the packet in bytes

You want to write a constraint to ensure that:

  • The src_port and dst_port fields are within the range of 0 to 65535 (inclusive)
  • The src_port and dst_port fields cannot be equal to each other (i.e., they must be distinct)
  • The packet_size field must be within the range of 1 to 1500 (inclusive)
  • At least one of the src_port or dst_port fields must be an even number
  • If the packet_size is greater than 1000, then the src_port field must be greater than 1024

Write a SystemVerilog constraint that satisfies these conditions.

======================================================

/// src dst 

  

  class packet;

    rand int src_port;

    rand int dst_port;

    rand int packet_size;


    constraint src_dst_port_c {

        src_port inside {[0:65535]}; // 0 to 65535 inclusive

        dst_port inside {[0:65535]}; // 0 to 65535 inclusive

        src_port != dst_port; // src_port and dst_port must be distinct

    }


    constraint packet_size_c {

        packet_size inside {[1:1500]}; // 1 to 1500 inclusive

    }


    constraint even_port_c {

        (src_port % 2 == 0) || (dst_port % 2 == 0); // at least one of src_port or dst_port must be even

    }


    constraint large_packet_c {

        (packet_size > 1000) -> (src_port > 1024); // if packet_size > 1000, then src_port > 1024

    }


endclass



// Testbench module

module tb;

    // Create a packet instance

    packet p;


    initial begin

        // Initialize the random seed

        //$random_seed = 1;


        // Create a new packet instance

        p = new();


        // Repeat the randomization and printing process

        repeat (10) begin

            // Randomize the packet fields

            p.randomize();


          $display("src  = %d , dst = %d , pkt size = %d", p.src_port , p.dst_port , p.packet_size );


            // Wait for 1ns before generating the next packet

            #1ns;

        end


        // Wait for 1ns before finishing the simulation

        #1ns;


        $finish;

    end

endmodule


No comments:

Post a Comment