生活随笔
收集整理的這篇文章主要介紹了
TFTP协议下载服务器指定文件夹内的图片
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
使用TFTP協(xié)議(Trivial File Transfer Protocol,簡單文件傳輸協(xié)議)下載服務器指定文件夾內的圖片
from socket
import *
import struct
from icecream
import ic
import os
import randomos
.chdir
(r
'D:\百戰(zhàn)python\Python網(wǎng)絡與并發(fā)編程——網(wǎng)絡\tftp模擬下載的圖片')
path
= os
.getcwd
()
ic
(path
)
file_list
= os
.listdir
(path
)
ic
(file_list
)
filename
= random
.choice
(file_list
)
ic
(filename
)
ic
(gethostname
())
ic
(gethostbyname
('mac-PC'))
ic
(gethostbyname
(gethostname
()))
server_ip
= gethostbyname
(gethostname
())
ic
(server_ip
)
send_data
= struct
.pack
('!H%dsb5sb' % len(filename
), 1, filename
.encode
(), 0, 'octet'.encode
(), 0)
s
= socket
(AF_INET
, SOCK_DGRAM
)
s
.sendto
(send_data
, (server_ip
, 69))
f
= open(r
'C:/Users/mac/PycharmProjects/pythonProject/myproject01/venv/第三章網(wǎng)絡/{}'.format(filename
), 'ab')
n
= 1
while True: receive_data
= s
.recvfrom
(1024) if n
== 1:ic
(receive_data
)operation_code
, block_num
= struct
.unpack
('!HH', receive_data
[0][:4]) rand_port
= receive_data
[1][1] print(operation_code
, block_num
, rand_port
, len(receive_data
), len(receive_data
[0]))if int(operation_code
) == 5: print('文件不存在')breakf
.write
(receive_data
[0][4:]) if len(receive_data
[0]) < 516: ic
(receive_data
)print(f
'數(shù)據(jù)接收{n}次,完成下載,文件的字節(jié)數(shù)為{514*(n-1)+len(receive_data[0])-2}') ic
(os
.path
.getsize
(filename
)) breakack_data
= struct
.pack
('!HH', 4, block_num
) s
.sendto
(ack_data
, (server_ip
, rand_port
)) n
+= 1
運行結果:
總結
以上是生活随笔為你收集整理的TFTP协议下载服务器指定文件夹内的图片的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內容還不錯,歡迎將生活随笔推薦給好友。