2022年2月3日 星期四

[ Python 常見問題 ] How can I get the IP address from NIC in Python?

 Source from here

Question
So how can I get the IP address of specific network interface in Python?

HowTo

Method #1 (use external package)
You need to ask for the IP address that is bound to your eth0 interface. This is available from the netifaces package. Before all, let's check out network interfaces:
# ip addr show
...
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
link/ether 00:0c:29:9f:e6:d5 brd ff:ff:ff:ff:ff:ff
altname enp2s1
inet 192.168.37.131/24 brd 192.168.37.255 scope global dynamic noprefixroute ens33
valid_lft 1672sec preferred_lft 1672sec
inet6 fe80::6b54:4ab:9041:4fcd/64 scope link noprefixroute
valid_lft forever preferred_lft forever

Then check below code snippet for how to retrieve IP address:
>>> import netifaces as ni
>>> from pprint import pprint
>>> pprint(ni.ifaddresses('ens33'))
  1. {2: [{'addr''192.168.37.131',  
  2.       'broadcast''192.168.37.255',  
  3.       'netmask''255.255.255.0'}],  
  4. 10: [{'addr''fe80::6b54:4ab:9041:4fcd%ens33',  
  5.        'netmask''ffff:ffff:ffff:ffff::'}],  
  6. 17: [{'addr''00:0c:29:9f:e6:d5''broadcast''ff:ff:ff:ff:ff:ff'}]}  

>>> ni.ifaddresses('ens33')[ni.AF_INET][0]['addr']
'192.168.37.131'
>>> ni.interfaces()
['lo', 'ens33', 'br-85c9ddfa802f', 'docker0', 'br-1f95accf9779', 'br-227986c2fe47']

Method #2 (no external package)
Here's a way to get the IP address without using a python package:
>>> import socket
>>> import fcntl
>>> import struct
>>> socket.gethostbyname(socket.gethostname())
'127.0.1.1'
>>> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
>>> packed_iface = struct.pack('256s', 'ens33'.encode('utf_8'))
>>> packed_addr = fcntl.ioctl(sock.fileno(), 0x8915, packed_iface)[20:24]
>>> socket.inet_ntoa(packed_addr)
'192.168.37.131'


[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...