How to get the IP address of the local machine in python
使用socket模块可获取本地IP,推荐通过连接8.8.8.8获取真实局域网IP(如192.168.x.x),避免返回127.0.0.1;多网卡环境可用netifaces库获取所有接口IP。

To get the IP address of the local machine in Python, you can use the built-in socket module. This approach works across different operating systems like Windows, macOS, and Linux.
Using socket.gethostbyname() with socket.gethostname()
This method retrieves the hostname of the machine and then resolves it to its corresponding IP address.Here's a simple example:
import socket
<p>ip_address = socket.gethostbyname(socket.gethostname())
print(f"Local IP Address: {ip_address}")</p>Note: On some systems, this might return 127.0.0.1 (localhost), especially if the hostname is mapped to localhost in the hosts file.Getting the external-facing IP (Recommended for accuracy)
If you want the actual local network IP (like 192.168.x.x or 10.x.x.x), a more reliable method is to connect to an external server (without sending data) and check the socket's local address.Example:
<code>import socket
<p>def get_local_ip():
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
try:</p><h1>Doesn't need to reach the destination</h1><pre class="brush:php;toolbar:false"><code> s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
except Exception:
ip = "127.0.0.1"
return ipprint(f"Local Network IP: {get_local_ip()}")
This method avoids issues with DNS mapping and reliably returns the machine’s LAN IP.Handling multiple network interfaces
If your machine has multiple network interfaces, the above method returns the IP associated with the default route. For advanced use cases, consider using third-party packages like netifaces to list all interface IPs.Install it via pip:
<code>pip install netifaces
Then use:
<code>import netifaces
<p>for interface in netifaces.interfaces():
addresses = netifaces.ifaddresses(interface)
if netifaces.AF_INET in addresses:
for addr in addresses[netifaces.AF_INET]:
print(f"Interface {interface}: {addr['addr']}")</p>For most basic purposes, the socket-based method connecting to 8.8.8.8 is reliable and doesn’t require external dependencies. Basically just pick the method that fits your environment and needs.
The above is the detailed content of How to get the IP address of the local machine in python. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20521
7
13633
4
Solve the error of multidict build failure when installing Python package
Mar 08, 2026 am 02:51 AM
When installing libraries that depend on multidict in Python, such as aiohttp or discord.py, users may encounter the error "ERROR: Could not build wheels for multidict". This is usually due to the lack of the necessary C/C compiler or build tools, preventing pip from successfully compiling multidict's C extension from source. This article will provide a series of solutions, including installing system build tools, managing Python versions, and using virtual environments, to help developers effectively solve this problem.
How to find the sum of 5 numbers using Python's for loop
Mar 10, 2026 pm 12:48 PM
This article explains in detail how to use a for loop to read 5 integers from user input and add them up, provide a concise and readable standard writing method, and compare efficient alternatives to built-in functions.
How to use the Python zip function_Parallel traversal of multiple sequences and dictionary construction
Mar 13, 2026 am 11:54 AM
The essence of zip is zipper pairing, which packs multiple iterable objects into tuples by position and does not automatically unpack the dictionary. When passing in a dictionary, its keys are traversed by default. You need to explicitly use the keys()/values()/items() view to correctly participate in parallel traversal.
How to draw a histogram in Python_Multi-dimensional classification data comparison and stacked histogram color mapping implementation
Mar 13, 2026 pm 12:18 PM
Multi-dimensional classification histograms need to manually calculate the x position and call plt.bar hierarchically; when stacking, bottom must be used to accumulate height, and xticks and ylim must be explicitly set (bottom=0); avoid mixing stacked=True and seaborn, and colors should be dynamically generated and strictly match the layer sequence.
How Python manages dependencies_Comparison between pip and poetry
Mar 12, 2026 pm 04:21 PM
pip is suitable for simple projects, which only install packages and do not isolate the environment; poetry is a modern tool that automatically manages dependencies, virtual environments and version locking. Use pip requirements.txt for small projects, and poetry is recommended for medium and large projects. The two cannot be mixed in the same project.
Python set intersection optimization_large data volume set operation skills
Mar 13, 2026 pm 12:36 PM
The key to optimizing Python set intersection performance is to use the minimum set as the left operand, avoid implicit conversion, block processing and cache incremental updates. Priority should be given to using min(...,key=len) to select the smallest set, disabling multi-parameter intersection(), using frozenset or bloom filters to reduce memory, and using lru_cache to cache results in high-frequency scenarios.
How to store sparse matrices in Python_Dictionary coordinate storage and use of scipy.sparse
Mar 12, 2026 pm 05:48 PM
Use scipy.sparse.coo_matrix instead of a dictionary because the bottom layer uses row/col/data three-array to efficiently support operations; the structure needs to be deduplicated, converted to csr/csc and then calculated; save_npz is preferred for saving; operations such as slicing must use csr/csc format.
How to run a Python script_Detailed explanation of various ways to run a Python script and command line operations
Apr 03, 2026 pm 01:51 PM
To run a Python script, make sure that Python is installed, the PATH configuration is correct, and the script has no syntax errors; confirm the interpreter path and version through which/where and --version; shebang only takes effect on Linux/macOS and requires chmod x; when reporting module errors, you need to check the working directory, sys.path, piplist, and running mode.





