Python Program to Get IP Address
socket.gethostbyname(socket.gethostname()) which returns the IP as a string.Examples
How to Think About It
gethostname(), then find the IP linked to that name using gethostbyname(). This gives the IP address as a string.Algorithm
Code
import socket ip_address = socket.gethostbyname(socket.gethostname()) print("Your IP address is:", ip_address)
Dry Run
Let's trace getting the IP address on a computer with hostname 'my-pc' and IP '192.168.1.10'.
Import socket module
The socket module is ready to use.
Get hostname
socket.gethostname() returns 'my-pc'
Get IP address
socket.gethostbyname('my-pc') returns '192.168.1.10'
Print IP address
Output: Your IP address is: 192.168.1.10
| Step | Function Call | Returned Value |
|---|---|---|
| 2 | socket.gethostname() | 'my-pc' |
| 3 | socket.gethostbyname('my-pc') | '192.168.1.10' |
Why This Works
Step 1: Import socket module
We import socket because it has functions to work with network details like IP addresses.
Step 2: Get hostname
The gethostname() function gets the computer's network name, which is needed to find its IP.
Step 3: Get IP address
Using gethostbyname() with the hostname returns the IP address as a string.
Step 4: Print result
We print the IP so the user can see their computer's network address.
Alternative Approaches
import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('8.8.8.8', 80)) ip = s.getsockname()[0] s.close() print('Your IP address is:', ip)
import netifaces iface = netifaces.gateways()['default'][netifaces.AF_INET][1] ip = netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr'] print('Your IP address is:', ip)
Complexity: O(1) time, O(1) space
Time Complexity
The program runs a few system calls to get the hostname and IP, which are constant time operations.
Space Complexity
Only a few variables store strings, so space used is constant.
Which Approach is Fastest?
The simple socket.gethostbyname approach is fastest and simplest, but the dummy connection method is more accurate for active IP.
| Approach | Time | Space | Best For |
|---|---|---|---|
| socket.gethostbyname(gethostname()) | O(1) | O(1) | Quick internal IP |
| socket dummy connection | O(1) | O(1) | Active internet IP |
| netifaces library | O(1) | O(1) | Detailed interface info |