Get the native IP, MAC address, computer name

Source: Internet
Author: User
Tags uuid

Python Gets the native IP, MAC address, computer name

Getting an IP address in Python is a big difference in PHP, so let's take a look at Python's native MAC address:

>>> Import UUID

>>> def get_mac_address ():

Mac = uuid. UUID (int = Uuid.getnode ()). HEX[-12:]

Return ': '. Join ([mac[e:e+2] for E in range (0,11,2)])

>>> get_mac_address ()

' A4:be:6d:99:87:db '

Here's another look at Python's approach to acquiring IP: using the socket

>>> Import Socket

>>> hostname = SOCKET.GETFQDN (Socket.gethostname ())

>>> Print (hostname)

User-20160730zr

>>> hostaddr = socket.gethostbyname (hostname)

>>> Print (HOSTADDR)

192.168.217.1

But note that the IP you get here is the intranet IP

Method Two: Available under Linux, window is invalid

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])

>>> get_ip_address (' lo ')

' 127.0.0.1 '

>>> get_ip_address (' eth0 ')

' 38.113.228.130 '

Get the native IP, MAC address, computer name

Related Article

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.