Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - set source port number with sockets

I'd like to send a specific UDP broadcast packet. Unfortunately, I need to send the UDP packets from a very specific port.

Let's say I broadcast via UDP "BLABLAH". The server will only answer if my incoming packet source port was 1444; if not, then the packet is discarded.

My broadcast socket setup looks like this:

s = socket(AF_INET,SOCK_DGRAM)

s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)

How can I then set the source port in Python?

like image 759
beratch Avatar asked Apr 22 '10 20:04

beratch


People also ask

Does socket use TCP or UDP Python?

The second argument determines the socket type; socket. SOCK_DGRAM is UDP, socket. SOCK_STREAM is a TCP socket. This all provided you are using a AF_INET or AF_INET6 socket family.


2 Answers

You need to bind the socket to the specific port you want to send from. The bind method takes an address tuple, much like connect, though you can use the wildcard address. For example:

s.bind(('0.0.0.0', 1444))
like image 115
Stéphan Kochen Avatar answered Sep 27 '22 20:09

Stéphan Kochen


Use s.bind(('', port)).

like image 37
jweyrich Avatar answered Sep 27 '22 20:09

jweyrich