[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
IP4 UDP
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(("8.8.8.8", 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

print(get_broadcast_ip())
---

The first trick is the use of a dummy socket connected to a "real" internet
address.
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.
https://github.com/giampaolo/psutil

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
more.
Anyway, it has a very convenient list of network interfaces and their
corresponding addresses.

So thus, the tiny function!

Brian
--
Happy 2020!
https://drive.google.com/file/d/1Sm7BRiuGMVCA3vZDlWMyPPx-jerj-jXz/view?usp=sharing


More information about the NCLUG mailing list