[NCLUG] A short subject: How to find the broadcast address in Python.

Brian Sturgill bsturgill at ataman.com
Mon Sep 21 18:10:51 MDT 2020

I'm in process of making intercoms.
They work by sending a stream of audio packets to a known ip port using the
address broadcast for the network.

Anyway, I wanted to autoconfigure the broadcast address and this isn't as
simple as it ought to be.
However I found two nifty tricks and used them in the following code:
import psutil
import socket

# Broadcast ip of the interface that is the default route.
def get_broadcast_ip():
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
        s.connect(("", 80))
        addr = s.getsockname()[0]
        ifs = psutil.net_if_addrs()
        for if_name in ifs:
            for if_a in ifs[if_name]:
                if if_a.address == addr:
                    return if_a.broadcast


The first trick is the use of a dummy socket connected to a "real" internet
This will cause 'getsockname' to give you the real ip address of the
default routed interface.

The second trick is the use of the 'psutil' package.

This is a package that gives you much information that you'd get from ps,
ifconfig, etc.
What's really interesting is that it works on Linux, MacOS, Windows and
Anyway, it has a very convenient list of network interfaces and their
corresponding addresses.

So thus, the tiny function!

Happy 2020!

More information about the NCLUG mailing list