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