1.简单易懂直接上代码:
# -*- coding=gb2312 -*-#! /usr/bin/env python# Python Network Programming Cookbook --Chapter -1# This program is optimized for python 2.7. It may run on any# other Python version with/without modifications# -*- coding=gb2312 -*-import socket def print_machine_info(): host_name=socket.gethostname() ip_address=socket.gethostbyname(host_name) print "Host name is:%s"% host_name print "IP address is:%s"% ip_address if __name__==‘__main__‘: print_machine_info()
2.获取远程设备的IP地址:
# -*- coding: UTF-8 -*-# !/usr/bin/env/ python # Python Network Programming Cookbook --Chapter -1# This program is optimized for Python 2.7# It may run on any other version with/without modifications import socket def get_remote_machine_info(): remote_host = ‘www.hqu.edu.cn‘ try: print "主机的IP地址是:%s" %socket.gethostbyname(remote_host) except socket.error,err_msg: print "%s: %s" %(remote_host,err_msg) if __name__==‘__main__‘: get_remote_machine_info()
3.将IPv4地址转换为不同的格式:
# -*- coding: UTF-8 -*-# 如果要使用底层的网络函数,有时普通的字符串格式的IP地址并不是很有用,需要我们把它转换为打包后的32位二进制格式 # !/usr/bin/env python# Python Network Programming Cookbook --Chapter -1# This program is optimized for Python 2.7# It may run on any other version with/without modifications import socketfrom binascii import hexlify def convert_ipv4_address(): for ip_addr in [‘127.0.0.1‘,‘192.168.0.1‘]: packed_ip_addr =socket.inet_aton(ip_addr) unpacked_ip_addr = socket.inet_ntoa(packed_ip_addr) print "IP 地址: %s => 打包后:%s ,没有打包前:%s"\ %(ip_addr,hexlify(packed_ip_addr),unpacked_ip_addr) if __name__==‘__main__‘: convert_ipv4_address()
4.通过指定的端口和协议找到服务名:
# -*- coding: UTF-8 -*-# 如果想找到网络服务,最好知道服务运行在TCP或UDP协议的哪个端口上# !usr/bin/env python# Python Network Programming Cookbook --Chapter -1# This program is optimized for Python 2.7# It may run on any other version with/without modifications import socketdef find_service_name(): protocolname = ‘tcp‘ for port in [80,25]: print "端口:%s => 服务名称是:%s " %(port,socket.getservbyport(port,protocolname))\ print "端口:%s => 服务名称是:%s" %(53,socket.getservbyport(53,‘udp‘)) if __name__==‘__main__‘: find_service_name()
5.主机字节序和网络字节之间相互转换:
# -*- coding: UTF-8 -*-# 编写底层网络应用时,或许需要处理通过电缆在两台设备之间传输的底层数据,需要把主机操作系统发出的数据转化为网络各式# !usr/bin/env python# Python Network Programming Cookbook --Chapter -1# This program is optimized for Python 2.7# It may run on any other version with/without modifications import socket def convert_integer(): data=1234 print "源字节:%s => Long host byte order:%s,Network byte order:%s"\ %(data,socket.ntohl(data),socket.htonl(data)) print "源字节:%s => Short host byte order:%s,Network byte order:%s"\ %(data,socket.ntohs(data),socket.htons(data)) if __name__==‘__main__‘: convert_integer()
时间: 2024-10-06 02:23:08