python擷取本地ip

來源:互聯網
上載者:User

標籤:

def get_ip_address(ifname):    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)    return socket.inet_ntoa(fcntl.ioctl(s.fileno(),0x8915,struct.pack(‘256s‘, ifname[:15]))[20:24])

 

1.通訊端

2.通常,非Python程式以32位位元組包的形式儲存和使用IP地址。inet_aton(ip_addr)和inet_ntoa(packed)函數在這個形式和IP地址間作轉換:http://blog.sina.com.cn/s/blog_6d0599f90100rlem.html

>>> socket.inet_aton(‘192.169.137.77‘)‘\xc0\xa9\x89M‘

 

3.檔案描述符與一個真實的socket串連,而非一個檔案。socket對象的fileno()方法返回關於這個socket的檔案描述符。

4.linux裡面提供了mac地址和ip地址擷取的ioctl參數;

#define SIOCGIFADDR 0x8915      /* get PA address       */#define SIOCSIFADDR 0x8916      /* set PA address       */#define SIOCSIFHWADDR   0x8924      /* set hardware address     */#define SIOCGIFHWADDR   0x8927      /* Get hardware address     */

5. struct.pack用於將Python的值根據格式符,轉換為字串(因為Python中沒有位元組(Byte)類型,可以把這裡的字串理解為位元組流,或位元組數組)。其函數原型為:struct.pack(fmt, v1, v2, ...),參數fmt是格式字串,關于格式字串的相關資訊下面有所介紹。v1, v2, ...表示要轉換的python值。http://blog.sina.com.cn/s/blog_4b5039210100f1tu.html

6.ioctl()。 http://blog.csdn.net/shanshanpt/article/details/19897897

 

python擷取本地ip

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.