标签:
#coding:utf-8 __author__ = ‘similarface‘ #!/usr/bin/env python import socket #二进制和ASCII互转及其它进制转换 from binascii import hexlify def get_remote_machine_info(remote_host): ‘‘‘ 获取根据域名获取IP地址 :param remote_host: 域名 :return:IP地址 ‘‘‘ try: #SimilarFacedeMacBook-Pro:~ similarface$ ping www.python.org #PING python.map.fastly.net (103.245.222.223): 56 data bytes print("%s的IP地址:%s" %(remote_host,socket.gethostbyname(remote_host))) except socket.error,err_msg: print("%s: %s" %(remote_host,err_msg)) def convert_ip4_address(): ‘‘‘ 转化IP地址 ‘‘‘ for ip_addr in [‘127.0.0.1‘,‘192.168.0.1‘]: #IP地址转换为一个32位的网络序列IP地址。 packed_ip_addr=socket.inet_aton(ip_addr) #将一个十进制网络字节序转换为点分十进制IP格式的字符串。 unpacked_ip_addr=socket.inet_ntoa(packed_ip_addr) print "IP地址: %s => 打包: %s, 非打包: %s" %(ip_addr, hexlify(packed_ip_addr), unpacked_ip_addr) def find_service_name(): ‘‘‘ 根据端口获取服务的名称 :return: ‘‘‘ protocolname=‘tcp‘ for port in range(53,22,80): try: print "Port: %s => service name: %s" %(port, socket.getservbyport(port, protocolname)) except Exception,e: print(e) print "Port: %s => service name: %s" %(53, socket.getservbyport(53, ‘udp‘)) def convert_integer(): ‘‘‘ #ntohl()是将一个无符号长整形数从网络字节顺序转换为主机字节顺序。 #将主机数转换成无符号长整型的网络字节顺序。本函数将一个32位数从主机字节顺序转换成网络字节顺序。 :return: ‘‘‘ data=1234 print "原数据: %s => 长主机字节顺序: %s, 长网络字节顺序: %s"%(data, socket.ntohl(data), socket.htonl(data)) print "原数据: %s => 短主机字节顺序: %s, 短网络字节顺序: %s"%(data, socket.ntohs(data), socket.htons(data)) def test_socket_timeout(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print "默认的超时时间: %s" %s.gettimeout() s.settimeout(100) print "当前的超时时间: %s" %s.gettimeout() import sys,socket,argparse def main(): parser=argparse.ArgumentParser(description="Socket 异常处理") parser.add_argument(‘--host‘,action=‘store‘,dest=‘host‘,required=False) parser.add_argument(‘--port‘,action="store",desc=‘port‘,type=int,required=False) parser.add_argument(‘--file‘,action-"store",desc=‘file‘,required=False) given_args=parser.parse_args() host=given_args.host port=given_args.port filename=given_args.file try: s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) except socket.error,e: print("Error creating socket: %s" % e ) sys.exit(1) try: s.connect((host,port)) except socket.gaierror,e: print "Address-related error connecting to server: %s" % e sys.exit(1) except socket.error,e: print "Connection error: %s" % e sys.exit(1) try: s.sendall("GET %s HTTP/1.0\r\n\r\n" % filename) except socket.error, e: print "Error sending data: %s" % e sys.exit(1) while 1: try: buf = s.recv(2048) except socket.error, e: print "Error receiving data: %s" % e sys.exit(1) if not len(buf): break # write the received data sys.stdout.write(buf) if __name__ == "__main__": remote_host=‘www.python.org‘ get_remote_machine_info(remote_host) convert_ip4_address() print(‘------find_service_name------‘) find_service_name() print(‘------convert_integer------‘) convert_integer() print(‘------main------‘) main()
标签:
原文地址:http://www.cnblogs.com/similarface/p/5519809.html