title: Sending a UDP packet with source port, but without binding
body: <p>I would like to send a UDP packet in Python and specify the source port but WITHOUT binding.</p>
  
  <p>An equivalent with hping3:</p>
  
  <pre><code>hping3 -s $sourceport -p $remoteport --udp --file message.bin -d 1024 -c 1 $remoteaddr
  </code></pre>
  
  <p>I have tried to do something like this:</p>
  
  <pre class="lang-python prettyprint-override"><code>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))
  </code></pre>
  
  <p>But of course, Python tries to bind, and it does not work. Now if I don't bind, I can do:</p>
  
  <pre class="lang-python prettyprint-override"><code>s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
  s.sendto("message", (RHOST, RPORT))
  </code></pre>
  
  <p>The message gets sent, but now the source port is not defined.</p>
  
  <p>Does anyone have an idea?</p>
  
  <p><strong>EDIT</strong>: 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.</p>
  
  <p>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).</p>
  
  <p><strong>EDIT 2</strong>: the solution is in the comments below <a href="https://stackoverflow.com/a/15055312/1324">Nos's answer</a>:</p>
  
  <p>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).</p>