Python socket 函數 getaddrinfo

來源:互聯網
上載者:User
# -*- coding: cp936 -*-socket.getaddrinfo(host,  port, family=0, socktype=0, proto=0, flags=0)#根據給定的參數host/port,相應的轉換成一個包含用於建立socket對象的五元組,#參數host為網域名稱,以字串形式給出代表一個IPV4/IPV6地址或者None.#參數port如果字串形式就代表一個服務名,比如“http”"ftp""email"等,或者為數字,或者為None#參數family為地主族,可以為AF_INET  ,AF_INET6 ,AF_UNIX.#參數socketype可以為SOCK_STREAM(TCP)或者SOCK_DGRAM(UDP)#參數proto通常為0可以直接忽略#參數flags為AI_*的組合,比如AI_NUMERICHOST,它會影響函數的傳回值#附註:給參數host,port傳遞None時建立在C基礎,通過傳遞NULL。#該函數返回一個五元組(family, socktype, proto, canonname, sockaddr),同時第五個參數sockaddr也是一個二元組(address, port)# Echo server programimport socketimport sysHOST = None               # Symbolic name meaning all available interfacesPORT = 50007              # Arbitrary non-privileged ports = Nonefor res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,                              socket.SOCK_STREAM, 0, socket.AI_PASSIVE):    af, socktype, proto, canonname, sa = res    try:        #根據getaddrinfo()的返回資訊初始化socket        s = socket.socket(af, socktype, proto)    except socket.error, err_msg:        print err_msg #回顯異常資訊        s = None        continue    try:        #sa是(host,port)的二元組        s.bind(sa)        #監聽用戶端請求        s.listen(1)    except socket.error, err_msg:        print err_msg        s.close()        s = None        continue    breakif s is None:    print 'could not open socket'    sys.exit(1)    conn, addr = s.accept()print 'Connected by', addrwhile 1:    data = conn.recv(1024)# 2)接受資料    if not data: break    conn.send(data)# 3)並返回2中接受到得資料conn.close()# Echo client programimport socketimport sysHOST = 'daring.cwi.nl'    # The remote hostPORT = 50007              # The same port as used by the servers = Nonefor res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):    af, socktype, proto, canonname, sa = res    try:        s = socket.socket(af, socktype, proto)    except socket.error, msg:        s = None        continue    try:        s.connect(sa)    except socket.error, msg:        s.close()        s = None        continue    breakif s is None:    print 'could not open socket'    sys.exit(1)    s.sendall('Hello, world')# 1)發送資料data = s.recv(1024)# 4)接受伺服器回顯的資料s.close()print 'Received', repr(data) #列印輸出

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.