How to obtain the local IP address using the standard library in python

Source: Internet
Author: User

How to obtain the local IP address using the standard library in python

Standard Library

Python has a powerful standard library. The core of Python only contains common types and functions such as numbers, strings, lists, dictionaries, and files, the Python Standard Library provides additional functions such as system management, network communication, text processing, database interfaces, graphic systems, and XML processing.

The main functions of the Python standard library are:

1. Text processing, including text formatting, regular expression matching, text difference calculation and merging, Unicode support, binary data processing, and other functions

2. File processing, including file operations, creating temporary files, File compression and archiving, and operating configuration files

3. operating system functions, including support for threads and processes, IO reuse, date and time processing, calling system functions, and logging

4. network communication, including network sockets, SSL encrypted communication, asynchronous network communication, and other functions

5. The network protocol supports multiple network protocols such as HTTP, FTP, SMTP, POP, IMAP, NNTP, and XMLRPC, and provides a framework for compiling network servers.

6. W3C format support, including HTML, SGML, and XML processing.

7. Other functions, including international support, mathematical operations, HASH, and Tkinter

Python uses the standard library to obtain the local IP Address

This is the simplest, but also the least reliable. It depends on the hosts file. If the hosts file is not configured, it is generally easy to get 127.0.0.1

import socketsocket.gethostbyname(socket.gethostname())
import sockets = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)s.connect(("8.8.8.8", 80))print(s.getsockname()[0])s.close()
import socketalias myip="python -c '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])'"  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])  print((([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")] or [[(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]]) + ["no IP found"])[0])   print([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1])  print([(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])
import osimport socket if os.name != "nt": import fcntl import struct  def get_interface_ip(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s',  ifname[:15]))[20:24]) def get_lan_ip(): ip = socket.gethostbyname(socket.gethostname()) if ip.startswith("127.") and os.name != "nt": interfaces = [ "eth0", "eth1", "eth2", "wlan0", "wlan1", "wifi0", "ath0", "ath1", "ppp0", ] for ifname in interfaces: try: ip = get_interface_ip(ifname) break except IOError: pass return ip

Obtain the ip address based on the NIC name in linux

>>> import socket, struct, fcntl>>> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)>>> sockfd = sock.fileno()>>> SIOCGIFADDR = 0x8915>>>>>> def get_ip(iface = 'eth0'):... ifreq = struct.pack('16sH14s', iface, socket.AF_INET, '\x00'*14)... try:... res = fcntl.ioctl(sockfd, SIOCGIFADDR, ifreq)... except:... return None... ip = struct.unpack('16sH2x4s8x', res)[2]... return socket.inet_ntoa(ip)...>>> get_ip('eth0')'10.80.40.234'>>>

Windows only

def getIPAddresses(): from ctypes import Structure, windll, sizeof from ctypes import POINTER, byref from ctypes import c_ulong, c_uint, c_ubyte, c_char MAX_ADAPTER_DESCRIPTION_LENGTH = 128 MAX_ADAPTER_NAME_LENGTH = 256 MAX_ADAPTER_ADDRESS_LENGTH = 8 class IP_ADDR_STRING(Structure): pass LP_IP_ADDR_STRING = POINTER(IP_ADDR_STRING) IP_ADDR_STRING._fields_ = [ ("next", LP_IP_ADDR_STRING), ("ipAddress", c_char * 16), ("ipMask", c_char * 16), ("context", c_ulong)] class IP_ADAPTER_INFO (Structure): pass LP_IP_ADAPTER_INFO = POINTER(IP_ADAPTER_INFO) IP_ADAPTER_INFO._fields_ = [ ("next", LP_IP_ADAPTER_INFO), ("comboIndex", c_ulong), ("adapterName", c_char * (MAX_ADAPTER_NAME_LENGTH + 4)), ("description", c_char * (MAX_ADAPTER_DESCRIPTION_LENGTH + 4)), ("addressLength", c_uint), ("address", c_ubyte * MAX_ADAPTER_ADDRESS_LENGTH), ("index", c_ulong), ("type", c_uint), ("dhcpEnabled", c_uint), ("currentIpAddress", LP_IP_ADDR_STRING), ("ipAddressList", IP_ADDR_STRING), ("gatewayList", IP_ADDR_STRING), ("dhcpServer", IP_ADDR_STRING), ("haveWins", c_uint), ("primaryWinsServer", IP_ADDR_STRING), ("secondaryWinsServer", IP_ADDR_STRING), ("leaseObtained", c_ulong), ("leaseExpires", c_ulong)] GetAdaptersInfo = windll.iphlpapi.GetAdaptersInfo GetAdaptersInfo.restype = c_ulong GetAdaptersInfo.argtypes = [LP_IP_ADAPTER_INFO, POINTER(c_ulong)] adapterList = (IP_ADAPTER_INFO * 10)() buflen = c_ulong(sizeof(adapterList)) rc = GetAdaptersInfo(byref(adapterList[0]), byref(buflen)) if rc == 0: for a in adapterList: adNode = a.ipAddressList while True: ipAddr = adNode.ipAddress if ipAddr:  yield ipAddr adNode = adNode.next if not adNode:  break

Third-party library

Https://github.com/ftao/python-ifcfg (local download)

import ifcfgimport json for name, interface in ifcfg.interfaces().items(): # do something with interface print interface['device'] print interface['inet'] print interface['inet6'] print interface['netmask'] print interface['broadcast'] default = ifcfg.default_interface()

Summary

The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.