HELP please i have this code
import socket
from threading import *
import time
HOST = '' # Symbolic name meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ('Socket created')
s.bind((HOST, PORT))
print ('Socket bind complete')
s.listen(10)
print ('Socket now listening')
def listen(conn):
odata = ""
end = 'end'
while end == 'end':
data = conn.recv(1024)
if data != odata:
odata = data
print(data)
if data == b'end':
end = ""
print("conection ended")
conn.close()
while True:
time.sleep(1)
conn, addr = s.accept()
print ('Connected with ' + addr[0] + ':' + str(addr[1]))
Thread.start_new_thread(listen,(conn))
and i would like it so that when ever a person comes onto the server it has its own thread. but i can't get it to work please someone help me. :_(
here is the error code:
Socket created
Socket bind complete
Socket now listening
Connected with 127.0.0.1:61475
Traceback (most recent call last):
File "C:\Users\Myles\Desktop\test recever - Copy.py", line 29, in <module>
Thread.start_new_thread(listen,(conn))
AttributeError: type object 'Thread' has no attribute 'start_new_thread'
i am on python version 3.4.0 and here is the users code:
import socket #for sockets
import time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket Created')
host = 'localhost'
port = 8888
remote_ip = socket.gethostbyname( host )
print('Ip address of ' + host + ' is ' + remote_ip)
#Connect to remote server
s.connect((remote_ip , port))
print ('Socket Connected to ' + host + ' on ip ' + remote_ip)
while True:
message = input("> ")
#Set the whole string
s.send(message.encode('utf-8'))
print ('Message send successfully')
data = s.recv(1024)
print(data)
s.close
The API you're using has moved from thread to _thread, so you'll need to do;
import _thread
The call is on the _thread module and requires a tuple as a second argument, so the correct line to start the thread would be;
_thread.start_new_thread(listen,(conn,))
IMHO, you're on the right track trying to use threading instead though, but that API works differently so you'll have to rewrite the code to make it work. A very brief description how it's used is for example available here.
Related
I'm learning the sockets python module and I'm looking at the following tutorial code:
'''
Simple socket server using threads
'''
import socket
import sys
from thread import *
HOST = '' # Symbolic name meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
#Function for handling connections. This will be used to create threads
def clientthread(conn):
#Sending message to connected client
conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string
#infinite loop so that function do not terminate and thread do not end.
while True:
#Receiving from client
data = conn.recv(1024)
reply = 'OK...' + data
if not data:
break
conn.sendall(reply)
#came out of loop
conn.close()
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
start_new_thread(clientthread ,(conn,))
s.close()
I'm stuck on the final line, s.close(). I don't understand what this does since the code seems to be stuck in an infinite loop right above, which is never broken. Am I missing something or is s.close() totally extraneous in this instance?
I have a piece of python code to listen on a port. The end result I want is that when anyone runs nmap against that IP, a custom name shows up in the service name column. To illustrate my requirement, see below screenshot that shows port 666 as the name doom.
I tried searching for solutions without any success.
Below is the python code that I'm using to listen on a port:
import socket
import sys
HOST = '' # Symbolic name, meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
s.close()
If someone could point me in the right direction or help me with the modification I should make to this code, I would really appreciate it.
Trying to Create Messenger Application within python (cross internet). So far I have successfully been able to send a message to the receiver end and then ping the message back to the user that sent it. However, it does not send the message to all connected users. I think this is because if python is listening for user input the socket cannot receive any data (I might be wrong...).
Below is the client side code:
import socket
host = '**.***.***.***' # Public Ip Hidden
port = 5005 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
b = input("Please enter your message.")
b = b.encode('utf-8')
s.sendall(b)
while True:
data = s.recv(1024)
print('Message Received:', repr(data))
Now below is the server side code:
import socket
import sys
import os
import thread
import threading
from thread import *
from threading import Thread
HOST = '' # Symbolic name meaning all available interfaces
PORT = 5005 # Arbitrary non-privileged port
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client = ''
clients = set()
clients_lock = threading.Lock()
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
#Function for handling connections. This will be used to create threads
def clientthread(conn):
#infinite loop so that function do not terminate and thread do not end.
with clients_lock:
clients.add(client)
while True:
#Receiving from client
data = conn.recv(1024)
if not data:
break
else:
print repr(data)
with clients_lock:
for c in clients:
for d in data:
conn.sendall(data)
print(data.decode("utf-8"))
#came out of loop
conn.close()
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
start_new_thread(clientthread ,(conn,))
s.close()
Any Suggestions would be much appreciated.
I am trying to create a basic instant message program that uses a p2p (peer-to-peer) connection so it will not need a server. I am pretty sure nothing is wrong, but every time I run the client program I have created, I get this error:
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
NameError: global name 'SOL_SOCKET' is not defined
Here is the program:
import socket
def Receiver():
# Create socket that supports IPv4, TCP Protocol
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket created."
# Requests for IP of host (DNS)
dns = "localhost"
HOST = ''
PORT = 25395
try:
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
except socket.error as serror:
print "socket error"
s.bind((HOST, PORT)) # Listens on all interfaces...
print 'Listening on port 25565'
s.listen(True) # Listen on the newly created socket...
conn, addr = s.accept()
print 'Connected in port 25565'
data = conn.recv(1024)
print data
s.close()
def Sender():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
dns = "localhost"
HOST = socket.gethostbyname(dns)
port = 25565
# Connect to server
s.connect((host,port))
print "Socket connected to " + dns + " on IP " + host
# Assign message to be sent to server to a variable
message = raw_input("Message to be sent to server: ")
#Send the actual message to server
s.sendall(message)
print "Message sent successfully"
s.close()
input = raw_input('S is send, R is receive: ')
if input == 's':
Sender()
if input == 'r':
Receiver()
I have tried removing s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) but it tells me that I cannot use 2 sockets on the same port when there isn't 2 sockets using the same port.
In your code:
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
do like:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# ^^^^ added ^^^
because you imported just socket, check following code pieces:
>>> import socket
>>> SOL_SOCKET
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'SOL_SOCKET' is not defined
>>> socket.SOL_SOCKET
1
I am learning socket programming and python. I need to create a client that sends a command to a server (list or get ). The server then validates the command. My client program can display "list" or "get" , but it doesn't show the error message when I enter other things.
Also, it only works one time; when I enter a different command after receiving a reply from the server, it gives me the following error:
Traceback (most recent call last):
File "fclient.py", line 49, in
client_socket.send(command)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 170, in _dummy
raise error(EBADF, 'Bad file descriptor')
I'm totally lost. What is the best way to get a command line input in the client program and send it to the server and ask the server to validate the command line parameter? Can someone take a look and point me to the right direction? Your help is greatly appreciated.
Client.py
import socket #for sockets
import sys #for exit
command = ' '
socksize = 1024
#return a socket descriptor which can be used in other socket related functions
#properties: address family: AF_INET (IP v4)
#properties: type: SOCK_STREAM (connection oriented TCP protocol)
try:
#create an AF_INET, STREAM socket (TCP)
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg: #error handling
print 'Failed to create socket. Error code: ' + str(msg[0]) + ', Error message: ' + msg[1]
sys.exit();
print 'Socket Created'
#Get the IP address of the remote host/url
#connect to IP on a certain 'port' using the connect
#host = 'flip3.engr.oregonstate.edu'
#port = 30021
#host = 'www.google.com'
#port = 80
host = '' #symbolic name meaning the local host
port = 8888 #arbitrary non-privileged port
try:
remote_ip = socket.gethostbyname(host)
except socket.gaierror:
#could not resolve
print 'Hostname could not be resolved. Existing'
sys.exit()
print 'IP address of ' + host + ' is ' + remote_ip
#Connect to remote server
client_socket.connect((remote_ip, port))
print 'Socket Connected to ' + host + ' on ip ' + remote_ip
#Send some data to remote server
while True:
print 'Enter a command: list or get <filename>'
command = raw_input()
if command.strip() == 'quit':
break
client_socket.send(command)
data = client_socket.recv(socksize)
print data
#Close the socket
client_socket.close()
Server.py
import socket
import sys
from thread import *
#HOST = 'flip3.engr.oregonstate.edu' #symbolic name meaning all available interfaces
#PORT = 30021
HOST = ''
PORT = 8888
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
server_socket.bind((HOST, PORT)) #bind to a address(and port)
except socket.error, msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#put the socket in listening mode
server_socket.listen(10) #maximum 10 connections
print 'TCP Server Waiting for client on port 30021'
#wait to accept a connection - blocking call
client, addr = server_socket.accept()
#display client information
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#keep talking with the client
while 1:
#Receiving from client
data = client.recv(1024)
if (data == 'list' or data == 'get'):
reply = 'receive: ' + data
client.send(reply)
break;
else:
reply = 'wrong command'
client.send(reply)
client.close()
The first problem is that you close your client socket inside your loop, closing it after receiving the reply to the first command. Move closing the socket out of the loop instead and introduce an exit condition to exit the loop:
#Connect to remote server
client_socket.connect((remote_ip, port))
print 'Socket Connected to ' + host + ' on ip ' + remote_ip
#Send some data to remote server
while True:
print 'Enter a command: list or get <filename>'
command = raw_input()
if command.strip() == 'quit':
break
client_socket.send(command)
data = client_socket.recv(socksize)
print data
# Close the socket
client_socket.close()
You're doing something similar on the server side: You try to reopen the listening socket every iteration. Move this part out of the loop as well:
#wait to accept a connection - blocking call
client, addr = server_socket.accept()
#display client information
print 'Connected with ' + addr[0] + ':' + str(addr[1])
The reason your command parsing doesn't work is because of this statement:
if (data == 'list' or 'get'):
What you meant to write here is
if (data == 'list' or data == 'get'):
The first expression will evaluate like this:
Is data == 'list'?
If yes, that sub-expression evaluates to True and is therefore what a or b will return.
If not, the second operand to or is chosen, which is the string 'get'.
The result of that or expression will now be implicitely cast to boolean by the if statement:
Case 1: True is already True
Case 2: A non-empty string cast to boolean evaluates to True as well
So your if statement will always evaluate to True, that's why your command parsing didn't work.
To write
if (data == 'list' or data == 'get'):
in a nicer form, I would suggest to use
if (data.strip() in ('list' 'get')):
Lastly, you should wrap your socket code in a try..finally to make sure the sockets are always closed even if exceptions like a KeyboardInterrupt happen:
try:
#keep talking with the client
while 1:
#Receiving from client
data = client.recv(1024)
if (data.strip() in ('list' 'get')):
reply = 'receive: ' + data
client.send(reply)
else:
reply = 'wrong command'
client.send(reply)
except KeyboardInterrupt:
print "Exiting gracefully."
finally:
server_socket.close()
(The finally clause gets executed under all circumstances - whether handled or undhandled exceptions happened, or not)
One problem is that you close client_socket in your while loop. After that, client_socket.send() will not work anymore. There are at least two ways to fix this:
Move client_socket.connect() into your while loop also.
Get rid of client_socket.close(), and move server_socket.accept() above the while loop in Server.py.
There are more sophisticated options involving select() or other methods, but one of the two items above should get you by for now.