Skip to content Skip to sidebar Skip to footer

Python/socket: How To Send A File To Another Computer Which Is On A Different Network?

The codes below work if the computers are on the same network. However if these computers are on different networks, the connection timed out. The codes of server.py are: #!/usr/bi

Solution 1:

Try this:

server.py:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import socket
import os

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", 12345)) #if the clients/server are on different network you shall bind to ('', port)

s.listen(10)
c, addr = s.accept()
print('{} connected.'.format(addr))

f = open("image.jpg", "rb")
l = os.path.getsize("image.jpg")
m = f.read(l)
c.send_all(m)
f.close()
print("Done sending...")

client.py:

#!/usr/bin/env python3# -*- coding: utf-8 -*-import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("server_public_ip", 12345)) # here you must past the public external ipaddress of the server machine, not that local address

f = open("recieved.jpg", "wb")
data = NonewhileTrue:
    m = s.recv(1024)
    data = m
    if m:
        while m:
            m = s.recv(1024)
            data += m
        else:
            break
f.write(data)
f.close()
print("Done receiving")

note: on your server.py you are waiting for 10 clients but you accept only one connection you shall put the c, addr = s.accept() in a while loop

Update: If the clients/server are behind a rooter then you have to forward the port on the rooter for that connection

Port Forwarding:

Works only WITH python 2.X

i've made myself a script to forward port on every OS but the script it too long you can grab it here

then in server.py:

from port_forwarding import forward_port

and before s = socket.socket ### put

forward_port(port, 'description')

don't forget to put the port_forwarding script in the same folder of sever.py

Post a Comment for "Python/socket: How To Send A File To Another Computer Which Is On A Different Network?"