Cut a message into segments

TCP cuts a stream of bytes into segments and numbers each one by its first byte.

What to build

A program that lists the segments of a message and the ACK each one gets.

Requirements

  • Cut the message into segments of at most MSS bytes, the last one possibly shorter.
  • For each segment print seq S len L ack A, where S is the number of its first byte, L its length and A the number the receiver sends back (S + L).
  • After the segments print segments K.

Input

One line with three numbers: the sequence number of the first byte, the message length in bytes, and the MSS.

Output

One line per segment, then segments K.

Constraints

1 ≤ length ≤ 100000; 1 ≤ MSS ≤ 1460; at most 100 segments.

Example

Input:

1001 250 100

Output:

seq 1001 len 100 ack 1101
seq 1101 len 100 ack 1201
seq 1201 len 50 ack 1251
segments 3

Why it works

The receiver acknowledges the next byte it expects, which is the end of the segment it just received. Each segment starts where the one before ended, so the byte numbers form one unbroken line.

Examples

Example 1 · Input
1001 250 100
Expected output
seq 1001 len 100 ack 1101
seq 1101 len 100 ack 1201
seq 1201 len 50 ack 1251
segments 3
Example 2 · Input
1 1460 1460
Expected output
seq 1 len 1460 ack 1461
segments 1

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

The first segment starts at the given sequence number; each next one starts where the last ended.

Hint 2

Every segment holds at most MSS bytes; the last one holds what is left. Use min(mss, left).

Hint 3

The ACK for a segment is its sequence number plus its length.

Solution

Show one correct solution (try it yourself first)
start, length, mss = map(int, input().split())
seq = start
left = length
count = 0
while left > 0:
    size = min(mss, left)
    print("seq", seq, "len", size, "ack", seq + size)
    seq += size
    left -= size
    count += 1
print("segments", count)

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: UDP and TCP: ports and connections →