Python Server NameError: global name 'SocketError' is not defined - python

I wanted to make a connection between a sever and a client, so the server sends a string to the client.
Here is the Server:
import socket
def Main():
host = '190.176.141.23'#ip changed
port = 12345
while True:
s = socket.socket()
s.bind((host,port))
s.listen(1)
c, addr = s.accept()
print "Connection from: " + str(addr)
command = c.recv(1024)
if command == 'GIVETEXT':
c.send('test')
try:
c.close()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise
pass
if __name__ == '__main__':
Main()
And here is the Client I made:
import socket
class Client(object):
def __init__(self, *args):
self.s = socket.socket()
def sent(self, host, port):
self.s.connect((host, port))
self.s.send('GIVETEXT')
self.Text = self.s.recv(1024)
print self.Text
self.s.close
return self.Text
Needless to say, that I executed the method in another piece of code, and it worked. But after that the server crashed, with the error message:
NameError: global name 'SocketError' is not defined

It is socket.error; not SocketError. Change your except line to:
except socket.error as e:

Related

How can I use a local variable declared in one function and implement it to another function? (Without global variables or calling the function)

import socket, sys
def create_socket(): # Creates a socket which connects two or more computers together
host = ""
port = 9999
socket_ = socket.socket()
try:
host
port
socket_
except socket.error as msg:
print("Socket Creation Error: " + str(msg))
return host, port, socket_
def bind_Socket(): # Binds the Socket and listening for connections
host, port, socket_ = create_socket()
try:
host
port
socket_
print("Binding the Socket: " + str(port))
socket_.bind((host, port))
socket_.listen(5)
except socket.error as msg:
print("Socket Creation Error: " + str(msg) + "Retrying....")
bind_Socket()
return host, port, socket_
def socket_accept(): # Establishes a connection with a client (socket must be listening)
host, port, socket_ = bind_Socket()
conn, address = socket_.accept()
send_command(conn)
print("Connection successful... " + "IP: " + address[0] + "\n" + "Port: " + address[1])
def send_command(conn): # Sends command to client
host, port, socket_ = bind_Socket()
cmd = ""
while (cmd != "Quit"):
cmd = input("Enter a command: ")
if(len(str.encode(cmd)) > 0):
conn.send(str.encode(cmd))
client_response = str(conn.recv(1024,"UTF-8"))
print(client_response, end="")
else:
conn.close()
socket_.close()
sys.exit()
def main():
create_socket()
bind_Socket()
socket_accept()
main()
The problem is when I call the bind_Socket() in main() It will print out "Binding the Socket: 9999" twice because it's also being called in the function socket_accept(). I just want to know how to use the same variables declared in one function and implement it in another without using global variables or calling the function like I did.
Functions can return objects to be used by other functions as arguments.
Set main up like this:
def main():
_, _, socket_ = bind_Socket()
socket_accept(socket_)
Then update _accept to accept args:
def socket_accept(socket_):
conn, address = socket_.accept()
....
Thus passing the socket object to the accept method.

Socket While True Loop Doesn't Work Properly

I want to ask you about while loop in socket works.
The problem is, when i started app, the server is waiting for connections by While True. But if anyone connect, server won't accept another connections. The While True loop freezes.
My Code:
import socket
import threading
class Server(object):
def __init__(self, host="localhost", port=5335):
"""Create socket..."""
self.host = host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.bind((self.host, self.port))
self.sock.listen(0)
self.clients = []
print("Server is ready to serve on adress: %s:%s..."%(self.host, self.port))
while True:
client, addr = self.sock.accept()
print("There is an connection from %s:%s..."%addr)
t = threading.Thread(target=self.threaded(client, addr))
t.daemon = True
t.start()
self.sock.close()
def threaded(self, client, adress):
"""Thread client requests."""
while True:
data = client.recv(1024)
print("%s:%s : %s"%(adress[0], adress[1], data.decode('ascii')))
if not data:
print("Client %s:%s disconnected..."%adress)
break
if __name__ == "__main__":
Server()
You aren't calling the thread properly. You're calling self.threaded(client, addr) immediately and then passing the result to threading.Thread().
In other words, this:
t = threading.Thread(target=self.threaded(client, addr))
... is identical to this:
result = self.threaded(client, addr)
t = threading.Thread(target=result)
You need to call it like this:
t = threading.Thread(target=self.threaded, args=(client, addr))

_socketobject' object has no attribute 'bing'

