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.
Related
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))
I am new to python programming. I have the task to read the broadcast feed on UDP port 4012.I have code of visual basic and it is working fine. The code is as follows.
#Dim receivingUdpClient As New UdpClient(4012)
#Dim RemoteIpEndPoint As New IPEndPoint(IPAddress.Any, 0)
#receiveBytes = receivingUdpClient.Receive(RemoteIpEndPoint)
#returnData = Encoding.ASCII.GetString(receiveBytes)
#Dim TestArray() As String = Split(returnData, ";")
I made the following program in python to read the broadcast feed on UPD port 4012, but was unable to achieve it with the following python program. The program is working and shows the cmd window message "waiting for 4012 localhost from 4012".
Can anybody help me out with this? If the code is correct then, how can i checked resolve this issue? i also want to read good material about socket programming in python specially about the UDP socket Broad Cast reading, if anybody can recommend any video or material for read.
import socket
s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_host = 'localhost'
udp_port = 4012
s.connect((udp_host,udp_port))
print("waiting for 4012",udp_host, "from" ,udp_port)
data , addr= s.recvfrom(1024)
print("Received Messages: ", data ,"from", addr)
You should use broadcast IP to listen.
Currently you are listening 'localhost', but broadcast IP is usually your subnet maximum IP (for 255.255.255.0 mask it is IP with number 255 in last octet)
You need to get right IP from somewhere. Manually you can do it with ifconfig on *nix, or ipconfig on Win:
inet 192.168.100.7 netmask 0xffffff00 broadcast 192.168.100.255
so you need 192.168.100.255
Also, easy way is to listen all IP's. To listen all IP's you could bind socket to '0.0.0.0' or just ''. But in this case you'll catch both broadcast and direct packets.
import socket
s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_host = ''
udp_port = 4012
s.connect((udp_host,udp_port))
print("waiting for 4012",udp_host, "from" ,udp_port)
data , addr= s.recvfrom(1024)
print("Received Messages: ", data ,"from", addr)
this snippet is something i use quite often do create basic socket server stuff...
socket_config = {
'udp_ip_address': 'your.ip.here.bla',
'udp_port_no': '6789',
'max_send_size': '1024'
}
#
# socket creation
#
serverSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
serverSock.bind((socket_config['udp_ip_address'],
int(socket_config['udp_port_no'])))
def receive_loop():
# eternal loop starts here
while True:
data, addr = serverSock.recvfrom(int(socket_config['max_send_size']))
data = data.decode('utf-8')
logger.debug("Message:" + data)
I have connected two windows machines using ethernet cable and i assigned static ip for each computer. I used wireshark on both machines to monitor the packets. I have used python socket to send UDP packets.
sender.py
import socket
import time
DST_IP="192.168.0.191"
DST_PORT=2000
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # UDP
message = b"your very important message"
while True:
sock.sendto(message, (DST_IP,DST_PORT))
print("message sent!")
time.sleep(1)
receiver.py
import socket
import time
UDP_IP = "192.168.0.191"
UDP_PORT = 2000
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print(data)
sender computer have address 192.168.0.155 and receiver has 192.168.1.191 wireshark shark on sender shows packet is sent and wireshark on receiver shows the packet is received.
But receiver side python doesn't show anything.
Why python socket is not receving anything whereas wireshark does?
Facts & context elements:
I need to capture data (latitude,longitude) coming out of a GPS device rework them and make them suitable for another application (QGIS). To this end I've tried to perform (What I thought at first would be a simple one) a python based module.
According to wire shark analysis.
Source Destination Protocol length info
192.168.0.1 225.2.5.1 UPD 136 source port : 1045 destination port:6495
I've tried this code found on various sources, like this one.
import socket
import os
UDP_IP = "225.2.5.1"
UDP_PORT = 6495
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(4096) # buffer size is 1024 bytes
print "received message:", data
os.system("pause")
The problem
This code doesn't work for me.The console windows whether collapse (despite the os.system("pause") or run indefinitely. As I'm not very skilled in python programming nor networking I've tested the provided code with the other IP address and port. As no result came from it I've also started to mix both of them. And finally, gave up and decided to share my issue with the community.
The aim :
I need to be able to access the data contains in this UDP frame with python 2.7 save them in a variable (data) for the next step of my programming project.
Thanks for reading and for your help
You should start your python program from the windows cmd-console or powershell, not from the explorer, then the window stays open and you see error messages. Remove the indentation error and the last line. Be sure, that your computer has the given IP-address. Bind your socket to any address:
import socket
UDP_IP = "0.0.0.0"
UDP_PORT = 6495
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(4096)
print "received message:", data
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").