| |

VerySource

 Forgot password?
 Register
Search
View: 998|Reply: 0

python获取本机IP、mac地址、计算机名

[Copy link]

2

Threads

2

Posts

0.00

Credits

Newbie

Rank: 1

Credits
0.00

 China

Post time: 2023-5-3 12:16:44
| Show all posts |Read mode
python获取本机IP、mac地址、计算机名
  • [backcolor=rgba(1, 126, 102, 0.08)]python

  • [backcolor=rgba(1, 126, 102, 0.08)]IP

  • [backcolor=rgba(1, 126, 102, 0.08)]mac地址


在python中获取ip地址和在php中有很大不同,在php中往往比较简单。那再python中怎么做呢?

我们先来看一下python 获得本机MAC地址:

1

2

3

4

import uuid
def get_mac_address():
    mac=uuid.UUID(int = uuid.getnode()).hex[-12:]
    return ":".join([mac[e:e+2]for ein range(0,11,2)])


下面再来看一下python获取IP的方法:使用socket

1

2

3

4

5

6

7

import socket
#获取本机电脑名
myname= socket.getfqdn(socket.gethostname(  ))
#获取本机ip
myaddr= socket.gethostbyname(myname)
print myname
print myaddr

结果为:

mypc  #电脑名

192.168.1.111 #ip地址

但是注意这里获取的IP是内网IP


方法三:在linux下可用

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

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'

转载地址:https://www.pythontab.com/html/2013/pythonjichu_0127/177.html



Reply

Use magic Report

You have to log in before you can reply Login | Register

Points Rules

Contact us|Archive|Mobile|CopyRight © 2008-2023|verysource.com ( 京ICP备17048824号-1 )

Quick Reply To Top Return to the list