w3resource

Python: Find local IP addresses using Python's stdlib

Python Basic: Exercise-55 with Solution

Write a Python to find local IP addresses using Python's stdlib.

Sample Solution:-

Python Code:

import socket
print([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] 
if not ip.startswith("127.")][:1], [[(s.connect(('8.8.8.8', 53)), 
s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, 
socket.SOCK_DGRAM)]][0][1]]) if l][0][0])

Sample Output:

192.168.0.200

Flowchart:

Flowchart: Find local IP addresses using Python's stdlib.

Python Code Editor:

 

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to get the current username.
Next: Write a Python program to get height and the width of console window.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Unknown Arguments Using *arguments:

If your function can take in any number of arguments then add a * in front of the parameter name:

def myfunc(*arguments):
 for a in arguments:
   print a
myfunc(a)
myfunc(a,b)
myfunc(a,b,c)