cannot downloads file using python socket programming
<p>i want to download a file from this url (<a href="http://justlearn.16mb.com/a.jpg" rel="nofollow">http://justlearn.16mb.com/a.jpg</a>) using python sockets only and i dont know how to do it as i am a novice in python.</p>

<p>Actually my main goal is to download files in half part using wifi connection and other half part using ethernet connection.</p>

<p>Thank you in advance for helping.</p>

<pre><code>import os
import socket

tcpd = 'http://justlearn.16mb.com/a.jpg'
portd = 80
ipd = socket.gethostbyname('http://justlearn.16mb.com/a.jpg')
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((tcpd,portd))



BUFFER_SIZE = 1024

with open('a.jpg', 'wb') as f:
    print ('file opened')
    while True:
        #print('receiving data...')
        data = s.recv(1024)
        #print('data=%s', (data))
        if not data:
            f.close()
            break
        # write data to a file
        f.write(data)

print('Successfully get the file')
s.close()
print('connection closed')     
</code></pre>

<p>You might want to try something like this instead. I am unable to test it due to a proxy, but the example should help you in the right direction. Using sockets directly would make this unnecessarily difficult.</p>

<pre><code>#! /usr/bin/env python3
import http.client


def main():
    connection = http.client.HTTPConnection('justlearn.16mb.com')
    connection.request('GET', '/a.jpg')
    response = connection.getresponse()
    if response.status != 200:
        raise RuntimeError(response.reason)
    with open('a.jpg', 'wb') as file:
        while not response.closed:
            buffer = response.read(1 &lt;&lt; 12)
            if not buffer:
                break
            file.write(buffer)
    connection.close()


if __name__ == '__main__':
    main()
</code></pre>

<p>Here is another example that is shorter and uses the <code>urlopen</code> function from the <code>urllib.request</code> package instead. The code is simpler since the HTTP code is handled in the background instead.</p>

<pre><code>#! /usr/bin/env python3
from urllib.request import urlopen


def main():
    with urlopen('http://justlearn.16mb.com/a.jpg') as source, \
            open('a.jpg', 'wb') as destination:
        while True:
            buffer = source.read(1 &lt;&lt; 12)
            if not buffer:
                break
            destination.write(buffer)


if __name__ == '__main__':
    main()
</code></pre>

python sockets wifi ethernet download-manager