Categories
Python Answers

How to find local IP addresses using Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *