天天看點

Python擷取本機IP(多網卡)

 Python擷取本機IP位址的一般方法為

<code>import</code> <code>socket</code>

<code>IP </code><code>=</code> <code>socket.gethostbyname(socket.gethostname())</code>

  通過gethostname擷取主機名,再用gethostbyname将主機名轉換為IP位址。

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

  一個方法是通過socket.gethostbyname_ex擷取主機IP位址清單,然後周遊清單取得自己需要的IP。

<code>#多網卡情況下,根據字首擷取IP</code>

<code>def</code> <code>GetLocalIPByPrefix(prefix):</code>

<code>    </code><code>localIP </code><code>=</code> <code>''</code>

<code>    </code><code>for</code> <code>ip </code><code>in</code> <code>socket.gethostbyname_ex(socket.gethostname())[</code><code>2</code><code>]:</code>

<code>        </code><code>if</code> <code>ip.startswith(prefix):</code>

<code>            </code><code>localIP </code><code>=</code> <code>ip</code>

<code>    </code> 

<code>    </code><code>return</code> <code>localIP</code>

<code>print</code><code>(GetLocalIPByPrefix(</code><code>'192.168'</code><code>))</code>

  更簡單的方法(不用修改代碼,還是用socket.gethostname函數),是通過配置hosts檔案改變IP優先級。

相關閱讀:

本文轉自walker snapshot部落格51CTO部落格,原文連結http://blog.51cto.com/walkerqt/1686735如需轉載請自行聯系原作者

RQSLT