Python Network programming: Socket,gethostname,gethostbyname

Source: Internet
Author: User

Features: Print host name and host IP:

[email protected] python]# Cat socket1.py #!/usr/bin/pythonimport sockethost_name = socket.gethostname () print " hostname:%s "% host_nameprint" IP address:%s "%socket.gethostbyname (HOST_NAME)

Operation Result:

[Email protected] python]#./socket1.py
hostname:iz94gh8l046z
IP address:10.170.16.67

Module:

Import socket

How to use:

Socket.gethostname get hostname (/etc/hostname)

Socket.gethostbyname Get host IP

After improvement:

[email protected] 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 ()

Operation Result:

[Email protected] python]#./socket2.py
hostname:iz94gh8l046z
IP address:10.170.16.67


Description: We want to call this function in a common __main__ code block.

At run time, Python assigns values to certain internal variables, such as __name__. Here, __name__ represents the process name of the calling program.

If you run the script in a command, the value of __name__ is __main__

However, if you import in another script, the situation is different.

That is, if the module is called at the command line, the Print_machine_info () function is automatically run

If imported in another script, the user will call this function manually.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Python network programming: Socket,gethostname,gethostbyname

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.