Python obtains native local IP address methods under Windows and Linux summary _python

Source: Internet
Author: User

This example summarizes Python's approach to obtaining 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 information of the machine, the gethostbyname method of the socket object can obtain the native IP address according to the host name, the socket object's Gethostbyname_ The ex method can obtain a list of all IP addresses for this machine

The first method: through the Socket.gethostbyname method of obtaining

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

The returned results are as follows:

' 172.16.34.102 '

The second method: Obtain the local host name and IP Address List by SOCKET.GETHOSTBYNAME_EX method

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

The returned results are as follows:

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

Both of these methods can be used under Linux, Linux also to obtain the local IP address through the following code

Import Socket
Import fcntl
import struct
def 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])

I hope this article will help you with your 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.