Python 3 module import error - python

I have created a python 3.4 file and trying to import some of the variables into another python script. Both of the scripts are in the same folder but I keep getting an error.
I can use the import and it works fine. However when I try to import variables from the script using from ServerConfiguration import port, ip I get an error saying NameError: name 'ServerConfiguration' is not defined
ServerConfiguration module:
import socket
import sys
import os
serverIP = None
def serverSocket():
PORT = 8884 # Port the server is listening on
ServerEst = input('Has a server been established')
if ServerEst == 'yes':
ServerIP = input ('Enter the servers IP address')
socks = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
socks.bind((ServerIP, PORT))
print('Connection Established at ' + serverIP)
else:
CreateServer = input('Would you like to create a server')
if CreateServer == 'yes':
ServerIP = input('What is you LAN IP? Please remeber if reomte user are allowed to connect port forward port "8884" ')
socks = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
socks.bind((ServerIP, PORT))
print('Connection Established to ' + ServerIP)
else:
print ('Defaulting to default')
ServerIP = 'localhost'
socks = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
socks.bind((ServerIP, PORT))
print('Connection Established to ' + ServerIP)
UserModule:
from ServerConfiguration import serverSocket, serverIP
import socket
import sys
import os
def sendMessage():
sockc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
MESSAGE = input('Type the message to send ')
sockc.sendto((MESSAGE.encode, "utf-8"), (serverIP, PORT))
print(MESSAGE)
ServerConfiguration.serverSocket()
sendMessage()

If you use
from ServerConfiguration import serverSocket, serverIP
you should write just
serverSocket()
without ServerConfiguration.
Another way:
import ServerConfiguration
...
ServerConfiguration.serverSocket()

Related

How to get information from a client socket and display information on a server?

How do I force the server to receive messages from the client and display the message: "{name} send message: {data}"? For example, a user sends a message to another user, and when a user named John sends the message "Hello Alice, how are you?", The server will be displayed at this point - John will send a message: Hello Alice, how are you? I will be grateful for your help.
I hope will find the answer to this question in this article. Code below:
server:
import threading
import socket
HOST = '127.0.0.1'
PORT = 8888
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen(15)
print(f'Server {HOST}:{PORT} start.')
users = []
def send_all(data):
for user in users:
user.send(data)
def listen_user(user):
print('Listening user')
while True:
data = user.recv(1024)
print(f'User sent {data}')
send_all(data)
def start_server():
while True:
user_socket, addr = server.accept()
users.append(user_socket)
potok_info = threading.Thread(target=listen_user, args=(user_socket,))
potok_info.start()
if __name__ == '__main__':
start_server()
client:
import socket
import time
import threading
import os
HOST = '127.0.0.1'
PORT = 8888
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST, PORT))
def send_message():
print('Enter name: ')
name = input()
while True:
data = client.recv(1024)
print(data.decode('utf-8'))
msg = (f'{name} send message {data}')
client.send(msg.encode('utf-8')) # this
def send_server():
listen_thread = threading.Thread(target=send_message)
listen_thread.start()
while True:
client.send(input('you: ').encode('utf-8'))
if __name__ == '__main__':
os.system('clear')
print('***** Welcome in Security Chat. *****')
send_server()
I modified your code like that.
This is your server script.
import threading
import socket
HOST = '127.0.0.1'
PORT = 8888
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen(15)
print(f'Server {HOST}:{PORT} start.')
users = [] # To store their name
sort = [] # To store their socket
def listen_user(user):
print('Listening user')
sort.append(user) # Store their socket in sort[]
user.send('Name'.encode('utf-8')) # send 'Name' to clients
name = user.recv(1024).decode('utf-8') # Receive their name
users.append(name) # Store their name in user[]
while True:
data = user.recv(1024).decode('utf-8')
print(f'{name} sent {data}')
for i in sort: # Send received messages to clients
if(i != server and i != user): # Filter server and message sender. Send message except them.
i.sendall(f'{name} > {data}'.encode('utf-8'))
user.close() # To close client socket connection.
def start_server():
while True:
user_socket, addr = server.accept()
potok_info = threading.Thread(target=listen_user, args=(user_socket, ))
potok_info.start()
if __name__ == '__main__':
start_server()
And This is your client script,
import socket
import time
import threading
import os
HOST = '127.0.0.1'
PORT = 8888
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST, PORT))
def send_message():
if('Name' in client.recv(1024).decode('utf-8')): # If 'Name' received. It allows you to send the name.
name = input('Enter Name : ') # Type name
client.send(name.encode('utf-8'))
while True:
data = input('Enter : ') # Enter message
client.send(data.encode('utf-8'))
receive = client.recv(1024).decode('utf-8')# Receive messages from other clients.
print(receive)
def send_server():
listen_thread = threading.Thread(target=send_message)
listen_thread.start()
if __name__ == '__main__':
os.system('clear')
print('***** Welcome in Security Chat. *****')
send_server()
Add remove some part in your code. Study it carefully then you can identify errors in your code.

Instance of 'socket' has no 'gethostbyname' member Python3

