在python中獲取ip地址和在php中有很大不一樣,在php中每每比較簡單。那再python中怎麼作呢?php
咱們先來看一下python 得到本機MAC地址:node
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 e in range ( 0 , 11 , 2 )])
|
下面再來看一下python獲取IP的方法:使用socketpython
1
2
3
4
5
6
7
|
import
socket
#獲取本機電腦名
myname
=
socket.getfqdn(socket.gethostname( ))
#獲取本機ip
myaddr
=
socket.gethostbyname(myname)
print
myname
print
myaddr
|
結果爲:linux
mypc #電腦名socket
192.168.1.111 #ip地址ui
可是注意這裏獲取的IP是內網IPspa
方法三:在linux下可用code
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'
|