def main(port):
try:
ip = '192.168.0.51'
s = socket.socket()
socket.setdefaulttimeout(1)
s.connect((ip, port))
rec = s.recv(1024).decode('utf-8')
print(rec)
except Exception:
pass
for port in range(1,100):
main(port)
I have watched tutorials on this and it still has not worked for me, I also tried it with my public IP but obviously I didn't put that in the code shown. I didn't receive any data from the connection, so I tried to decode it but still didn't work. I am trying to get the banner so the service running on the port. How would I do this? What did I do wrong? I don't mind if it's in py2 or py3
Related
I am trying to build a connection between a server and one or more clients in Python using sockets. My code works just fine when I connect with a client in the same network, but my goal is to build a program which me and my friend can use, so I want to figure out a way to connect to my server from an external network via the internet.
My server-side code looks like this:
import socket
server = "internal_ip"
port = 5006
serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
serv.bind((server, port))
print(server)
except socket.error as e:
print(e)
serv.listen(2)
while True:
conn, addr = serv.accept()
from_client = ""
while True:
data = conn.recv(4096)
if not data:
break
from_client += str(data)
print(from_client)
conn.send(str.encode("I am SERVER"))
conn.close()
print("Client disconnected")
And this is my client:
import socket
server = "internal_ip"
port = 5006
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client.connect((server, port))
except socket.error as e:
print(e)
while True:
try:
client.send(str.encode("I am CLIENT"))
from_server = client.recv(4096)
#client.close()
print(from_server)
except:
break
client.close()
This works just fine within a network. Then I started testing the code from an external client. I changed the ip to my external ip address which I have found using whatismyipaddress.com, and port number to a different one than I use on the server side.
server = "external_ip"
port = 5007
Then I enabled port forwarding using cmd:
netsh interface portproxy add v4tov4 listenport=5007 listenaddress=external_ip connectport=5006 connectaddress=internal_ip
I get WinError 10060. Tried switching firewall on and off, and allowing these specific ports, but I can't make it work.
Can you help me with my problem please?
I'm using python 3.8, and trying to learn to code for networking; I've seen some examples from 2014 with code for a port scanner, which is defines the port scanning function like this:
def pscan(port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
con = sock.connect((target, port))
with print_lock:
print("Port:",port,"is open.")
con.shutdown()
con.close()
When I implement this in pycharm I see the message:
"Cannot find reference 'shutdown' in 'None'
and
"Cannot find reference 'close' in 'None'
The code runs, but never seems to stop... I am guessing that it is due to not properly closing the socket.
Can anyone educate me as to where my error is?
connect doesn't return anything.
I think you want this:
def pscan(port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((target, port))
with print_lock:
print("Port:",port,"is open.")
sock.shutdown()
sock.close()
Also, no need to call shutdown if you're going to immediately call close afterwards.
I am attempting to make a simple bluetooth program in python using pybluez. For the server script I have this code:
import bluetooth as bt
HOST = ""
PORT = 8888
s = bt.BluetoothSocket(bt.RFCOMM)
s.bind((HOST,PORT))
s.listen(1)
conn, addr = s.accept()
print("Connected by", addr)
while True:
data = conn.recv(1024)
print(data)
When I attempt to run it I get the Error:
OSError: The requested address is not valid in its context.
I have done extensive research and am unable to find any real cause; it seems to be that pybluez doesn't like to be bound to the address "", but every example I found online said to do that.
I figured out my problem. For RFCOMM connections, the port needs to be even and between 1 and 30. Sorry for any inconvenience.
I'm trying to code a port scanner in python with banner grabbing.
Without the s.send('getBanner\n') line (which grabs the banner) my script works, and it prints the open ports.
But when I add the 'getBanner' line, a socket error says '[Errn 32] Broken Pipe'.
I know that this error probably happens because the clients don't wait till the connection get established and close the socket. How can I solve this?
The code:
import socket
host = '192.168.1.1'
for port in range(1,1024):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = s.connect_ex((host, port))
s.send(('getBanner\n'))
banner = s.recv(1024)
if result == 0:
print "[+] Port %s tcp/open" % port
print "[+] Banner: %s" % banner
s.close()
Not all ports have a service listening on them and when they do, you need to follow whatever protocol is normal for that service. I assume you have some sort of service that responds to "getBanner", but most will not. You are connecting to things like FTP, SSH, DNS, NFS and mail servers and these things don't have "getBanner" commands. But you are also trying to connect to ports that don't have anything listening on them and this generates an error.
Looking at the docs:
connect_ex(...)
connect_ex(address) -> errno
This is like connect(address), but returns an error code (the errno value)
instead of raising an exception when an error occurs.
Your connection call is returning an error code and you need to check that before trying to send the request. So, as a minimum:
import socket
host = '192.168.1.1'
for port in range(1,1024):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = s.connect_ex((host, port))
if result == 0:
s.send(('getBanner\n'))
banner = s.recv(1024)
if result == 0:
print "[+] Port %s tcp/open" % port
print "[+] Banner: %s" % banner
s.close()
But since most servers listening on ports don't respond to a "getBanner" command, its either going to hang or more likely raise connection reset errors.
I am currently working on a server in Python, the problem I am facing is the client could not retrieve the sent data from server.
The code of the server is:
import sys
import socket
from threading import Thread
allClients=[]
class Client(Thread):
def __init__(self,clientSocket):
Thread.__init__(self)
self.sockfd = clientSocket #socket client
self.name = ""
self.nickName = ""
def newClientConnect(self):
allClients.append(self.sockfd)
while True:
while True:
try:
rm= self.sockfd.recv(1024)
print rm
try:
self.sockfd.sendall("\n Test text to check send.")
print "Data send successfull"
break
except socket.error, e:
print "Could not send data"
break
except ValueError:
self.sockfd.send("\n Could not connect properly")
def run(self):
self.newClientConnect()
self.sockfd.close()
while True:
buff = self.sockfd.recv(1024)
if buff.strip() == 'quit':
self.sockfd.close()
break # Exit when break
else:
self.sendAll(buff)
#Main
if __name__ == "__main__":
#Server Connection to socket:
IP = '127.0.0.1'
PORT = 80
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
print ("Server Started")
try:
serversocket.bind(('',5000))
except ValueError,e:
print e
serversocket.listen(5)
while True:
(clientSocket, address) = serversocket.accept()
print 'New connection from ', address
ct = Client(clientSocket)
ct.start()
__all__ = ['allClients','Client']
#--
And the client connecting is:
import socket
HOST = '192.168.1.4' # The remote host
PORT = 5000 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
data = s.recv(1024)
s.close()
print 'Received', data#repr(data)
In need of a quick solution....
Thanks,
I tested out your code, and when I commented out
rm= self.sockfd.recv(1024)
print rm
it worked fine. Basically the server stopped there to wait for a message that never came. If it still does not work for you, there might be two problems. Either you have a firewall that blocks the connection somehow, or you have old servers running in the background from previous tries that actually wasn't killed. Check your processes if pythonw.exe or equivalent is running when it shouldn't be, and kill it.
To wait for response:
with s.makefile('rb') as f:
data = f.read() # block until the whole response is read
s.close()
There are multiple issues in your code:
nested while True without break
finally: ..close() is executed before except ValueError: ..send
multiple self.sockfd.close()
etc
Also you should probably use .sendall() instead of .send().
your server code is excepting client send something first,
rm= self.sockfd.recv(1024)
but I don't see any in your code
please try send something in your client code
s.connect((HOST, PORT))
s.send("hello")
Short solution
Add a short sleep after connect.
import time
time.sleep(3)