Python network programming: socket, gethostname, gethostbyname

Source: Internet
Author: User

Python network programming: socket, gethostname, gethostbyname

Function: print the Host Name and Host IP Address:

 

[root@iZ94gh8l046Z python]# cat socket1.py #!/usr/bin/pythonimport sockethost_name = socket.gethostname()print hostname:%s % host_nameprint IP address: %s %socket.gethostbyname(host_name)

Running result:

 

[Root @ iZ94gh8l046Z python] #./socket1.py
Hostname: iZ94gh8l046Z
IP address: 10.170.16.67

Module:

Import socket

Usage:

Socket. gethostname get hostname (/etc/hostname)

Socket. gethostbyname

After improvement:

 

[root@iZ94gh8l046Z python]# cat socket2.py #!/usr/bin/pythonimport socketdef print_machine_info():    host_name = socket.gethostname()    ip_address = socket.gethostbyname(host_name)    print hostname:%s % host_name    print IP address: %s %ip_addressif __name__ == '__main__':    print_machine_info()

 

Running result:

[Root @ iZ94gh8l046Z python] #./socket2.py
Hostname: iZ94gh8l046Z
IP address: 10.170.16.67


Description: We need to call this function in the commonly used _ main _ code block.

During runtime, Python assigns values to some internal variables, such as _ name __. Here, __name _ indicates the name of the process that calls the program.

If you run the script in the command, the value of __name _ is _ main __

However, if you import data in other scripts, the situation is different.

That is to say, if this module is called in the command line, the print_machine_info () function is automatically run.

If you import data in other scripts, you must manually call this function.

 

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.