Python methods for obtaining local IP addresses in windows and linux, pythonlinux

Source: Internet
Author: User

Python methods for obtaining local IP addresses in windows and linux, pythonlinux

This example summarizes how python obtains the local IP address of a local machine in windows and linux. Share it with you for your reference. The specific analysis is as follows:

Python's socket contains rich functions and methods to obtain the IP address information of the Local Machine. The gethostbyname method of the socket object can obtain the IP address of the Local Machine Based on the host name. The gethostbyname_ex method of the socket object can obtain the list of all IP addresses of the local machine.

Method 1: Use socket. gethostbyname to obtain

Import socketlocalIP = socket. gethostbyname (socket. gethostname () # obtain the local ipprint "local ip: % s" % localIP

The returned results are as follows:

'2017. 16.34.102'

Method 2: Use socket. gethostbyname_ex to obtain the Host Name and IP address list of the local machine.

import socketipList = socket.gethostbyname_ex(socket.gethostname())print(ipList)

The returned results are as follows:

('China-43226208c', [], ['192. 168.5.196 '])

The above two methods can also be used in linux. in linux, the local IP address is also obtained using the following code.

import socketimport fcntlimport structdef 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])

I hope this article will help you with Python programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.