I have the following UDP / DGRAM socket in Python:
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print "received message:", data
This code is running in a proxy server, so destination IP and port is not matching the socket. I'm using tproxy to intercept the packets.
How can I get the destination IP and port, not the source IP and port?
from the docs of
socket.getsockname():
Return the socket’s own address. This is useful to find out the port number of an IPv4/v6 socket, for instance.
so you'd want to print out sock.getsockname()
Related
I'm attempting to send a UDP packet from a baremetal embedded device to a script running python.
I see the packet in WireShark and confirmed that everything is correct.
However, the Python script does not see the packet.
I've tested the python code by sending a UDP packet from another python script. The receiving python script does receive it at that point.
I see the packet in the FireWall. It says the packet was allowed and sent to python. I've created a rule in the FireWall to allow traffic from this device. I've also tried disabling the FireWall.
Below is my python script listening for the UDP packet
import socket
UDP_PORT = 5005
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind(('', UDP_PORT))
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print "received message:", data
print "received from:", addr
Why would Python drop the packet?
Netstat shows it received the UDP packet without any errors:
Netstat before receiving the packet
netstat -s -n -p UDP
UDP Statistics for IPv4
Datagrams Received = 5982014
No Ports = 79096
Receive Errors = 829
Datagrams Sent = 1641811
Netstat after receiving the packet
netstat -s -n -p UDP
UDP Statistics for IPv4
Datagrams Received = 5982130
No Ports = 79100
Receive Errors = 829
Datagrams Sent = 1641932
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).
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").
Can anyone tell me the most basic approach to generate UDP, TCP, and IP Packets with Python?
As suggested by jokeysmurf, you can craft packets with scapy
If you you want to send/receive regular, i.e. non-custom, packets then you should use socket or socketserver:
http://docs.python.org/library/socket.html#module-socket
http://docs.python.org/library/socketserver.html#module-SocketServer
For example, to send a TCP HTTP GET request to Google's port 80 use:
import socket
HOST = 'google.com' # The remote host
PORT = 80 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('GET / HTTP/1.1\r\nHost: google.com\r\n\r\n')
data = s.recv(1024)
s.close()
print 'Received', repr(data)
To send UDP instead of TCP change SOCK_STREAM to SOCK_DGRAM.
You can do interactive packet manipulation with scapy.
This article is going to get you started on gluing together an IP packet.
Construction of a tcp packet is as easy as:
packet = IP(src="10.0.0.10")