Menu Close

How to find local IP addresses using Python?

Sometimes, we want to find local IP addresses using Python.

In this article, we’ll look at how to find local IP addresses using Python.

How to find local IP addresses using Python?

To find local IP addresses using Python, we can use the socket module.

For instance, we write

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
print(s.getsockname()[0])
s.close()

to call docket.socket to create a socket object.

Then we connect to a DNS server with s.connect.

Next, we get the IP address from the getsockname method.

Finally, we call close to close the connection.

Conclusion

To find local IP addresses using Python, we can use the socket module.

Posted in Python, Python Answers