Python gets native native IP address method summary under Windows and Linux

Source: Internet
Author: User
This article summarizes Python's method of acquiring native local IP addresses under Windows and Linux. Share to everyone for your reference. The specific analysis is as follows:

Python socket contains a wealth of functions and methods to obtain the IP address of the computer, the socket object GetHostByName method can be based on the host name to obtain a native IP address, socket object Gethostbyname_ The ex method can get a list of all IP addresses in the machine

The first method: The Socket.gethostbyname method is used to obtain

Import Socketlocalip = Socket.gethostbyname (Socket.gethostname ()) #得到本地ipprint "Local ip:%s"%localip

The returned results are as follows:

' 172.16.34.102 '

Second method: Get a list of native hostname and IP address by socket.gethostbyname_ex method

Import socketiplist = SOCKET.GETHOSTBYNAME_EX (Socket.gethostname ()) print (IPList)

The returned results are as follows:

(' china-43226208c ', [], [' 192.168.5.196 '])

The above two methods can also be used under Linux, Linux also with the following code to get the native IP address

Import Socketimport fcntlimport structdef get_ip_address (ifname):  s = socket.socket (socket.af_inet, socket. SOCK_DGRAM)  return Socket.inet_ntoa (Fcntl.ioctl (    S.fileno (),    0x8915, # siocgifaddr    struct.pack (' 256s ', ifname[:15]))  [20:24])

Hopefully this article will help you with Python programming.

  • 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.