杰瑞科技汇

Windows下Python如何获取IP?

Of course! This is a very common and important task for any Python developer working on Windows. Here’s a comprehensive guide covering different ways to get and manage IP addresses in Python on Windows.

Windows下Python如何获取IP?-图1
(图片来源网络,侵删)

We'll cover:

  1. Getting your Machine's Local IP Address (the one on your network).
  2. Getting your Machine's Public IP Address (the one visible on the internet).
  3. Managing Network Interfaces (disabling/enabling adapters).
  4. Parsing ipconfig Output (a classic Windows task).
  5. Essential Prerequisites (what you need to install).

Prerequisites: Installing the ipaddress Module

For all the examples below, you'll need Python's built-in ipaddress module. It's included with standard Python installations, so you likely don't need to do anything.

To be sure, you can run this in your terminal or command prompt:

python -m pip install ipaddress

(Although it's usually not necessary, this command will either install it or tell you it's already installed).

Windows下Python如何获取IP?-图2
(图片来源网络,侵删)

Getting Your Local IP Address (The Easy Way)

This is the IP address assigned to your computer by your router (e.g., 168.1.15). It's used for communication within your local network.

The most reliable cross-platform method is to connect to a remote server and see which local address it uses. This works because the socket knows which interface the traffic is being sent out from.

Code:

import socket
def get_local_ip():
    """Gets the local IP address of the machine."""
    try:
        # Connect to a remote server (Google's DNS) to determine the local IP
        # The address and port don't matter as long as it's reachable.
        with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
            s.connect(("8.8.8.8", 80))
            local_ip = s.getsockname()[0]
        return local_ip
    except Exception as e:
        return f"Error getting local IP: {e}"
if __name__ == "__main__":
    my_local_ip = get_local_ip()
    print(f"Your Local IP Address is: {my_local_ip}")

How it works:

  1. We create a UDP socket. UDP is connectionless, so connect() here doesn't actually establish a connection; it just sets the default destination for packets.
  2. s.connect() tells the OS, "I want to send a packet to this address."
  3. The OS has to choose which network interface (Wi-Fi, Ethernet, etc.) to use to get to that destination.
  4. s.getsockname() asks the socket, "What is my own address on the interface you just chose?"
  5. The result is the local IP address of that interface.

Getting Your Public IP Address

This is the IP address that your router sees from the outside world. It's usually assigned by your Internet Service Provider (ISP).

Windows下Python如何获取IP?-图3
(图片来源网络,侵删)

The easiest way to get this in Python is by making a web request to a service that tells you your IP.

Code (using the requests library):

First, you need to install the requests library:

pip install requests
import requests
def get_public_ip():
    """Gets the public IP address of the machine."""
    try:
        # Use a reliable service that returns the caller's IP
        response = requests.get('https://api.ipify.org?format=json')
        response.raise_for_status()  # Raise an exception for bad status codes (4xx or 5xx)
        public_ip = response.json()['ip']
        return public_ip
    except requests.exceptions.RequestException as e:
        return f"Error getting public IP: {e}"
if __name__ == "__main__":
    my_public_ip = get_public_ip()
    print(f"Your Public IP Address is: {my_public_ip}")

Alternative Services:

  • https://ifconfig.me/ip
  • https://icanhazip.com
  • https://ipinfo.io/json

Managing Network Interfaces (Enable/Disable)

This is a more advanced task that requires administrator privileges because you are modifying system network settings. The best way to do this on Windows is by calling the netsh (Network Shell) command-line utility using Python's subprocess module.

Code:

import subprocess
import sys
def manage_network_adapter(adapter_name, action):
    """
    Enables or disables a Windows network adapter.
    :param adapter_name: The name of the adapter (e.g., "Ethernet", "Wi-Fi").
    :param action: "enable" or "disable".
    """
    action = action.lower()
    if action not in ["enable", "disable"]:
        print("Invalid action. Please use 'enable' or 'disable'.")
        return
    # The command to run. Requires admin rights.
    # Note: The adapter name might need to be in quotes if it contains spaces.
    command = f"netsh interface set interface name=\"{adapter_name}\" {action}"
    print(f"Attempting to {action} adapter: '{adapter_name}'")
    print("This script requires Administrator privileges.")
    print("Please run your terminal/IDE as an Administrator.")
    try:
        # For security, it's better to pass the command as a list of arguments
        # and use shell=False. However, netsh can be tricky.
        # Using shell=True is simpler here but less secure.
        process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = process.communicate()
        if process.returncode == 0:
            print(f"Successfully {action}d '{adapter_name}'.")
            print(stdout.decode('utf-8', errors='ignore'))
        else:
            print(f"Failed to {action} '{adapter_name}'.")
            print("Error Output:")
            print(stderr.decode('utf-8', errors='ignore'))
    except Exception as e:
        print(f"An exception occurred: {e}")
