问题
I would like to send a UDP packet in Python and specify the source port but WITHOUT binding.
An equivalent with hping3:
hping3 -s $sourceport -p $remoteport --udp --file message.bin -d 1024 -c 1 $remoteaddr
I have tried to do something like this:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((SHOST, SPORT))
But of course, Python tries to bind, and it does not work. Now if I don't bind, I can do:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
s.sendto("message", (RHOST, RPORT))
The message gets sent, but now the source port is not defined.
Does anyone have an idea?
EDIT: extended description: my python script complements another application which is an UDP server bound to a defined port (above 1024). My script only needs to send UDP packets to a remote server, but with the same source port as my local UDP server so that the remote UDP server believes the local UDP server is the author of the packet, and will continue the transmission with it.
I think I also have to say that this is a completely legal application and is not related at all with any hacking (in fact, it already works with hping3, but I would like to remove this dependency).
EDIT 2: the solution is in the comments below Nos's answer:
Use the pyip python package and create a raw socket. Don't forget to be root, because only root can send raw packets (this is NOT a limitation of Python but an OS limitation, this is to prevent security issues, so to send raw packets as a user you need to tweak your OS config).
回答1:
There's no API for sending an UDP packet with a defined source port in python , nor on most (all?) the operating systems python runs on without binding the socket to a local port first.
So you'll have to bind() your socket if you want to control the source port.
If bind() "does not work", then you're either binding to a port that another process owns, or a port number < 1024 which only the root user can bind to, or you're giving some other wrong parameters to bind() - but we'd need more info to help you, e.g. the error message you get, the actual parameters you pass to bind, etc.
来源:https://stackoverflow.com/questions/15055266/sending-a-udp-packet-with-source-port-but-without-binding