I was trying to scan ports through socket but it's show all ports closed. Here is my code:
import socket
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = input(" Please Input Ip address To Scan ")
#port = input(" ENter The Port ")
def portscanner(host):
for port in range(1,150):
if sock.connect_ex((host,int(port))):
print(f"{port} Is Closed")
else:
print("port is open")
portscanner(host)
Try creating a connection inside the forloop. And make sure that the input is in valid form.
You can do that using
try and catch near the sock.connect_ex to check whether you are actually sending valid host or not.
To make things faster you can use settimeout(0.25) inside the for loop too.
I meant to do this -
for port in range(start, end):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(.25)
result = sock.connect_ex((host, port))
if result == 0:
print(port,'port is open')
sock.close()
Related
I am trying to implement sockets with python.the following code works well without the while loop..but with the while loop, for the second iteration , it gets stuck in s.sendall().could you please suggest how to fix this ?
def main():
host = socket.gethostname()
port = 11111
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
print "Connected to Server!"
while True:
print "Enter your Command:"
command = raw_input()
if(command):
try:
sock.sendall(repr(command))
except socket.error:
print "Socket Error Occured"
data = sock.recv(1024)
if data:
print('Received', repr(data))
else:
print "No Data"
else:
os.system("clear")
sock.close()
if __name__ == "__main__":
main()
Hello
I don't have all the information I need to make this post as
informed as I'd like, however I can make some educate
d guesses and try my best to explain what I think is going wrong. Are you ready?? Lets get into it.
So,
You start off by making a tcp socket and then connecting to a server hosted locally on port 11111
host = socket.gethostname()
port = 11111
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
next you enter a loop
while True:
#input command, request eval
Here your goal is to take user input and send it to a server to eval. You do that with
#get user input
print "Enter your Command:"
command = raw_input()
#send command to server for eval
sock.sendall(repr(command))
#receive then print eval
data = sock.recv(1024)
print('Received', repr(data))
this works and sends commands as you'd expect, although sending repr(command) might not be what you want to send
command = "1+1"
eval(command)
//2
eval(repr(command))
//'1+1'
Now
Here is where I have to make some assumptions
Early on you connected to a server
sock.connect((host, port))
I'm assuming that the server accepts your connection evals your command and sends the answer back. Something like
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind('localhost',11111)
sock.listen()
while True:
conn, addr = sock.accept()
command = conn.recv(1024)
sock.sendall(eval(command))
If this is the case then your connection might fail because your eval server runs eval once and then accepts a new connection.
That means that your client can no longer send to, or recieve data from, the server
I hope this helps.
I am sending a message to client but the client wont stop spamming the message
server.py
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
hostname = socket.gethostname()
hostip = socket.gethostbyname(hostname)
port = 462
server.bind((hostname, port))
server.listen(1)
print((hostip, port))
client, address = server.accept()
print("New connection!: ", address)
while True:
data = input("Do something:")
if data == "help":
print("test: 'test'")
input("Click ENTER to continue")
elif data == "test":
client.send("test".encode('ascii'))
else:
continue
client.py
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 462
s.connect(('', port))
data = s.recv(1024)
while True:
if data.decode('ascii') == "test":
print(data.decode('ascii'))
else:
continue
You didn't post the full example, but I think I can see where the problem is.
Where/when do you actually read/receive the data from the socket in the client.py?
Because it looks like you received the data, saved it in the in the "data" variable and then you keep looping forever decoding this data, not reading from socket.
So I think you need to move your while loop in client.py outside, so that the read/receive from socket method is inside your loop, not outside as it appears it is now.
Edit: Yup, from the full code that you posted I can see that indeed, this should fix your problem.
I have the following code written in 2.7 python:
#...import stuff
remoteServer = raw_input("Enter a remote host to scan: ")
remoteServerIP = socket.gethostbyname(remoteServer)
print "Please wait, scanning remote Host", remoteServerIP
try:
for port in xrange(1, 1024):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((remoteServerIP, port))
if result == 0:
print "port {}: open".format(port)
sock.close
except KeyboardInterrupt:
print "\nexiting..."
sys.exit()
Output:
Enter a remote host to scan: www.myexamplesite.com
Please wait, scanning remote Host xxx.xxx.xx.xx
port 21: open
port 22: open
...
But the problem is that I also want to know which ports are used and for what they are used just like:
#... as usual
port 1 httpserver
port 2 chat server
...
but this is only printing the ports from 1 to 1024
is there a function/way to do this?
socket.getservbyport() will translate port numbers into the service expected to be running on that port (via /etc/services), but won't actually communicate over the port to find out what is really running.
This question already has answers here:
Python Socket Multiple Clients
(6 answers)
Closed 5 years ago.
Im trying to have multiple clients be able to connect to a server however when a second user connects it kicks the other client off the server as you cant have 2 clients connected to a socket and i was wondering if there was anything around this.
server.py
import socket
def Main():
host = '10.41.13.228'
port = 5000
s = socket.socket()
s.bind((host,port))
s.listen(1)
name = input("Please Enter your name - ")
while True:
c, addr = s.accept()
print("Connection from: " + str(addr))
data = c.recv(1024).decode('utf-8')
print(data)
c.close()
if __name__ == '__main__':
Main()
Client.py
import socket
def Main():
host = '10.41.13.228'
port = 5000
s = socket.socket()
s.connect((host, port))
name = input("Please enter your name - ")
message = input("-> ")
while True:
while message != 'q':
ToSend = (str(name) + " - " + str(message))
s.sendall(ToSend.encode('utf-8'))
message = input("-> ")
s.close()
if __name__ == '__main__':
Main()
The problem i noticed in your code is s.listen method. Where you are listening to only one client connection. You could increase the amount to have more clients connected to the server.
As described in the example from the docs:
Note that a server must perform the sequence socket(), bind(), listen(), accept() (possibly repeating the accept() to service more than one client), while a client only needs the sequence socket(), connect(). Also note that the server does not sendall()/recv() on the socket it is listening on but on the new socket returned by accept().
Therefore, there are two missing parts in your code.
As already commented, your listen() method should take a 2 as argument (as you intend to have 2 clients).
You should call accept() twice. Remember to keep in mind the comment of the example. Quoting again:
note that the server does not sendall()/recv() on the socket it is
listening on but on the new socket returned by accept()
Out of topic. It is indeed a good practice to have a keyword such as 'exit' to break from the loop of your server once recieved.
I have two scripts, Server.py and Client.py.
I have two objectives in mind:
To be able to send data again and again to server from client.
To be able to send data from Server to client.
here is my Server.py :
import socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "192.168.1.3"
port = 8000
print (host)
print (port)
serversocket.bind((host, port))
serversocket.listen(5)
print ('server started and listening')
while 1:
(clientsocket, address) = serversocket.accept()
print ("connection found!")
data = clientsocket.recv(1024).decode()
print (data)
r='REceieve'
clientsocket.send(r.encode())
and here is my client :
#! /usr/bin/python3
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host ="192.168.1.3"
port =8000
s.connect((host,port))
def ts(str):
s.send('e'.encode())
data = ''
data = s.recv(1024).decode()
print (data)
while 2:
r = input('enter')
ts(s)
s.close ()
The function works for the first time ('e' goes to the server and I get return message back), but how do I make it happen over and over again (something like a chat application) ?
The problem starts after the first time. The messages don't go after the first time.
what am I doing wrong?
I am new with python, so please be a little elaborate, and if you can, please give the source code of the whole thing.
import socket
from threading import *
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "192.168.1.3"
port = 8000
print (host)
print (port)
serversocket.bind((host, port))
class client(Thread):
def __init__(self, socket, address):
Thread.__init__(self)
self.sock = socket
self.addr = address
self.start()
def run(self):
while 1:
print('Client sent:', self.sock.recv(1024).decode())
self.sock.send(b'Oi you sent something to me')
serversocket.listen(5)
print ('server started and listening')
while 1:
clientsocket, address = serversocket.accept()
client(clientsocket, address)
This is a very VERY simple design for how you could solve it.
First of all, you need to either accept the client (server side) before going into your while 1 loop because in every loop you accept a new client, or you do as i describe, you toss the client into a separate thread which you handle on his own from now on.
client.py
import socket
s = socket.socket()
s.connect(('127.0.0.1',12345))
while True:
str = raw_input("S: ")
s.send(str.encode());
if(str == "Bye" or str == "bye"):
break
print "N:",s.recv(1024).decode()
s.close()
server.py
import socket
s = socket.socket()
port = 12345
s.bind(('', port))
s.listen(5)
c, addr = s.accept()
print "Socket Up and running with a connection from",addr
while True:
rcvdData = c.recv(1024).decode()
print "S:",rcvdData
sendData = raw_input("N: ")
c.send(sendData.encode())
if(sendData == "Bye" or sendData == "bye"):
break
c.close()
This should be the code for a small prototype for the chatting app you wanted.
Run both of them in separate terminals but then just check for the ports.
This piece of code is incorrect.
while 1:
(clientsocket, address) = serversocket.accept()
print ("connection found!")
data = clientsocket.recv(1024).decode()
print (data)
r='REceieve'
clientsocket.send(r.encode())
The call on accept() on the serversocket blocks until there's a client connection. When you first connect to the server from the client, it accepts the connection and receives data. However, when it enters the loop again, it is waiting for another connection and thus blocks as there are no other clients that are trying to connect.
That's the reason the recv works correct only the first time. What you should do is find out how you can handle the communication with a client that has been accepted - maybe by creating a new Thread to handle communication with that client and continue accepting new clients in the loop, handling them in the same way.
Tip: If you want to work on creating your own chat application, you should look at a networking engine like Twisted. It will help you understand the whole concept better too.