communication between two computers via Python socket in a LAN failed - python

Two computers in a LAN connecting to a wireless router, one IP address is 192.168.1.106 (server), the other one is 192.168.1.107 (client), the gateway on both computer is 192.168.1.1 (the router itself).
The two computer can ping each in two directions which means there should be no problem with routing and the router itself. But I failed when I tried to use Python UDP socket, the server cannot get any information from the client, and same happened when I change the ip address. (But it works fine when server and client are on a same computer using local ip address, so the code is should be ok)
I am using the following code:
server:
import socket
address = ('192.168.1.106', 5678) # the server listening on address 192.168.1.106
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(address)
while True:
data, addr = s.recvfrom(2048)
if data == "empty":
print "no data from client"
else:
print "received:", data, "from", addr
s.close()
client:
import socket
address = ('192.168.1.106', 5678) # the client send to address 192.168.1.106
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
msg = raw_input()
if not msg:
msg = "empty"
s.sendto(msg, address)
s.close()

Did you open the UDP port on the firewall on both comoutera?

Related

Python socket connection not working over Local Network

I'm trying to get two computers (my PC and my laptop) to communicate over the Local Network using the Socket module in python.
This is the Server side code running on my PC (connected via LAN):
import socket
HOST = '192.168.1.3' #local PC IP
print(HOST)
PORT = 8080 # Port to listen on (non-privileged ports are > 1023)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
print(data)
if not data:
break
conn.sendall(data)
And this is the Client side code, running on my Laptop (connected over WiFi):
import socket
TCP_IP = '192.168.1.3'
TCP_PORT = 8080
BUFFER_SIZE = 1024
MESSAGE = b"Hello, World!"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()
print("received data:", data)
The thing is: when I execute both codes, the Server side stays idle waiting for a connection and the Client side, after a while stops and returns the following timeout error:
Traceback (most recent call last):
File "C:\Users\...\client.py", line 13, in <module>
s.connect((TCP_IP, TCP_PORT))
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
I can't understand why it won't connect from another device in the same network while it works perfectly if I execute the Client code on the same machine as the Server, even if when I run netstat -an in the CMD I can see the computer listening on that port:
TCP 192.168.1.3:8080 0.0.0.0:0 LISTENING
I tough it had something to do with the port forwarding so I tried playing around with it but I'm having troubles with that too (the ports seem to remain closed).
I really don't know what to do next, if you have some advice or know something else I could try please reply.
It actually was a firewall problem, I just needed to disable the windows defender firewall for the local network and now everything is working fine
In Windows 10, I had to open the port I was using for the socket, and it worked for me.
Here is a link to the instructions.
You're listening and connecting to the same IP - you need to listen to the client's IP(or just any IP with the correct port number) on the server and connect to the server's IP on the client.
For example, if the client's IP is 1.2.3.4 and the server's is 1.2.3.5, then
# server side
s.bind(('1.2.3.4', 8080)) # CLIENT_IP = '1.2.3.4'; PORT = 8080
# can also be s.bind(('0.0.0.0', 8080)) if you want multiple clients to connect.
# client side
s.connect(('1.2.3.5', 8080)) # SERVER_IP = '1.2.3.5'; PORT = 8080

How to send messages to a remote computer using python socket module?

I'm trying to send a message from a computer to a another computer that is not connected to the other computer local network.
I did port forwarding (port 8080, TCP) and I didn't manage to get the remote computer to connect and to send the message.
when i try to connect it's just getting stuck on the connect method (client).
I also need to mention that I'm open to change anything in the router settings.
the client code (remote computer):
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("%My public IP address%", 8080))
msg = s.recv(1024)
msg = msg.decode("utf-8")
print(msg)
the server code:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("192.168.0.2", 8080))
s.listen(5)
while True:
clientsocket, address = s.accept()
print(f"Connection from {address} has been established.")
clientsocket.send(bytes("Hey there!!", "utf-8"))
clientsocket.close()
From my understanding, your aim is to connect to a server from a remote computer and send a message from the server to the client. As such, all it requires is the client to connect to the external-facing IP address of your server. Once that is done, router simply forwards the traffic according to the port forwarding rules.
Server:
import socket
def Main():
host = '10.0.0.140'
port = 42424
s = socket.socket()
s.bind((host, port))
s.listen(1)
c, addr = s.accept()
while True:
data = c.recv(1024)
if not data:
break
data = str(data).upper()
c.send(data)
c.close()
if __name__ == '__main__':
Main()
Client:
import socket
def Main():
host = '10.0.0.140' #The host on your client needs to be the external-facing IP address of your router. Obtain it from here https://www.whatismyip.com/
port = 42424
s = socket.socket()
s.connect((host,port))
message = raw_input("->")
while message != 'q':
s.send(message)
data = s.recv(1024)
message = raw_input("->")
s.close()
if __name__ == '__main__':
Main()
Also do note that, When connecting to a server behind a NAT firewall/router, in addition to port forwarding, the client should be directed to the IP address of the router. As far as the client is concerned, the IP address of the router is the server. The router simply forwards the traffic according to the port forwarding rules.

