Can't connect to python socket server on a different network - python

I made this basic Python 3 socket server in an attempt to learn socket programming. I can connect to it using 'telnet 192.168.x.x 9001' on the same computer, running Ubuntu 16.04, but when I try using my other computer on a different network, Windows 10, on a different network it wont let me connect (when using the computer running Windows 10, I run the serve on Ubuntu).
This is the code I have written.
import socket
from _thread import start_new_thread
host = ""
port = 9001
class Server:
def __init__(self, host, port):
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.server.bind((host, port))
except socket.error as e:
print(str(e))
self.server.listen(10)
def main(self, conn):
while True:
conn.send(str.encode("Enter some text to make uppercase: "))
message = conn.recv(4096)
message = str(message,'utf-8')
conn.send(str.encode(message.upper()))
def run(self):
while True:
conn, addr = self.server.accept()
print("Connection from {}:{:d}".format(addr[0], addr[1]))
start_new_thread(self.main, (conn, ))
my_server = Server(host, port)
my_server.run()

Related

Python connect to an external server using sockets

I am trying to build a connection between a server and one or more clients in Python using sockets. My code works just fine when I connect with a client in the same network, but my goal is to build a program which me and my friend can use, so I want to figure out a way to connect to my server from an external network via the internet.
My server-side code looks like this:
import socket
server = "internal_ip"
port = 5006
serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
serv.bind((server, port))
print(server)
except socket.error as e:
print(e)
serv.listen(2)
while True:
conn, addr = serv.accept()
from_client = ""
while True:
data = conn.recv(4096)
if not data:
break
from_client += str(data)
print(from_client)
conn.send(str.encode("I am SERVER"))
conn.close()
print("Client disconnected")
And this is my client:
import socket
server = "internal_ip"
port = 5006
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client.connect((server, port))
except socket.error as e:
print(e)
while True:
try:
client.send(str.encode("I am CLIENT"))
from_server = client.recv(4096)
#client.close()
print(from_server)
except:
break
client.close()
This works just fine within a network. Then I started testing the code from an external client. I changed the ip to my external ip address which I have found using whatismyipaddress.com, and port number to a different one than I use on the server side.
server = "external_ip"
port = 5007
Then I enabled port forwarding using cmd:
netsh interface portproxy add v4tov4 listenport=5007 listenaddress=external_ip connectport=5006 connectaddress=internal_ip
I get WinError 10060. Tried switching firewall on and off, and allowing these specific ports, but I can't make it work.
Can you help me with my problem please?

Cant run Python UDP server with OOP

i Try to create udp port listener using OOP but i try to start server it not start. In python console it only show
=============RESTART: D:\server.py==================
>>>
this is my code
import threading
import time
import socket
class udpreceive:
def __init__(self,port,ip):
self.port = port
self.ip = ip
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.bind((self.ip, self.port))
def startserver(self):
while True:
time.sleep(1)
data, addr = self.sock.recvfrom(1024)
print (data)
server1 = udpreceive(514,"192.168.1.5")
t1 = threading.Thread(target=server1.startserver)
what is the error? I'm new to OOP and socket programming Thanks

The socket server on ubuntu can't be connected

the code of socket-server and the code of socket-client can run perfectly on my localhost, but when I run the code of socket-server on Ubuntu server, the code of socket-client on my localhost can't connect to Ubuntu server.And the code of socket-client on Ubuntu Server can't connect to my localhost Server.
socket-server.py
import socket
import threading
def bbs(conn):
user_list.append(conn)
try:
while 1:
msg = conn.recv(1024)
if msg:
for user in user_list:
user.send(msg)
except ConnectionResetError:
user_list.remove(conn)
conn.close()
user_list = []
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('0.0.0.0', 18000))
server.listen()
while 1:
conn, addr = server.accept()
t = threading.Thread(target=bbs, args=(conn,))
t.start()
socket-client.py
import socket
import threading
import time
def send_msg():
while 1:
msg = input()
client.send((name + ':' + msg).encode('utf-8'))
def recv_msg():
while 1:
msg = client.recv(1024)
if msg:
try:
print(msg.decode('utf-8'))
time.sleep(1)
except UnicodeDecodeError:
pass
name = input('请输入你的昵称:')
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('10.26.8.132', 18000))
sendmsg_thread = threading.Thread(target=send_msg)
recvmsg_thread = threading.Thread(target=recv_msg)
sendmsg_thread.start()
recvmsg_thread.start()
Server is always wait for connection, Client report an error:
TimeoutError: [WinError 10060] The connection attempt failed because the connecting party did not respond correctly after a period of time or because the connecting host did not respond.
Wang if this works without issue on your localhost, but not over a network connection, it might be a firewall issue on both client & server. You can use 'nc' (netcat) for testing the connection from client to the server.

