Encapsulation wraps data in one header per layer. Here you write the headers out as text.
What to build
A program that builds the text of a frame from its parts and reports its size.
Requirements
- Print the frame as
ETH src>dst | IP src>dst | TCP src>dst | message, with MAC addresses, IP addresses and ports. - On the second line print
size N bytes, where N is the message length plus 58 bytes of headers.
Input
Four lines: the source and destination MAC addresses, the source and destination IP addresses, the source and destination ports, and the message.
Output
Two lines: the frame text, then size N bytes.
Constraints
The message has 1 to 200 characters (plain ASCII).
Example
Input:
aa:00:00:00:00:01 aa:00:00:00:00:fe
192.168.1.10 93.184.216.34
51000 80
GET /index.html
Output:
ETH aa:00:00:00:00:01>aa:00:00:00:00:fe | IP 192.168.1.10>93.184.216.34 | TCP 51000>80 | GET /index.html
size 73 bytes
Why it works
Each layer puts its header in front of what the layer above gave it, so the application message ends up innermost and the Ethernet header outermost. The size adds the three fixed header sizes to the message length.
Examples
aa:00:00:00:00:01 aa:00:00:00:00:fe 192.168.1.10 93.184.216.34 51000 80 GET /index.html
ETH aa:00:00:00:00:01>aa:00:00:00:00:fe | IP 192.168.1.10>93.184.216.34 | TCP 51000>80 | GET /index.html size 73 bytes
3c:22:fb:91:0a:7e ff:ff:ff:ff:ff:ff 10.0.0.5 10.0.0.255 68 67 hello
ETH 3c:22:fb:91:0a:7e>ff:ff:ff:ff:ff:ff | IP 10.0.0.5>10.0.0.255 | TCP 68>67 | hello size 63 bytes
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Build the string in the order ETH, IP, TCP, then the message, joined with " | ".
Hint 2
Read the lines with input(); the message is the whole last line and may contain spaces.
Hint 3
The size is the message length plus 20 (TCP) plus 20 (IP) plus 18 (Ethernet).
Solution
Show one correct solution (try it yourself first)
mac_a, mac_b = input().split()
ip_a, ip_b = input().split()
port_a, port_b = input().split()
message = input()
print("ETH " + mac_a + ">" + mac_b + " | IP " + ip_a + ">" + ip_b + " | TCP " + port_a + ">" + port_b + " | " + message)
print("size " + str(len(message) + 58) + " bytes")
▶ Open this solution in the compiler, then press Visualize to watch it run step by step