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

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.

Related

Please help me in socket programming in python

Problem while making connection with server.
server side:
import socket
import threading
import sys
ip = "let ip address of server, cant type real one for security purposes, example: 1.2.3.4"
port = 9999
def make_socket(ip, port):
global server
try:
server = socket.socket()
server.bind((ip, port))
except:
make_socket(ip, port)
def handle_client(conn, addr):
print(f"Connected with {addr}\n")
connected = True
while connected:
msg = conn.recv(1024).decode("utf-8")
if msg == "exit()":
connected = False
if len(msg) > 0:
print(f"CLIENT: {msg}")
if connected:
msg = input("You: ")
if len(msg) > 0:
conn.send(msg.encode("utf-8"))
conn.close()
def make_connection():
server.listen(2)
while True:
conn, addr = server.accept()
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
print(f"ACTIVE CONNECTIONS:{threading.activeCount() - 1}")
print("SERVER INITIATED.")
make_socket(ip, port)
make_connection()
client side:
import socket
ip = "same address as written in server side, example: 1.2.3.4"
port = 9999
client = socket.socket()
client.connect((ip, port))
def send(msg):
message = msg.encode("utf-8")
client.send(message)
run = True
while run:
msg = input("You: ")
if msg == "exit()":
send(msg)
run = False
else:
send(msg)
print(f"Server: {client.recv(100).decode('utf-8')}")
It runs as expected in the same pc.
But when I am running client script and server script in 2 different pcs, they are not connecting. Even though the address is same. I have to type the ip address of server in server.bind and client.connect, right? They both should be same, right?
The IP address you pass to client.connect() should be the IP address of the computer where the server is running (if it's the same computer as where the client is running, you can just pass 127.0.0.1 as that address always means localhost). For the bind() call I recommend passing in '' (i.e. an empty string) as the address, so that your server will accept incoming connections from any active network interface. You only need to pass in an explicit IP address to bind() if you want limit incoming connections to only those coming through the local network card that is associated with the specified IP address.

Create a socket server using python, and access it from another network\country

How can I create a socket server, and access it from another network\country? I create a server using java. I want to connect the server from another network (like a hotel's wi-fi)
How can I do that?
My python server:
def start():
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((socket.gethostname(), 2201))
print("Waiting for connection...\n")
while True:
server.listen()
(client, (ipNum, portNum)) = server.accept()
message = str(client.recv(32).decode())
if(message != ""):
print("Client: " + message)
Command(message.lower())
print("Server: " + BackMessage)
else:
time.sleep(0.05)
start() # Start the server
Python client:
import socket
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 2001 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
It's not working when I switch connections only when I'm in the same network with the server. How can I make it work?
My reputation is not enough to add a comment, so I put an answer here.
If server locate in a local area network, it cannot be found be a client in another local area network.
You should put the server at the WAN(Wide Area Network) or use NAT(Network Address Translation) + nat traversal.

ConnectionRefusedError when trying to host python socket server on raspberry pi

I'm trying to make a basic python networking program. All I'm trying to do is send strings of text back and forth between the server and the client. I'm trying to host the server on my Raspberry Pi, and connect with a client on Windows 10. The program works great locally on my computer, but when I try to connect to my server, it gives me ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it. My server code is as follows:
import socket # Import socket module
import netifaces as ni
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port))
#host_ip = ni.ifaddresses('wlan0')[ni.AF_INET][0]['addr']
host_ip = "bruh?"
print("Server started! \nHostname: " + host + " \nIP: " + host_ip + " \nPort: " + str(port))
s.listen() # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print('Got connection from', addr)
output = "Welcome to the server!".encode()
c.send(output)
c.close()
Client code:
import socket
s = socket.socket()
host = 192.168.1.21
port = 12345
s.connect((host, int(port)))
noResponse = False
serverResponse = s.recv(1024).decode()
print(serverResponse)
s.close()
Does anyone know what my problem is? Thanks.
There may be a few reasons you are getting a ConnectionRefusedError, please try the following:
Check that no firewall is blocking your connection.
Double-check the server IP, if it is wrong you may get this error.
Try to use Hercules to check the connection.
Also, I would change the code as follow:
Server:
import socket
HOST = '' # localhost
PORT = # IMPORTANT !! Do not use reserved ports
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind((HOST, PORT))
sock.listen()
conn, addr = sock.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
print('Data: ',data)
conn.sendall('RT')
Client:
import socket
HOST = '' # server IP address
PORT = # server port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect((HOST, PORT))
sock.sendall('Hello, I am the Client')
data = sock.recv(1024)
print('Received', data)
By doing this you are using a TCP connection and you can test your code with different TCP server and client emulators.

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.

communication between two computers via Python socket in a LAN failed

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?

Categories

Resources