Trying to make a server with sockets in python

I'm trying to make a chat app in Python and I'm having some trouble.
I made a server on which I can connect successfully by using the local IP address. However, when I try to connect to it on an another device with my public IP address, there seems to be a timeout, no errors occur and it's continuously trying to connect.
Edit: I've already set up port-forwarding for my IPv4 address. And the client is using the public IP.
server.py:
import socket
s = socket.socket()
host = socket.gethostbyname(socket.gethostname())
port = 2000
s.bind((host, port))
print("Server started, waiting for incoming connections")
s.listen(5)
connection, address = s.accept()
print("New connection from", address)
while True:
data = connection.recv(1024).decode()
print("received:", data)
ret = data + "+++++++"
connection.send(ret.encode())
client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = #my public ip address from whatsmyip.com
port = 2000
s.connect((host, port))
print("Connected.")
while True:
message = input("msg: ")
s.send(message.encode())
data = s.recv(1024).decode()
print(data)
Well, first of all, is your server in a network with other devices? If you have a router there, the IP you see in whatsmyip.com is the router's, not your computer's, IP. So you'd be trying to connect to it.
You can check that with the command netstat.

Python3 TCP Server not seeing incoming messages from external device

I want to create a small TCP server that takes incoming TCP connections from a device that is hooked up via Ethernet to my computer.
The physical port for that has the IP 192.168.1.100 statically assigned to it.
The scripts I use as a client and server are listed at the bottom.
The setup works if I want to send messages between the python scripts. However, I am unable to receive anything from the external device (screenshot from Wireshark capture below). From what I have read I can define an interface to listen to by defining its IP. So I defined the IP of the interface as the host variable. However, I do not receive anything in my script but the messages sent by the other script. I had a similar situation already here on stackoverflow. I thought that defining the correct IP as the host would resolve this issue but it did not.
I am also having a hard time capturing the traffic between the two scripts with Wireshark at all. They did not show up anywhere.
I need to pick up these connections on the eth0 interface with the static IP 192.168.1.100:
tcp_server.py
import socket
# create a socket object
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
# host = socket.gethostname()
host = "192.168.1.100"
port = 9002
# bind to the port
serverSocket.bind((host, port))
# queue up to 5 requests
serverSocket.listen(5)
while True:
# establish a connection
clientSocket, addr = serverSocket.accept()
print("Got a connection from %s" % str(addr))
msg = 'Thank you for connecting' + "\r\n"
clientSocket.send(msg.encode('ascii'))
clientSocket.close()
and this as a client:
tcp_client.py
import socket
# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
# host = socket.gethostname()
host = "192.168.1.100"
port = 9002
# connection to hostname on the port.
s.connect((host, port))
# Receive no more than 1024 bytes
msg = s.recv(1024)
s.close()
print(msg.decode('ascii'))

UDP client cannot talk through an external IP address

I am running a UDP server and client (python). When within the same local network, the client is able to talk to the server. However when the server IP address is set to IP address of the router (which has UDP port forwarding to the server), the client is not able to talk with the server at all. I am wondering if anyone can point out why this works within the local network (on different machines) but I cannot make the client connect to the server using external IP address of the router to which both the client and server are connected.
The code for the client
import socket
import sys
HOST, PORT = "<IP address of router which is port forwarded to server>", 5000
data = " Hello from Client" #.join(sys.argv[1:])
# SOCK_DGRAM is the socket type to use for UDP sockets
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# As you can see, there is no connect() call; UDP has no connections.
# Instead, data is directly sent to the recipient via sendto().
sock.sendto(data + "\n", (HOST, PORT))
received = sock.recv(1024)
print "Sent: {}".format(data)
print "Received: {}".format(received)
Code for the server
import SocketServer
class MyUDPHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = self.request[0].strip()
socket = self.request[1]
print "{} wrote:".format(self.client_address[0])
print data
socket.sendto(data.upper(), self.client_address)
if __name__ == "__main__":
HOST, PORT = "<local IP address of server", 5000
server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler)
server.serve_forever()
OK i figured out what was going on.
Router is connected to two computers - Computer A and Computer B. Computer A can talk to Computer B using the local network (UDP server client). However when Computer A (UDP client) sends data to Computer B (UDP server) using the Router IP address (external IP address) with the router port forwarding to Computer B, it was not working. Apparently the server will only accept connections that originate outside the local network when the client uses the external IP address

Categories

Resources