Im coding a chat program with python. But when i write "host = socket.gethostname()" it gives me error. My file is named "server.py" (without quotes) How can i fix? Code:
import socket
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostbyname()
port = 12347
socket.bind((host, port))
socket.listen(10)
c, addr = socket.accept()
c.sendall(bytes("Hi!".encode("utf-8")))
print("Connected to {}".format(addr))
while True:
data = str(c.recv(1024))[1:]
if data:
print("Client: {}".format(data))
respond = input("Server: ").encode("utf-8")
if respond == "q":
exit()
else:
c.sendall(bytes(respond.encode("utf-8")))
this should be a red flag:
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
when importing socket, socket is the socket module. The line above assigns the name socket to a socket object.
Then
host = socket.gethostbyname()
doesn't work because the method applies to the module, but the module name has been reassigned to the socket object.
That would work (renaming your socket object):
import socket
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostbyname("localhost") # needs an argument, btw

Clients not receiving data from Server python

I am new to Python. I am writing a Server program and a Client program. In here, Server plays the role of distributing the data to the multiple clients. It works great. My task is to distribute the data from the server by using server.py file. Whenever any clients wants it, he just execute clients.py in his laptop and get the results. But in here, the Server starts distributing the data. The ip, the server using was 127.0.1.1. It is not taking the network provided ip. How to make it use the ip provided by LAN. When the clients from other computer execute clients.py file . It shows Connection refused error. Note that we are all connected in the LAN. How to solve it and make clients receive the data.
Here's the sample Client Code:
import socket
import os
from threading import Thread
import socket
import time
s = socket.socket()
host = '127.0.1.1'
port = 10016
print(host)
s.connect((host, port))
while True:
print(s.recv(1024))
s.close()
Sample Server Code:
import socket
import os
from threading import Thread
import thread
import threading
import time
import datetime
def listener(client, address):
print ("Accepted connection from: ", address)
with clients_lock:
clients.add(client)
try:
while True:
client.send(a)
time.sleep(2)
finally:
with clients_lock:
clients.remove(client)
client.close()
clients = set()
clients_lock = threading.Lock()
host = socket.gethostname()
port = 10016
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host,port))
s.listen(3)
th = []
print ("Server is listening for connections...")
while True:
client, address = s.accept()
timestamp = datetime.datetime.now().strftime("%b %d %Y,%a, %I:%M:%S %p")
a = "Hi Steven!!!" + timestamp
th.append(Thread(target=listener, args = (client,address)).start())
s.close()
configure the ip provided by LAN to client.py (ip in LAN like this: 192.168.122.33)
host = 'ip provided by LAN'
Finally found the answer
In the '/etc/hosts' file content, i have an IP address mapping with '127.0.1.1' to my hostname. This is causing the name resolution to get 127.0.1.1. I commented this line. Now it works. Every one in my lan can receive the data
Server Code:
import socket
import os
from threading import Thread
import threading
import time
import datetime
def listener(client, address):
print ("Accepted connection from: ", address)
with clients_lock:
clients.add(client)
try:
while True:
client.send(a)
time.sleep(2)
finally:
with clients_lock:
clients.remove(client)
client.close()
clients = set()
clients_lock = threading.Lock()
host = socket.getfqdn() # it gets ip of lan
port = 10016
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host,port))
s.listen(3)
th = []
print ("Server is listening for connections...")
while True:
client, address = s.accept()
timestamp = datetime.datetime.now().strftime("%b %d %Y,%a, %I:%M:%S %p")
a = ("Hi Steven!!!" + timestamp).encode()
th.append(Thread(target=listener, args = (client,address)).start())
s.close()
Client Code:
import socket
import os
import time
s = socket.socket()
host = '192.168.1.43' #my server ip
port = 10016
print(host)
print(port)
s.connect((host, port))
while True:
print((s.recv(1024)).decode())
s.close()

Python - How to get connections OS type?

How can I get the connected users OS type?
because when I use os.name from the OS module it shows my servers OS type not the users
Code:
import socket
import threading
from thread import start_new_thread
connect = ""
conport = 8080
def clientThread(conn):
while True:
message = conn.recv(512)
if message.lower().startswith("quit"):
conn.close()
if not message:
break
def startClient():
host = connect
port = conport
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((host, port))
sock.listen(1)
print("[+] Server Started")
while True:
conn, addr = sock.accept()
start_new_thread(clientThread, (conn,))
sock.close()
client = threading.Thread(target=startClient)
client.start()

how to send response from server to client using python socket?

i want to communication between two system using python socket, in which one machine is local system(client) and another is public system(server),
the code i write is :
client.py
import socket
import commands
import sys
import time
s = socket.socket()
state = sys.argv[1]
pname = sys.argv[2]
user = commands.getoutput("whoami")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('132.65.45.156', 5001))
info = commands.getoutput("echo '%s','%s','%s','%s'"%(state,ip,user,pname))
while True:
data2 = info
s.sendall(data2)
break
server.py
import socket
import time
import string
import sys
import base64
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', 5001))
sock.listen(5)
while True:
newSocket, address = sock.accept()
print "Connected from ", address
filename = newSocket.recv(5001)
while True:
data = newSocket.recv(5001)
if not data: break
print filename, "Received\n"
sock.close()
After getting response from client to server, what to do if server want to send response to client ?

Categories