if __name__ == "__main__":
    # --- IMPORTANT ---
    # 1. Find your exact adapter name by running `ipconfig` in a command prompt.
    # 2. Run this script from an Administrator Command Prompt or PowerShell.
    # Example: Disable the Wi-Fi adapter
    # manage_network_adapter("Wi-Fi", "disable")
    # Example: Enable the Ethernet adapter
    # manage_network_adapter("Ethernet", "enable")
    if len(sys.argv) != 3:
        print("Usage: python manage_network.py <AdapterName> <enable|disable>")
        print("Example: python manage_network.py \"Wi-Fi\" disable")
    else:
        adapter = sys.argv[1]
        action = sys.argv[2]
        manage_network_adapter(adapter, action)

How to use:

  1. Find the exact name of your adapter by opening Command Prompt and typing ipconfig /all. Look for the "Description" or "Name" of the adapters.
  2. Save the code above as manage_network.py.
  3. Right-click on your Command Prompt or PowerShell and select "Run as administrator".
  4. Navigate to the directory where you saved the file.
  5. Run the script with the adapter name and action:
    python manage_network.py "Wi-Fi" disable

Parsing ipconfig Output

Sometimes you need to get detailed information about all network interfaces, just like the ipconfig command. You can run ipconfig from Python and parse its text output.

Code:

import subprocess
import re
import json
def parse_ipconfig():
    """Runs 'ipconfig /all' and parses the output into a dictionary."""
    try:
        # Run the ipconfig command and capture the output
        result = subprocess.run(['ipconfig', '/all'], capture_output=True, text=True, check=True)
        output = result.stdout
        # Regex to find adapter blocks and their details
        # This regex is a good starting point but might need refinement for all edge cases.
        adapter_pattern = re.compile(
            r'([^\r\n]+?) adapter\s*:\s*([^\r\n]+?)\r\n'  # Adapter Name and Type
            r'(.*?)(?=\r\n[^\r\n]+ adapter:|\Z)',         # All details until next adapter or end
            re.DOTALL
        )
        details_pattern = re.compile(r'([^\s:]+):\s*([^\r\n]+)')
        adapters = {}
        for match in adapter_pattern.finditer(output):
            adapter_name = match.group(1).strip()
            adapter_type = match.group(2).strip()
            details_block = match.group(3)
            details = {}
            for detail_match in details_pattern.finditer(details_block):
                key = detail_match.group(1).strip()
                value = detail_match.group(2).strip()
                details[key] = value
            adapters[adapter_name] = {
                "Type": adapter_type,
                "Details": details
            }
        return adapters
    except subprocess.CalledProcessError as e:
        return f"Error running ipconfig: {e.stderr}"
    except Exception as e:
        return f"An error occurred: {e}"
if __name__ == "__main__":
    ipconfig_data = parse_ipconfig()
    # Print the raw dictionary
    # print(json.dumps(ipconfig_data, indent=2))
    # A more user-friendly print
    if isinstance(ipconfig_data, dict):
        for name, info in ipconfig_data.items():
            print(f"--- Adapter: {name} ({info['Type']}) ---")
            details = info['Details']
            if 'IPv4 Address' in details:
                print(f"  IPv4 Address: {details['IPv4 Address']}")
            if 'IPv6 Address' in details:
                print(f"  IPv6 Address: {details['IPv6 Address']}")
            if 'Physical Address' in details:
                print(f"  MAC Address: {details['Physical Address']}")
            print("-" * 30)
    else:
        print(ipconfig_data)

This script uses regular expressions to break down the text output of ipconfig /all into a structured Python dictionary, which is much easier to work with than raw text.

分享:
扫描分享到社交APP
上一篇
下一篇