Send string from mac to raspberry pi wirelessly [duplicate]

This question already has answers here:
Utilising bluetooth on Mac with Python
(2 answers)
Closed 4 years ago.
I am using a mac to try and send a string wirelessly to a raspberry pi using Bluetooth with python. However, I was not able to find an API that works with mac. I have tried options like pybluez and lightblue, but it seems like they don't work with mac. Is there a solution available for this? Bluetooth communication would be preferable, but I am open to other suggestions. Thanks in advance
Updated Answer
Still using netcat approach as below, but this is the sender implemented in Python adapted from this answer and works with the receiver below:
#!/usr/local/bin/python3
import socket
def netcat(host, port, content):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, int(port)))
s.sendall(content.encode())
s.shutdown(socket.SHUT_WR)
while True:
data = s.recv(4096)
if not data:
break
print(repr(data))
s.close()
netcat('192.168.0.131', 40000, 'Hi')
Here is a matching listener/server as implemented here that works with the sender above or the simple netcat sender from the command line.
#!/usr/bin/env python
import socket
import select
class SocketServer:
""" Simple socket server that listens to one single client. """
def __init__(self, host = '0.0.0.0', port = 2010):
""" Initialize the server with a host and port to listen to. """
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.host = host
self.port = port
self.sock.bind((host, port))
self.sock.listen(1)
def close(self):
""" Close the server socket. """
print('Closing server socket (host {}, port {})'.format(self.host, self.port))
if self.sock:
self.sock.close()
self.sock = None
def run_server(self):
""" Accept and handle an incoming connection. """
print('Starting socket server (host {}, port {})'.format(self.host, self.port))
client_sock, client_addr = self.sock.accept()
print('Client {} connected'.format(client_addr))
stop = False
while not stop:
if client_sock:
# Check if the client is still connected and if data is available:
try:
rdy_read, rdy_write, sock_err = select.select([client_sock,], [], [])
except select.error:
print('Select() failed on socket with {}'.format(client_addr))
return 1
if len(rdy_read) > 0:
read_data = client_sock.recv(255)
# Check if socket has been closed
if len(read_data) == 0:
print('{} closed the socket.'.format(client_addr))
stop = True
else:
print('>>> Received: {}'.format(read_data.rstrip()))
if read_data.rstrip() == 'quit':
stop = True
else:
client_sock.send(read_data)
else:
print("No client is connected, SocketServer can't receive data")
stop = True
# Close socket
print('Closing connection with {}'.format(client_addr))
client_sock.close()
return 0
def main():
server = SocketServer(port=40000)
server.run_server()
print('Exiting')
if __name__ == "__main__":
main()
Original Answer
Try using netcat or nc.
On RaspberryPi, listen on port 40,000 using TCP:
nc -l 40000
On Mac, assuming RaspberryPi has IP address of 192.168.0.131:
echo "hi" | /usr/bin/nc 192.168.0.131 40000
RaspberryPi shows:
hi

Python Server running as a Windows Service doens't accept connexion

Most of all, my question is pretty similar to the following : Cannot access Python server running as Windows service. I tried the solution but it doesn't solve my problem.
I was able to connect a client and a server by using the Python Socket Tutorial :
# Echo server program
import socket
HOST = '' # Symbolic name meaning the local host
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
# Echo client program
import socket
HOST = 'daring.cwi.nl' # The remote host
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)
and It worked like a charm, then I coded the following Windows Service :
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import logging
import sys
class AppServerSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "PySvc"
_svc_display_name_ = "PySvc"
_svc_description_ = "PySvc"
def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
logging.basicConfig(filename='C:/test.log',
level =logging.DEBUG,
format ='%(asctime)s %(message)s',
filemode='w')
rc = None
self.HOST = '' # Symbolic name meaning the local host
self.PORT = 50007 # Arbitrary non-privileged port
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s.bind((self.HOST, self.PORT))
logging.debug("BIND")
self.s.listen(1)
logging.debug("LISTENED")
self.conn, self.addr = self.s.accept()
logging.debug("ACCEPT")
logging.debug("connected to " + str(self.addr))
self.s.setblocking(1)
logging.debug("set blocking")
# if the stop event hasn't been fired keep looping
while rc != win32event.WAIT_OBJECT_0:
# block for 5 seconds and listen for a stop event
rc = win32event.WaitForSingleObject(self.hWaitStop, 5000)
self.main()
def main(self):
pass
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)
But the connexion is never accepted by the service. the log contains :
2018-03-19 16:37:48,967 BIND
2018-03-19 16:37:48,967 LISTENED
If I do a netstat :
NETSTAT -an | find /i "listening"
I find the following line, which show that the server is listening :
TCP 0.0.0.0:50007 0.0.0.0:0 LISTENING
Can someone explain me why it doesn't work ?

Categories

Resources