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.