In Python, I made a client.py and server.py with some simple socket code.
server.py:
import socket
HEADERSIZE = 10
PORT = 1235
ADDR = "192.168.198.1" # this is my local IP found from ipconfig in cmd
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((ADDR, PORT))
s.listen(5)
while True:
client, address = s.accept()
print(f'Connection from {address} established')
msg = "Hello Client"
msg = f'{len(msg):<{HEADERSIZE}}'+msg
client.send(bytes(msg, "utf-8"))
client.py:
import socket
HEADERSIZE = 10
ADDR = "67.xxx.xxx.xx" # my public IP found from whatsmyip.com
PORT = 1235
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ADDR, PORT))
while True:
full = ''
new = True
while True:
msg = s.recv(16)
if new:
msglen = int(msg[:HEADERSIZE])
new = False
full += msg.decode("utf-8")
if len(full) - HEADERSIZE == msglen:
new = True
full = ''
print(full)
Previously, I had the addresses in both programs set to socket.gethostname() because I was working on my computer only. When I sent the client to my friend to test it out with the updated information you see here, I get this error code:
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
The same thing happens when I run it on my computer.
I'm very new to sockets / networking, so I apologize if I'm missing something obvious, but I've been having issues with this and any help is appreciated
Related
trying to ping a server from a client like this:
#server
import socket
HOST = ''
PORT = 50007
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.sendall(data)
conn.close()
#client
import socket
HOST = ''
PORT = 50007
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(f"Received {data!r}")
But there is a hang on server side after the s.accept(), and ...[111] connection refused on the client side.
BTW: I am on a windows machine for the server, and pinging from a linux machine. They are connected with an ethernet cable. I have also set a static address for the linux machine, from the windows machine.
Another thing, is that the exact same code works in the opposite direction ...
Could someone help?! Stuck on this for ages!
(Using Python 3) I am trying to connect server and client and symply send a message from one to another but I don't know why I get this strange error: OSError: [WinError 10057]. Does anyone know why it happened? I did a bit of reaserch but didn't find anything, I think I made an error when making global variables, or is it somenthing with message encoding and decoding?
Here is my full error:
File "server_side.py", line 34, in
shell()
File "server_side.py", line 6, in shell
s.send(command.encode('utf-8'))
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a
sendto call) no address was supplied
Here is my server_side code:
import socket
def shell():
command = input('[+] Insert command: ')
s.send(command.encode('utf-8'))
message = target.recv(1024)
print(message.decode('utf-8'))
s = ''
target = ''
ip = ''
def server():
global s
global target
global ip
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
s.bind(('192.168.1.109', 54321))#target ip, port more bit isti
s.listen(5)
print('[+] Listening for connections')
target, ip = s.accept()
print('[+] Connection established from: %s' %str(ip))
server()
shell()
And this is my client_side code:
import socket
def shell():
command = sock.recv(1024)
message = 'Hello there'
sock.send(message.encode('utf-8'))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('192.168.1.109', 54321)) #home ip
shell()
sock.close()
My command input on server_side example vould be the word : Hello, or somenthing like that.
You have to put the shell() function in a infinite loop, and you have to run the server_side code and then the client_side code.
Here is a bit changed code:
Server side code:
import socket
def shell():
command = input('[+] Insert command: ')
s.send(command.encode('utf-8'))
message = target.recv(1024)
print(message.decode('utf-8'))
s = ''
target = ''
ip = ''
def server():
global s
global target
global ip
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
s.bind(('192.168.1.109', 54321))#target ip, port more bit isti
s.listen(5)
print('[+] Listening for connections')
target, ip = s.accept()
print('[+] Connection established from: %s' %str(ip))
while True:
server()
shell()
s.close()
Client side code:
import socket
def shell():
command = sock.recv(1024)
message = 'Hello there'
sock.send(message.encode('utf-8'))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('192.168.1.109', 54321)) #home ip
while True:
shell()
sock.close()
i have an assignment to make a web server on the TCP by using LAN , the project is to make a request to localhost on port 80 and present "hi" in a browser and to present "404 not found" if the request is wrong, i have a problem with being port 80 is busy, it stop working when using any port but 80, the hint from the assignment is "If you run your server on a host that already has a Web server running on it, then you should use a different port than port 80 for your Web server." and my code is :
from socket import *
import os
def test():
serverPort = 80
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('', serverPort))
serverSocket.listen(1)
print("web server on port", serverPort)
while True:
print("ready to serve")
connectionSocket, addr = serverSocket.accept()
try:
message = connectionSocket.recv(1024)
print(message)
filename = message.split()[1]
print(filename[1:])
print(filename, '||', filename[1])
f = open(filename[1:])
outputdata = f.read()
connectionSocket.send(outputdata.encode())
connectionSocket.close()
except Exception:
print("404 Not Found")
connectionSocket.send("""404 Not Found\r\n""".encode())
pass
pass
if __name__ == "__main__":
test()
simply you need to check if port already in use or not
def check(port):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
return s.connect_ex(('localhost', serverPort)) == 0
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.
Note : This problem has been completely solved, as was am running client.py before server.py
Just got started with socket programming, I have created the below code and expecting to print some byte message, but it isn't doing that.
I just want to make the message available for any person on any
machine. But it's refusing by the machine to do that.
Here is my code:
server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 12048
s.bind((socket.gethostname(), port))
s.listen()
while True:
c, addr = s.accept()
print("Got connection from", addr)
c.send(bytes("Thank you", "utf-8"))
client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 12048
s.connect(('192.168.0.1', port))
msg = s.recv(1024)
print(msg.decode("utf-8"))
Some images to better explain my errors:
Any help would be appreciated!!!
It looks like in the server.py script you use s.bind((socket.gethostname(), port)) where socket.gethostname() is a hostname, but in the client.py script you use s.connect(('192.168.0.1', port)) where '192.168.0.1' is the hostname you are trying to connect.
I think there you have socket.gethostname() != '192.168.0.1' and that's the problem.
Also, you can bind to all available IP addresses on the host using this solution Python socket bind to any IP?
Let's use listen_ip = socket.gethostbyname(socket.gethostname()) for connection since socket.gethostname() may return hostname instead of IP and it will not be solved by python dns resolver in local network if it was local name, not DNS.
and use it later as s.bind((listen_ip, port)) and s.connect((listen_ip, port))
After some debugging I've got a working solution for you
There are the scripts required.
server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostbyname(socket.gethostname())
port = 12_048
s.bind((host, port))
s.listen()
print("Server listening # {}:{}".format(host, port))
while True:
c, addr = s.accept()
print("Got connection from", addr)
c.send(bytes("Thank you", "utf-8"))
client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '192.168.1.162' # The IP printed by the server must be set here
# or we can set it using env variable named SERVER_IP
if 'SERVER_IP' in os.environ:
host = os.environ['SERVER_IP']
port = 12048
print("Connecting to {}:{}".format(host, port))
s.connect((host, port))
msg = s.recv(1024)
print(msg.decode("utf-8"))
In a chat conversation we concluded that the hardcoded IP in the question is not the correct one. This solution does have the IP he needed but it will be different in each case. Remeber that server.py needs to be launched first, and when you see the printed Server listening # IP:12048, write that IP in client.py and launch it. Client does need to be launched after seeing that line even if you already know the IP, as the server needs some time to be ready and the client will crash if it tries to connect to the server while it is not ready.
server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostbyname(socket.gethostname())
port = 12048
s.bind((host, port))
s.listen()
print("Server listening # {}:{}".format(host, port))
while True:
c, addr = s.accept()
print("Got connection from", addr)
c.send(bytes("Thank you", "utf-8"))
client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '192.168.1.162' # The IP printed by the server must be set here
port = 12048
print("Connecting to {}:{}".format(host, port))
s.connect((host, port))
msg = s.recv(1024)
print(msg.decode("utf-8"))