程式扎記: [ Python 範例代碼 ] Testing TCP connections

標籤

2015年11月25日 星期三

[ Python 範例代碼 ] Testing TCP connections

Source From Here 
Here’s a quick snippet of python code that attempts to establish a TCP connection and reports whether it was successful or not. Netcat is a lot better suited for this role, but sometimes you may not be able to install it. In these situations this little script can come in handy: 
  1. #!/usr/bin/env python  
  2.   
  3. import socket  
  4. import time  
  5. from time import sleep  
  6.   
  7. HOST=""  
  8. PORT=""  
  9. TIMEOUT=1.0  
  10. WAIT = 1  
  11.   
  12. while True:  
  13.     try:  
  14.         s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
  15.         s.settimeout(TIMEOUT)  
  16.         s.connect((HOST, PORT))  
  17.         print "[%s] Connection established" % time.strftime("%H:%M:%S")  
  18.         time.sleep(1)  
  19.         s.close()  
  20.     except:  
  21.         print "[%s] Cannot connect" % time.strftime("%H:%M:%S")  
  22.         sleep(WAIT)  # Sleep in sec before retry  
Supplement 
Python Stdlib - socket — Low-level networking interface 
[ Python 文章收集 ] 時間信息的獲取與表示簡介 
[Python Std Library] Data Types : datetime — Basic date and time types

2 則留言:

  1. 代碼產生器的部份,copy to clipboard 會造成 error.

    回覆刪除
    回覆
    1. Thanks for reminding! That's because the post is directly copy from my local machine and the corresponding js (javascript) isn't being uploaded to google blog. Sorry for inconvenience...^^"

      刪除

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!