使用Python模拟TCP/IP协议栈

1. 代码如下

import random
 
class ApplicationLayer:
    def send_data(self, data):
        print(f"Application Layer: Sending data: {data}")
        return data
 
    def receive_data(self, data):
        print(f"Application Layer: Received data: {data}")
 
class TransportLayer:
    def send_segment(self, data):
        print("Transport Layer: Creating TCP segment")
        random.seed(100)
        source_port = random.randint(1024, 65535)
        dest_port = 80  # Assuming HTTP
        segment = f"TCP|{source_port}|{dest_port}|{data}"
        return segment
 
    def receive_segment(self, segment):
        print("Transport Layer: Receiving TCP segment")
        parts = segment.split("|")
        if len(parts) >= 4 and parts[0] == "TCP":
            data = "|".join(parts[3:])
            print(f"From port {parts[1]} to port {parts[2]}")
            return data
        else:
            print("Invalid TCP segment")
            return None
 
class InternetLayer:
    def send_packet(self, segment):
        print("Internet Layer: Creating IP packet")
        source_ip = "192.168.1.1"
        dest_ip = "10.0.0.1"
        packet = f"IP|{source_ip}|{dest_ip}|{segment}"
        return packet
 
    def receive_packet(self, packet):
        print("Internet Layer: Receiving IP packet")
        parts = packet.split("|")
        if len(parts) >= 4 and parts[0] == "IP":
            segment = "|".join(parts[3:])
            print(f"From IP {parts[1]} to IP {parts[2]}")
            return segment
        else:
            print("Invalid IP packet")
            return None
 
class LinkLayer:
    def send_frame(self, packet):
        print("Link Layer: Creating Ethernet frame")
        mac_source = "00:1A:2B:3C:4D:5E"
        mac_dest = "A1:B2:C3:D4:E5:F6"
        frame = f"ETH|{mac_source}|{mac_dest}|{packet}"
        return frame
 
    def receive_frame(self, frame):
        print("Link Layer: Receiving Ethernet frame")
        parts = frame.split("|")
        if len(parts) >= 4 and parts[0] == "ETH":
            packet = "|".join(parts[3:])
            print(f"From MAC {parts[1]} to MAC {parts[2]}")
            return packet
        else:
            print("Invalid Ethernet frame")
            return None
 
class TCPIPStack:
    def __init__(self):
        self.application = ApplicationLayer()
        self.transport = TransportLayer()
        self.internet = InternetLayer()
        self.link = LinkLayer()
 
    def send_message(self, message):
        print("\n--- Sending Message ---")
        # 应用层:将message封装为data
        data = self.application.send_data(message)
        
        # 传输层:将data封装为segment,添加源端口和目标端口等信息
        segment = self.transport.send_segment(data)
        
        # 网络层:将segment封装为包packet,添加源IP和目标IP等信息
        packet = self.internet.send_packet(segment)
        
        # 数据链路层:将packet封装为帧(frame),添加源和目标MAC地址等信息
        frame = self.link.send_frame(packet)
        
        print(f"Final Frame: {frame}")
        return frame
 
    def receive_message(self, frame):
        print("\n--- Receiving Message ---")
        packet = self.link.receive_frame(frame)
        if packet:
            segment = self.internet.receive_packet(packet)
            if segment:
                data = self.transport.receive_segment(segment)
                if data:
                    self.application.receive_data(data)
 
 
def main():
	stack = TCPIPStack()
	sent_frame = stack.send_message("Hello, World!")
	stack.receive_message(sent_frame)
	
	
if __name__ == "__main__":
	main()
	

2. 运行结果

3. TCP/IP协议栈中数据封装的过程:数据的四种形态

posted @ 2024-09-04 19:16  Guanjie255  阅读(27)  评论(0编辑  收藏  举报