Python獲取本機IP(多網絡卡)

2021-09-20 22:16:08 字數 1441 閱讀 2326

python獲取本機ip位址的一般方法為

1

2

3

importsocket

ip=socket.gethostbyname(socket.gethostname())

通過gethostname獲取主機名,再用gethostbyname將主機名轉換為ip位址。

那麼,問題來了。如果主機有多個網絡卡/ip,怎樣獲取某個指定的ip位址呢?

乙個方法是通過socket.gethostbyname_ex獲取主機ip位址列表,然後遍歷列表取得自己需要的ip。

1

2

3

4

5

6

7

8

9

10

11

12

13

importsocket

#多網絡卡情況下,根據字首獲取ip

defgetlocalipbyprefix(prefix):

localip=''

foripinsocket.gethostbyname_ex(socket.gethostname())[2]:

ifip.startswith(prefix):

localip=ip

returnlocalip

print(getlocalipbyprefix('192.168'))

更簡單的方法(不用修改**,還是用socket.gethostname函式),是通過配置hosts檔案改變ip優先順序。

上面的方法只支援ipv4,如果要獲取ipv6資訊,參考socket.getaddrinfo。

多網絡卡下獲取本機IP的方式。

多網絡卡下獲取本機ip的方式。方式一 public class networkutils catch socketexception e log.error 獲取本地ip 失敗 e return localhostip 方式二 private static string getinetaddress...

linux獲取本機網絡卡ip位址

include include include include include include include include include define eth name eth0 int main strncpy ifr.ifr name,eth name,ifnamsiz ifr.ifr n...

python 獲取本機 IP

這個方法是目前見過最優雅獲取本機伺服器的ip方法了。沒有任何的依賴,也沒有去猜測機器上的網路裝置資訊。而且是利用 udp 協議來實現的,生成乙個udp包,把自己的 ip 放如到 udp 協議頭中,然後從udp包中獲取本機的ip。這個方法並不會真實的向外部發包,所以用抓包工具是看不到的。但是會申請乙個...