Ex 3
Ex 3
: 3 Date: / / 2025
Simulation of PING and TRACEROUTE
commands using Twisted Python
Ping Simulation:
class PingServer(protocol.Protocol):
def dataReceived(self, data):
message = data.decode().strip()
print(f"Received: {message}")
if message.lower() == "ping":
self.transport.write("pong\n".encode())
else:
self.transport.write("Unknown command\n".encode())
class PingFactory(protocol.Factory):
def buildProtocol(self, addr):
print(f"New connection from {addr}") # Debug message
return PingServer()
class PingClient(protocol.Protocol):
""" Client that sends a 'ping' message and waits for a response. """
def connectionMade(self):
print("Connected to server. Sending 'ping'...")
self.transport.write("ping\n".encode()) # Send "ping" message
class PingClientFactory(protocol.ClientFactory):
""" Factory for creating client connections. """
Output:
Traceroute simulation:
class TracerouteServer(DatagramProtocol):
def datagramReceived(self, data, addr):
"""Handle incoming UDP packets and respond with hop information."""
print(f"Received packet from {addr[0]}:{addr[1]} - Data:
{data.decode().strip()}") # Debug message
try:
ttl = int(data.decode().strip())
except ValueError:
return
reactor.listenUDP(33434, TracerouteServer())
print("Traceroute server started on port 33434...") # Debug message
reactor.run()
class TracerouteServer(DatagramProtocol):
def datagramReceived(self, data, addr):
"""Handle incoming UDP packets and respond with hop information."""
print(f"Received packet from {addr[0]}:{addr[1]} - Data:
{data.decode().strip()}") # Debug message
try:
ttl = int(data.decode().strip())
except ValueError:
return
reactor.listenUDP(33434, TracerouteServer())
print("Traceroute server started on port 33434...") # Debug message
reactor.run()
Output:
RESULT:
Thus the ping and traceroute commands are simulated and implemented in python
using twisted and the outputs are demonstrated.