I am able to execute the client-server programs in Python IDLE and in PyCharm but I am stuck while executing the same program on Google Colab.
The sample server code is:
s = socket.socket()
print("Socket Created")
s.bind(('localhost',9999))
s.listen(3)
print("Waiting for a Connection !!")
while True:
c, addr = s.accept()
name = c.recv(1024).decode()
print("Connected with :",addr, " ", name)
c.send(bytes("Welcome to Socket Programming",'utf-8', name))
c.close()
The sample client code is:
c = socket.socket()
c.connect(('localhost', 9999))
name = input("Enter your name: ")
c.send(bytes(name,'utf-8'))
print(c.recv(1024).decode())
On Google Colab, I pasted these codes in different notebooks and ran the server code first. I got the following error:
<ipython-input-1-0b55cff963bc> in <module>()
1 import socket
2 c = socket.socket()
----> 3 c.connect(('localhost', 9999))
4
5 name = input("Enter your name: ")
ConnectionRefusedError: [Errno 111] Connection refused
Then, I pasted the client code in the same notebook but in different code shells then I am not getting any output. Even after searching on Google, I am not able to find the solution to my problem. What wrong am I doing?
Related
I am working on a chat app using sockets in python3 and I have two files server.py and client.py and when I run server.py it runs perfectly fine but when I try to connect to server.py using client.py it returns following error:
Traceback (most recent call last):
File "client.py", line 24, in <module>
read_sockets,write_socket, error_socket = select.select(sockets_list,[],[])
OSError: [WinError 10038] An operation was attempted on something that is not a socket
and I did a bit of research and tried things like changing some stuff but that also failed.
Code for both the files:
server.py :
# Imports and initialization
import socket
from colorama import init, Fore, Style
import sys
import threading
init()
quit_msg = '!quit'
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Checking arguments and further code
if len(sys.argv) != 3:
print(Fore.RED + "[*] Correct usage: script, IP address(host), port number(room)")
sys.exit()
host = str(sys.argv[1])
port = int(sys.argv[2])
server.bind((host, port))
server.listen()
list_of_clients = []
def client_thread(conn , addr):
print(Fore.GREEN + "[+] Welcome to this room")
while True:
try:
message = conn.recv(2048)
if message:
print(Fore.YELLOW + f"[{addr[0]}" + Fore.GREEN + f"{message}")
message_to_send = Fore.YELLOW + f"[{addr[0]}" + Fore.GREEN + f"{message}"
brodcast(message_to_send, conn)
else:
remove(conn)
except:
continue
def brodcast(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(Fore.CYAN + f"[ {addr} ] connected")
thread = threading.Thread(target=client_thread, args=(conn, addr))
conn.close()
server.close()
client.py:
# Imports and intilization
import socket
import sys
import select
from colorama import init, Fore, Style
init()
quit_msg = '!quit'
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if len(sys.argv) != 3:
print(Fore.RED + "[*] Correct usage: script, IP address(host), port number(room)")
sys.exit()
host = str(sys.argv[1])
port = int(sys.argv[2])
client.connect((host, port))
while True:
sockets_list = [sys.stdin, client]
read_sockets,write_socket, error_socket = select.select(sockets_list,[],[])
for socks in read_sockets:
if socks == client:
message = socks.recv
print(message)
else:
message = sys.stdin.readline()
client.send(message)
sys.stdout.write("<You>")
sys.stdout.write(message)
sys.stdout.flush()
client.close()
Commands:
In terminal 1:
python3 server.py 127.0.0.1 8080
Output after running command in terminal 1:
nothing
In terminal 2:
python3 client.py 127.0.0.1 8080
Output after running command in terminal 2:
Traceback (most recent call last):
File "client.py", line 24, in <module>
read_sockets,write_socket, error_socket = select.select(sockets_list,[],[])
OSError: [WinError 10038] An operation was attempted on something that is not a socket
And I also noticed one thing that after running command in terminal 2 it exits with an error but in terminal 1 it returns:
[ ('127.0.0.1', 10703) ] connected
So, this is all the information related to my question so please solve my problem and explain where I have done things wrong.
Thanks in advance :)
If you're on Windows, the docs mention what's wrong:
File objects on Windows are not acceptable, but sockets are. On Windows, the underlying select() function is provided by the WinSock library, and does not handle file descriptors that don’t originate from WinSock.
You can't wait on stdin on Windows.
I have a server.py and client.py pair. When I run the server on my machine and open multiple terminals to runs clients, I can connect fine. But when I try to run clients on another computer, the client never connects to the server. I'm pretty sure I tested this code a few months ago on multiple computers and it worked fine (though maybe I'm remembering wrong), but I think I updated my python version, so maybe that's why? How can I change my code below so it works?
server.py
import socket
from threading import Thread
import sys
clients = []
def recv(clientsocket):
while True:
msg = clientsocket.recv(1024) # wait for message from any of the clients.
print("\n" + msg.decode())
for c in clients: # send to all the clients.
c.send(msg)
def send(clientsocket):
while True:
msg = "[Server] %s" % input("\n") # wait for input
print(msg)
for c in clients: # send to all the clients.
c.send(msg.encode())
clientsocket.close()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create a socket object
host = socket.gethostname() # Get local machine name
#port = 3001 # Reserve a port for your service.
port = int(input("Enter port: "))
print ('Server started at [%s]' % socket.gethostbyname(host))
print ('Waiting for clients...')
#s.bind((host, port)) # Bind to the port
s.bind((socket.gethostbyname(host), port))
s.listen(5) # Now wait for client connection.
while True:
#Waits until someone new to accept
c, addr = s.accept()
print(addr, "connected.")
clients.append(c)
thread_recv = Thread(target=recv, args=((c,)))
thread_recv.start()
thread_send = Thread(target=send, args=((c,)))
thread_send.start()
s.close()
client.py
import socket
from threading import Thread
hostname = input("Enter hostname/IP to connect to: ")
# port = 3001
port = int(input("Enter port: "))
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect((hostname, port))
def recv():
while True:
print("\n" + clientsocket.recv(2048).decode())
def send(username):
while True:
msg = "[%s] %s" % (username, input(""))
clientsocket.send(msg.encode()) # send message to the server.
username = input("Choose a username: ")
msg = "[%s has just connected]" % (username)
clientsocket.send(msg.encode())
thread_send = Thread(target=send, args=(username,))
thread_send.start()
thread_recv = Thread(target=recv, args=())
thread_recv.start()
while True:
# keep the threads going.
pass
Edit
Every time I start the server, it says my ip address is the same: 192.168.56.1. Even though I've turned my computer off and tried again. But when I go to Google and ask what is my ip address, it is something totally different. Why does the socket keep choosing 192.168.56.1? Is there something special about it? Is this something related to my problem?
Just bind you server to 0.0.0.0 and bind it to all network interfaces:
server.py
s.bind(('0.0.0.0', port))
Then the code in server.py will end up being something like this:
import socket
from threading import Thread
import sys
clients = []
def recv(clientsocket):
while True:
msg = clientsocket.recv(1024) # wait for message from any of the clients.
print("\n" + msg.decode())
for c in clients: # send to all the clients.
c.send(msg)
def send(clientsocket):
while True:
msg = "[Server] %s" % input("\n") # wait for input
print(msg)
for c in clients: # send to all the clients.
c.send(msg.encode())
clientsocket.close()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create a socket object
host = socket.gethostname() # Get local machine name
#port = 3001 # Reserve a port for your service.
port = int(input("Enter port: "))
print ('Server started at [%s]' % socket.gethostbyname(host))
print ('Waiting for clients...')
#s.bind((host, port)) # Bind to the port
s.bind(('0.0.0.0', port))
s.listen(5) # Now wait for client connection.
while True:
#Waits until someone new to accept
c, addr = s.accept()
print(addr, "connected.")
clients.append(c)
thread_recv = Thread(target=recv, args=((c,)))
thread_recv.start()
thread_send = Thread(target=send, args=((c,)))
thread_send.start()
s.close()
I'm new to python and I'm trying to ping my office network and trying to get the hostnames for an inventory system I'm trying to build for work. When I run the script below, I get the IP Address and get either Online or Offline, but I don't get the correct hostname. I only get the hostname of the computer sending out the ping. I think I need to capture it with a string but not sure how to do that. Ultimately this will be run in a GUI with the push of a button.
import ipaddress
from subprocess import PIPE, Popen
import socket
network = ipaddress.ip_network('192.168.1.0/24')
for i in network.hosts():
i = str(i)
h = socket.gethostname()
toping = Popen(['ping', '-c', '5', '-w', '100', i], stdout=PIPE)
output = toping.communicate()[0]
hostalive = toping.returncode
if hostalive == 0:
print(i)
print(h)
print("Is Online")
else:
print(i)
print("Is Offline")
I am creating a TCP server on raspberry pi so that i can control it from my android phone over WIFI. I have connected both the pi and the phone to my WIFI router.
import socket
from cookieLED_FINAL import callLED
host = '192.168.100.100'
port = 5560
def setupServer():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket created.")
try:
s.bind((host, port))
except socket.error as msg:
print(msg)
print("Socket bind complete.")
return s
def setupConnection():
s.listen(1) # Allows one connection at a time.
conn, address = s.accept()
print("Connected to: " + address[0] + ":" + str(address[1]))
return conn
def storeFile(filePath):
picFile = open(filePath, 'wb')
print("Opened the file.")
pic = conn.recv(1024)
while pic:
print("Receiving picture still.")
picFile.write(pic)
pic = conn.recv(1024)
picFile.close()
def dataTransfer(conn):
# A big loop that sends/receives data until told not to.
while True:
# Receive the data
data = conn.recv(1024) # receive the data
data = data.decode('utf-8')
# Split the data such that you separate the command
# from the rest of the data.
dataMessage = data.split(' ', 1)
command = dataMessage[0]
if command == 'GET':
reply = GET()
elif command == 'REPEAT':
reply = REPEAT(dataMessage)
elif command == 'STORE':
print("Store command received. Time to save a picture")
storeFile(dataMessage[1])
print("FINISHED STORING FILE")
break
elif command == 'LED_ON':
callLED()
reply = 'LED was on'
elif command == 'EXIT':
print("Our client has left us :(")
break
elif command == 'KILL':
print("Our server is shutting down.")
s.close()
break
else:
reply = 'Unknown Command'
# Send the reply back to the client
conn.sendall(str.encode(reply))
print("Data has been sent!")
conn.close()
s = setupServer()
while True:
try:
conn = setupConnection()
dataTransfer(conn)
except:
break
When using IP:
192.168.100.100 :
[Errno 99] Cannot assign requested address
127.162.100.100 or 0.0.0.0: The socket is being created but android client is not getting connected.
On my android phone i am using an app named TCP/UDP Test Tool which I downloaded from play store.
I am new on linux as well as on raspberry pi 3 B+.
OS: RASPBIAN
PROGRAMMING LANGUAGE: PYTHON 3.5
Download a software named Advanced IP Scanner.
Connect all the devices to the same network i.e Access point.
On the raspberry pi open terminal and type ifconfig get the ipv4 not the 0.0.0.0 or the 127.0.0.1 the other one.
For example if the ip is showing 192.168.100.144 then input 192.168.100.1-255 in Advanced IP scanner in windows start the scan and find the ips that has your raspberry pi's name written in it. Now input these ips in the tcp client and connect.
I am completely new to network and socket programming. I have tried some code; say I have 3 clients and a server c1 messages and it goes through server and reflected in c2 and c3.
My problem:
I don't want to see my own message (if I say "hi" it's showing for me also but it should be shown in c2 and c3 only).
is there a way like only c2 can see a message and not c3 when c1 sends it
unable to do this in Python and error is shown, so how can be it done in Python 3
server.py
import socket
import time
host = ''
port = 5020
clients = []
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
a=s.bind((host, port))
#s.setblocking(0)
quitting = False
print "Server Started."
print("socket binded to %s" % (port))
while not quitting:
try:
data, addr = s.recvfrom(1024)
if "Quit" in str(data):
quitting = True
if addr not in clients:
clients.append(addr)
#print clients
for client in clients:
if not a:# tried this for broadcasting to others not c1
s.sendto(data, client)
print time.ctime(time.time()) + str(addr) + ": :" + str(data)
except:
pass
s.close()
This is Python 2 code.
client.py
enter code hereimport socket
import threading
import time
shutdown = False
def receving(name, sock):
while not shutdown:
try:
while True:
data, addr = sock.recvfrom(1024)
print str(data)
except:
pass
host = ''
port = 5020
server = ('',5020)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
#s.setblocking(0)
for i in range(5):
threading.Thread(target=receving, args=("RecvThread",s)).start()
alias = raw_input("Name: ")
message = raw_input(alias + "-> ")
while message != 'q':
if message != '':
s.sendto(alias + ": " + message, server)
message = raw_input(alias + "-> ")
time.sleep(0.1)
shutdown = True
s.close()
The output am getting in server is correct the time and server message, but my problem is client output c1 message is shown in c1 itself.
Name: c1
c1-> hi
c1-> c1: hi
see the 3rd line the message "hi" is shown to me also.
Instead of
for client in clients:
if not a:# tried this for broadcasting to others not c1
s.sendto(data, client)
You can do this:
for client in clients:
if client!=addr:# tried this for broadcasting to others not c1
s.sendto(data, client)
Because address of every connected client is stored in addr variable when you do this:
data, addr = s.recvfrom(1024)