How to capture loop back traffic in Python, with Wireshark i am able to observe the communication as below:
I want to be the "Man In the middle" in this scenario. As i am trying to make the simulator of a Trace32 debugger in my system.
Edit 10-Aug-2020:
I have tried below code, and receiving error, it seems we can not reuse the same port:
OSError: [WinError 10048] Only one usage of each socket address
(protocol/network address/port) is normally permitted
import socket
UDP_IP = "127.0.0.1"
DEBUG_PORT = 20000
MASTERPORT = 53180
MESSAGE = b"TRACE32 C"
mastersock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
debugsock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
debugsock.bind((UDP_IP, DEBUG_PORT))
while True:
data, addr = debugsock.recvfrom(1024) # buffer size is 1024 bytes
print("Listen on Debugger port: %s" % data)
if (data):
print ("Send back response to Master")
mastersock.sendto(MESSAGE, (UDP_IP, MASTERPORT))
Related
I want to create a small TCP server that takes incoming TCP connections from a device that is hooked up via Ethernet to my computer.
The physical port for that has the IP 192.168.1.100 statically assigned to it.
The scripts I use as a client and server are listed at the bottom.
The setup works if I want to send messages between the python scripts. However, I am unable to receive anything from the external device (screenshot from Wireshark capture below). From what I have read I can define an interface to listen to by defining its IP. So I defined the IP of the interface as the host variable. However, I do not receive anything in my script but the messages sent by the other script. I had a similar situation already here on stackoverflow. I thought that defining the correct IP as the host would resolve this issue but it did not.
I am also having a hard time capturing the traffic between the two scripts with Wireshark at all. They did not show up anywhere.
I need to pick up these connections on the eth0 interface with the static IP 192.168.1.100:
tcp_server.py
import socket
# create a socket object
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
# host = socket.gethostname()
host = "192.168.1.100"
port = 9002
# bind to the port
serverSocket.bind((host, port))
# queue up to 5 requests
serverSocket.listen(5)
while True:
# establish a connection
clientSocket, addr = serverSocket.accept()
print("Got a connection from %s" % str(addr))
msg = 'Thank you for connecting' + "\r\n"
clientSocket.send(msg.encode('ascii'))
clientSocket.close()
and this as a client:
tcp_client.py
import socket
# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
# host = socket.gethostname()
host = "192.168.1.100"
port = 9002
# connection to hostname on the port.
s.connect((host, port))
# Receive no more than 1024 bytes
msg = s.recv(1024)
s.close()
print(msg.decode('ascii'))
Ok im going to try an explain what is going on here... I have a network of multiple same type devices. I have a program that runs on any pc on the network that discovers these individual devices and categorizes them by ip, name, mac, etc.. This program allows for configuration of each device. The devices broadcast a udp packet to "255.255.255.255" with the information for discovery. I can run wireshark and intercept the packets broadcasted from the devices. I have a python program that will broadcast udp packets with data of my choosing.. Now.. This stems from me learning python and my project oriented approach.. I learn better this way :). Ok that being said.. My idea is to broadcast the exact udp packet that another device broadcasts, which in turn should land me on the discovery software as a particular network device.. By following udp stream in wireshark i can copy the data and enter it in my python program and broadcast it on the network. I can broadcast to any destination ip and see it in wireshark but when i try and send it to 255.255.255.255 it never shows up. Now i understand that routers will not forward 255x4 broadcasts pass the local network. When i run the discovery program i can see all the devices broacasting their packets to 255x4 but not the packet originating from my pc. Any ideas would be greatly appreciated.
Python Code:
import udp
import socket #for sockets
import sys #for exit
# create dgram udp socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
except socket.error:
print 'Failed to create socket'
sys.exit()
host = '255.255.255.255';
port = 55558;
while(1) :
msg = '''...z..
hrQT.b.......hrQT.b
.....w...NanoStation M2...N2N
..Test......"XM.ar7240.v5.6.2.27929.150716.1201........NanoStation M2'''
try :
#Set the whole string
s.sendto(msg, (host, port))
# receive data from client (data, addr)
d = s.recvfrom(1024)
reply = d[0]
addr = d[1]
print 'Server reply : ' + reply
except socket.error, msg:
print 'Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
To receive UDP packets, you need to bind the socket to the IP address and UDP port that you want to receive packets on.
1 import socket
2
3 UDP_IP = "127.0.0.1"
4 UDP_PORT = 5005
5
6 sock = socket.socket(socket.AF_INET, # Internet
7 socket.SOCK_DGRAM) # UDP
8 sock.bind((UDP_IP, UDP_PORT))
9
10 while True:
11 data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
12 print "received message:", data
I would recommend using different UDP sockets for sending and receiving packets.
I'm trying to take incoming data from one port and stream it to a port on another computer. Here is what I have so far:
import socket
port = 8787
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("", port))
print ("waiting on port:", port)
while 1:
data, addr = s.recvfrom(1024)
print (data)
`
So I can stream the data in from the port using the script above no problem. What I need to do is now take that data stream and forward it to a port on another computer. I came across this:
#!/usr/bin/python
from socket import *
bufsize = 1024 # Modify to suit your needs
targetHost = "192.1.1.2"
listenPort = 8788
def forward(data, port):
print "Forwarding: '%s' from port %s" % (data, port)
sock = socket(AF_INET, SOCK_DGRAM)
sock.bind(("localhost", port)) # Bind to the port data came in on
sock.sendto(data, (targetHost, listenPort))
def listen(host, port):
listenSocket = socket(AF_INET, SOCK_DGRAM)
listenSocket.bind((host, port))
while True:
data, addr = listenSocket.recvfrom(bufsize)
forward(data, addr[1]) # data and port
listen("localhost", listenPort)
But I'm not sure where to put the outgoing port. The IP for the home server that I'm pulling data on has an IP of say 192.1.1.1 and is streaming data in from port 8787. The remote server has an IP of say 192.1.1.2 and it's listening on port 8788. I'm not sure where I need to put port 8787, which is where the home server is pulling in the data from. Any suggestions would be most helpful. Thanks!
If that last code you quoted runs on your 192.1.1.1, you need to call listen("localhost", 8787) in the last line instead of listen("localhost", listenPort), and you should be fine. listenPort refers to the port where the server that the data is being forwarded to (192.1.1.2) is listening, while listen expects the port where the current machine (192.1.1.1) listens for input. listen then calls forward (telling it to use the same port for the outgoing connection).
How do I get a response from the server?
Client side:
#CLIENT
import socket
import time
host = "localhost"
port = 5454
data_c = input()
c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
c.sendto(bytes(data_c, 'utf-8'),(host,port))
print( data_c )
print( c.recv(1024).decode('utf-8'))
SERVER side:
#SERVER
import socket
import time
host = "localhost"
port = 5454
data_s = "ACKNOWLEDGMENT"
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
print(s.recv(1024).decode('utf-8'))
I can send a message from the server that the client will receive, but can not seem to get communication (like an ACK.) to make it back to the server.
(yes UDP is not a good way to be doing this i'm pretty sure, but that was a specific for the project)
for question 1: to send the ACK, you could replicate what you have in the reverse direction.
Since UDP is connection-less you don't know beforehand you receive a packet where the packet will come from, so you have to use recvfrom to get both the packet and the peer (address/port) the packet came from. Then you have to use that address to send data back.
What you're doing now in your client (but what really looks like the server) in the loop is send the same data over and over to itself. Instead in the loop you should receive packets using the previously mentions recvfrom then send replies to the peer you received the packet from.
So something like the following pseudo code
while True:
peer = recvfrom(...)
sendto(..., peer)
After many attempts to get a simple acknowledgment reply from my server this did it.
Beyond literally starting completely over each round, the time.sleep(.1) function was the only missing key. It allowed the server and client both time to close the current socket connection so that there was not an error of trying to bind multiple bodies to a single location or something.
OSError: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted
Working result:
#SERVER
import socket
import time
host = "localhost"
port = 5454
data_s = "ACKNOWLEDGMENT"
while 1:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
received = print("Client: " + s.recv(1024).decode('utf-8')) #waiting to receive
s.close
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
time.sleep(.1)
s.sendto(bytes(data_s, 'utf-8'),(host,port)) #sending acknowledgment
print("Server: " + data_s)
s.close # close out so that nothing sketchy happens
time.sleep(.1) # the delay keeps the binding from happening to quickly
Server Command Window:
>>>
Client: hello
Server: ACKNOWLEDGMENT
Client:
#CLIENT
import socket
import time
host = "localhost"
port = 5454
c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while 1:
data_c = input("Client: ")
c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
c.sendto(bytes(data_c, 'utf-8'),(host,port)) #send message
c.close
# time.sleep()
c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
c.bind((host, port))
print("Server: " + c.recv(1024).decode('utf-8')) # waiting for acknowledgment
c.close
c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
time.sleep(.1)
Client Command Window:
>>>
Client: hello
Client: hello
Server: ACKNOWLEDGMENT
I did finally remove the redundant input("Client: ") there at the top.
A special thanks #JoachimPileborg for helping, but I have to give it to the little guy just because it was the path I ended up taking.
I am able to send and receive UDP messages in separate programs, but I'm not able to do the same task in one program.
import socket
UDP_IP = "192.168.1.178"
UDP_PORT = 8888
msg = 'test'
print "UDP target IP: ", UDP_IP
print "UDP target PORT: ", UDP_PORT
print "Message: ", msg
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(msg, (UDP_IP, UDP_PORT))
UDP_IP2 = "192.168.1.198"
sock.bind((UDP_IP2, UDP_PORT))
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print "received message:", data
With this program, I am able to send UDP messages, however, I am not able to receive any messages from the other machine.
What am I doing wrong?
Thanks in advance,
Mikkel
In your example you try to bind socket addr after sending, what's wrong.
Address can be bound to socket only before any data transfer.
If there is no explicit bind OS sets any free (unused) port number in range [1024, 65535] on first .send()/.recv() call.
Next, socket can be bound only to single IP (except special case '0.0.0.0' which means "all host's interfaces").