#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 " % 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()
''' 时间服务器客户端 ''' import socket,struct,sys,time #时间服务器地址 NTP_SERVER='0.asia.pool.ntp.org' #参考1970的时间 TIME1970=2208988800L def sntp_client(): #建立socket对象 client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #SNTP protocol data data = 'x1b' + 47 * ' ' #向时间服务器发送数据 client.sendto(data,(NTP_SERVER,123)) #获取数据和地址 data,address=client.recvfrom(1024) if data: print(address) # t = struct.unpack( '!12I', data )[10] # print(t) t -= TIME1970 print ' Time=%s' % time.ctime(t) if __name__=='__main__': sntp_client()
import socket,sys,argparse ''' 简单的socket客服端 ''' host='localhost' def echo_client(port): #建立套结字 sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #服务地址 server_address=(host,port) #连接服务器 sock.connect(server_address) try: # Send data message = "Test message. This will be echoed" print "Sending %s" % message sock.sendall(message) # Look for the response amount_received = 0 amount_expected = len(message) while amount_received < amount_expected: data = sock.recv(16) amount_received += len(data) print "Received: %s" % data except socket.errno, e: print "Socket error: %s" %str(e) except Exception, e: print "Other exception: %s" %str(e) finally: print "Closing connection to the server" sock.close() ''' 简单的接受数据的服务器端 ''' import socket,sys,argparse host='localhost' data_payload=2048 backlog=5 def echo_server(port): """ 简单的打印屏幕服务 """ #TCP协议的套结字 sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #是否端口重复使用 sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) ################# server_address=(host,port) #绑定IP和端口 sock.bind(server_address) #监听 sock.listen(backlog) while True: #建立连接 client,address=sock.accept() #获取消息 data=client.recv(data_payload) if data: #发送数据 client.send(data) #结束连接 client.close()