First I wanna say I am new to python I mostly use to do programming in java so forgive me if the answer is obvious but I am having the error (_socketobject' object has no attribute 'bing') when I run my script but I cant see anything wrong with it....
import socket
import sys
import threading
import paramiko
host_key = paramiko.RSAKey
(filename='/home/moonman/Desktop/test_rsa.key')
class Server (paramiko.ServerInterface):
def __init__(self):
self.event = threading.Event()
def check_channel_request(self, kind, chanid):
if kind == 'session':
return paramiko.OPEN_SUCCEEDED
return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
def check_auth_password(self, username, password):
if (username == 'moonman') and (password == 'lover23567'):
return paramiko.AUTH_SUCCESSFUL
return paramiko.AUTH_FAILED
try:
global sock
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bing(('192.168.1.13' , 22))
sock.listen(1)
print '[+] Listening for Connection ...'
except Exception, e:
print '[-] Cant start listening ): ' + str(e)
try:
client, addr = sock.accept()
print '[+] Just got a reverse connection from ' + str(addr)
t = paramiko.Transport(client)
t.load_server_moduli()
t.add_server_key(host_key)
server = Server()
t.start_server(server=server)
global chan
chan = t.accept(1)
print chan.recv(1024)
chan.send("Connection Understood! Loud and clear!!")
except:
print "[-] Connection just died"
pass
Socket object has no attribute as bing. I guess you meant sock.bind which binds the socket to the address you defined.
Try this:
sock.bind(('192.168.1.13' , 22))

Can a Server listens to a UDP messages without IP configured

Please look at the following python code.
I created a Server class to listen on port 10000 to receive UDP broadcast messages.
If IP address is configured in the system, it can receive UDP broadcast messages. If no ip address configured, it cannot receive any messages.
Could you tell me why?
import socket
import sys
class Server:
class Handler:
def handle(self, message):
pass
def __init__(self, serialNo):
self.serialNo = serialNo
def _setAddress(self, socket, message, address):
self.message = message
self.address = address
self.socket = socket
def send(self, message):
self.socket.sendto(message, self.address)
def getSerialNo(self):
return self.serialNo
def __init__(self, port, handler):
self.ss = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.ss.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.ss.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
self.handler = handler
try:
self.ss.bind(('<broadcast>', port))
except:
self.ss.close()
raise RuntimeError("Create socket error")
self.ss.setblocking(1)
def loop(self):
while True:
try:
print "Listening for broadcast..."
message, address = self.ss.recvfrom(8192)
print "Got request from %s:%s" % (address, message)
self.handler._setAddress(self.ss, message, address)
self.handler.handle(message)
except (KeyboardInterrupt, SystemExit):
raise
except:
sys.exc_info()[0]
After referring to pydhcp client code, I made following changes:
import socket
import sys
import select
class Server:
class Handler:
def handle(self, message):
pass
def __init__(self, serialNo):
self.serialNo = serialNo
def _setAddress(self, socket, message, address):
self.message = message
self.address = address
self.socket = socket
def send(self, message):
self.socket.sendto(message, self.address)
def getSerialNo(self):
return self.serialNo
def __init__(self, port, handler):
self.ss = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.ss.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.ss.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
self.handler = handler
try:
self.ss.bind(("0.0.0.0", int(port)))
except:
self.ss.close()
raise RuntimeError("Create socket error")
def loop(self):
while True:
try:
print "Listening for broadcast..."
data_input,data_output,data_except = select.select([self.ss],[],[], 60)
if (data_input != []):
(message, address) = self.ss.recvfrom(2048)
print "Got request from %s:%s" % (address, message)
self.handler._setAddress(self.ss, message, address)
self.handler.handle(message)
else:
print "no data within 60 seconds"
except (KeyboardInterrupt, SystemExit):
raise
except:
sys.exc_info()[0]
Now it can receive the broadcasting packets, but it cannot work on RedHat.

Python threading giving global name not defined error

The following code is giving a global name not defined error, but as far as I can see the name is defined. I'm new to Python, is this a scope issue?
import os, socket
from threading import Thread
class serv:
def __init__(self):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(('', 443))
def run(self):
self.socket.listen(10)
print "Listening"
self.conn, self.addr = self.socket.accept()
try:
Thread(target=clientThread, args=(self.conn,)).start()
except Exception, errtxt:
print errtxt
def exit(self):
print "Disconnected"
self.conn.close()
def clientThread(conn):
print "Connected"
while 1:
conn.send("Hello, worlds!\n")
S = serv()
S.run()
The specific error is
global name 'clientThread' is not defined
you should use
self.clientThread
I would make these changes:
(1) Pass self to self.clientThread
def run(self):
self.socket.listen(10)
print "Listening"
self.conn, self.addr = self.socket.accept()
try:
Thread(target=self.clientThread, args=(self,)).start()
except Exception, errtxt:
print errtxt
(2) Reference self in clientThread
def clientThread(self):
print "Connected"
while 1:
self.conn.send("Hello, worlds!\n")
Another possibility is to have your object derive from threading.Thread instead of have a Thread. Then your code looks more like this:
import os, socket
from threading import Thread
class serv(Thread):
def __init__(self):
super(serv, self).__init__()
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(('', 443))
def run(self):
self.socket.listen(10)
print "Listening"
self.conn, self.addr = self.socket.accept()
try:
print "Connected"
while 1:
self.conn.send("Hello, worlds!\n")
except Exception, errtxt:
print errtxt
def exit(self):
print "Disconnected"
self.conn.close()
S = serv()
S.start()

Categories

Resources