Skip to content

How to get the IP Address in Python

If you need to get the IP Address in your Python application, then you can do the following:

Option 1 – Using socket.gethostname()

import socket print(socket.gethostbyname(socket.gethostname()))
Code language: Python (python)

Option 2 – Using socket.getsockname()

import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) print(s.getsockname()[])
Code language: Python (python)

Option 3 – Using the netifaces module

from netifaces import interfaces, ifaddresses, AF_INET for ifaceName in interfaces(): addresses = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'No IP addr'}] )] print(' '.join(addresses))
Code language: Python (python)

See also  How to Check for Factor in Python
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x