Bence
Bence

Reputation: 109

Why Python Socket works only on local network?

I'm trying to send a text file trhough Python sockets and it works but only on local network. Why is that?(I'm working with Python 3.6) This is the server.py:

import socket

HOST = '0.0.0.0'
PORT = 80
ADDR = (HOST,PORT)
BUFSIZE = 4096

print(socket.gethostbyname(socket.gethostname()))
serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

serv.bind(ADDR)
serv.listen(5)

print ('listening ...')

while True:
  conn, addr = serv.accept()
  print ('client connected ... ', addr)
  myfile = open('asd.txt', 'w')

  while True:
    data = conn.recv(BUFSIZE)
    if not data: break
    myfile.write(data.decode("utf-8"))
    print ('writing file ....')

  myfile.close()
  print ('finished writing file')
  conn.close()
  print ('client disconnected')

This is the client.py:

import socket

HOST = '192.168.2.109' 
PORT = 80
ADDR = (HOST,PORT)
BUFSIZE = 4096
textfile = "C:/Users/Public/asd.txt"

bytes = open(textfile, "r").read()

print (len(bytes))

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect_ex(ADDR)


client.send(bytes.encode())

client.close()

I've tried this and it worked on local network, but when I sent to my friend the client to try it, it just printed out the bytes but didn't connect to my server.(The server was running on my pc)

Upvotes: 0

Views: 2106

Answers (1)

Pratik Kumar
Pratik Kumar

Reputation: 2231

If the client and host are connected to the same network(LAN) i.e through same router or a hotspot, then the above code will work. If you want to do something like, run server.py on a PC connected to your WiFi and run client.py on a laptop connected through dongle you will have to use port-forwarding.

Upvotes: 2

Related Questions