Port scanner in python3 - python-3.x

I am learning to program in python3, I've been learning for a month, so I decided to try the python's socket module and make a port scanner.
import socket
host = input("Host: ")
port = int(input("Port: "))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((host, port))
except:
print(str(port) + " isnt open")
else:
print(str(port) + " is open")
The issue with the code is that the ports are never open, even the most common ones like 80 or 443.
So I'm asking for you guys to help me fixing eventual bugs.

I think another error is happening.
Have you tried printing the exception inside the except block?
import socket
host = input("Host: ")
port = int(input("Port: "))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((host, port))
except Exception as err:
print(str(port) + " isnt open")
print(err.args) #for debugging
else:
print(str(port) + " is open")
This would let you see the actual error.

Maybe this will help:
import socket
host = str(input("Host: "))
port = int(input("Port: "))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = s.connect_ex((host,port))
if result == 0:
print('Port', port, 'is open')
else:
print('Port', port, 'is closed')

Related

How to connect a python backdoor to No-IP DNS

i'm programing a backdoor in python 3.9.1, My question is how can I connect it to my noip dns, when I use my private ip it works normally, but when I try to use the dns address it gives me an error, here is the code:
import socket
def connection():
global s
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('testtest123.ddns.net', 4445))
s.listen(1)
print("waiting...")
def accept_connections():
global target
target, ip_list = s.accept()
print("connection received from: " + str(ip_list[0]))
def commands():
while True:
command = input('command> ')
bit_encoded_command = str.encode(command)
if command == 'exit':
target.send(bit_encoded_command)
receive = target.recv(1024)
receive_decoded = bytes.decode(receive, "utf-8")
print(receive_decoded)
break
connection()
accept_connections()
commands()
s.close()
and the error is:
"OSError: [WinError 10049] The requested address is not valid in its context"
First of all, I recommend you not to use global variables.
As suggested by the error message, you cannot bind that address to your network interface. Use 0.0.0.0 instead and your program will handle all incoming requests.
You will then have to make sure that testtest123.ddns.net points to the machine running your code and that the port you specified is open (i.e. accessible by everyone on the Internet).
E.g.
import socket
def connection():
global s
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('0.0.0.0', 4445))
s.listen(1)
print("waiting...")
def accept_connections():
global target
target, ip_list = s.accept()
print("connection received from: " + str(ip_list[0]))
def commands():
while True:
command = input('command> ')
bit_encoded_command = str.encode(command)
if command == 'exit':
target.send(bit_encoded_command)
receive = target.recv(1024)
receive_decoded = bytes.decode(receive, "utf-8")
print(receive_decoded)
break
connection()
accept_connections()
commands()
s.close()

Python 3 socket client not connecting to server

I have a server.py and client.py pair. When I run the server on my machine and open multiple terminals to runs clients, I can connect fine. But when I try to run clients on another computer, the client never connects to the server. I'm pretty sure I tested this code a few months ago on multiple computers and it worked fine (though maybe I'm remembering wrong), but I think I updated my python version, so maybe that's why? How can I change my code below so it works?
server.py
import socket
from threading import Thread
import sys
clients = []
def recv(clientsocket):
while True:
msg = clientsocket.recv(1024) # wait for message from any of the clients.
print("\n" + msg.decode())
for c in clients: # send to all the clients.
c.send(msg)
def send(clientsocket):
while True:
msg = "[Server] %s" % input("\n") # wait for input
print(msg)
for c in clients: # send to all the clients.
c.send(msg.encode())
clientsocket.close()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create a socket object
host = socket.gethostname() # Get local machine name
#port = 3001 # Reserve a port for your service.
port = int(input("Enter port: "))
print ('Server started at [%s]' % socket.gethostbyname(host))
print ('Waiting for clients...')
#s.bind((host, port)) # Bind to the port
s.bind((socket.gethostbyname(host), port))
s.listen(5) # Now wait for client connection.
while True:
#Waits until someone new to accept
c, addr = s.accept()
print(addr, "connected.")
clients.append(c)
thread_recv = Thread(target=recv, args=((c,)))
thread_recv.start()
thread_send = Thread(target=send, args=((c,)))
thread_send.start()
s.close()
client.py
import socket
from threading import Thread
hostname = input("Enter hostname/IP to connect to: ")
# port = 3001
port = int(input("Enter port: "))
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect((hostname, port))
def recv():
while True:
print("\n" + clientsocket.recv(2048).decode())
def send(username):
while True:
msg = "[%s] %s" % (username, input(""))
clientsocket.send(msg.encode()) # send message to the server.
username = input("Choose a username: ")
msg = "[%s has just connected]" % (username)
clientsocket.send(msg.encode())
thread_send = Thread(target=send, args=(username,))
thread_send.start()
thread_recv = Thread(target=recv, args=())
thread_recv.start()
while True:
# keep the threads going.
pass
Edit
Every time I start the server, it says my ip address is the same: 192.168.56.1. Even though I've turned my computer off and tried again. But when I go to Google and ask what is my ip address, it is something totally different. Why does the socket keep choosing 192.168.56.1? Is there something special about it? Is this something related to my problem?
Just bind you server to 0.0.0.0 and bind it to all network interfaces:
server.py
s.bind(('0.0.0.0', port))
Then the code in server.py will end up being something like this:
import socket
from threading import Thread
import sys
clients = []
def recv(clientsocket):
while True:
msg = clientsocket.recv(1024) # wait for message from any of the clients.
print("\n" + msg.decode())
for c in clients: # send to all the clients.
c.send(msg)
def send(clientsocket):
while True:
msg = "[Server] %s" % input("\n") # wait for input
print(msg)
for c in clients: # send to all the clients.
c.send(msg.encode())
clientsocket.close()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create a socket object
host = socket.gethostname() # Get local machine name
#port = 3001 # Reserve a port for your service.
port = int(input("Enter port: "))
print ('Server started at [%s]' % socket.gethostbyname(host))
print ('Waiting for clients...')
#s.bind((host, port)) # Bind to the port
s.bind(('0.0.0.0', port))
s.listen(5) # Now wait for client connection.
while True:
#Waits until someone new to accept
c, addr = s.accept()
print(addr, "connected.")
clients.append(c)
thread_recv = Thread(target=recv, args=((c,)))
thread_recv.start()
thread_send = Thread(target=send, args=((c,)))
thread_send.start()
s.close()

How can Python's socket (UDP) be used to connect different machines on different WiFi?

I've been trying to set up a game to play with my friends. We all live in different places and have different IP, WiFi etc. I started coding on my own computer using socket using SOCK_DGRAM. It worked fine when I ran the server and client code on my own computer, but when my friends tried to run the client code they couldn't send anything to my server. No error was thrown, what they sent just wasn't picked up by my server.
Here is the server code:
import socket
host = "192.168.88.191"
port = 2000
connections = Connections() # Where I store my friends' way of contacting the server
player_list = [] # A list of players to be used by my Players class
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
s.setblocking(False)
print("Server started")
while True:
try:
data, addr = s.recvfrom(1024)
got_data = True
except OSError:
got_data = False
if got_data:
if not addr in connections.addresses:
connections.addresses.append(addr) # Store all new addresses
player_list.append(Players(len(player_list))) # Append to player list (don't worry about this part)
data = data.decode("utf-8")
print("Message from " + str(addr) + ": " + data)
player_list[int(addr[1] - 2001)].move(data, player_list) # Function for game logic
message = ""
for player in player_list:
message += str(player.number) + " " + str(player.x) + " " + str(player.y) + "," # Make the message that I want to send
message = message[:-1]
print("Sending: " + message)
for address in connections.addresses:
s.sendto(message.encode("utf-8"), address)
Here is the client code:
class Sock():
def __init__(self):
self.host = "192.168.88.191"
self.port = 2000
self.server = (self.host, 2000)
self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
try:
print("Trying to connect on port " + str(self.port))
self.s.bind((self.host, self.port))
except OSError:
self.port += 1
else:
self.s.setblocking(False)
print("Connected on port " + str(self.port) + "!")
break
def send_data(self, message):
print("Sending: " + message)
self.s.sendto(message.encode("utf-8"), self.server)
def recieve_data(self):
try:
data, addr = self.s.recvfrom(1024)
data = data.decode("utf-8")
print("Recieved from server: " + data)
return data
except socket.error:
pass
My IP is 192.168.88.191. I would assume that my friends need to use their IP in the client code, but where? I know that you can find your IP by doing socket.gethostbyname(socket.gethostname())
EDIT: This client code didn't actually work, it tried every port until it reached the highest port possible and threw an error. We did some adjustments to the code and got it to connect, but the server still didn't recieve anything. The client could send just fine, but the server didn't recieve. I'm not 100% about the adjustment in question, but I think we replaced: self.server = (self.host, 2000) with: self.server = (socket.gethostbyname(socket.gethostname()), 2000) although as I said I don't know if that's exacly what we did.

How to reuse the socket address python?

Here is server side code:
import socket
import sys
HOST = '' # Symbolic name, meaning all available interfaces
PORT = 7800 # 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]))
msg = conn.recv(1024)
s.close()
whenever I use this code for the first time I can easily connect with the client and after second time I get the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"
How could I modify the code that it will work again and again?
Try this line after creating s :
# ...
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# ...
Socket options SO_REUSEADDR and SO_REUSEPORT, how do they differ? Do they mean the same across all major operating systems?

Python UDP client-server with different matching incoming-outgoing ports

Based on the example at http://www.binarytides.com/programming-udp-sockets-in-python/ I modified it to run on python 3 and used two opposed ports on client and server, so replies from each one go to these ports. Here are my examples
Server:
'''
Simple udp socket server
'''
import socket
import sys
HOST = 'localhost'
PORT_IN = 8889 # Arbitrary non-privileged port
PORT_OUT = 8888
# Datagram (udp) socket
try :
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print('Socket created')
except socket.error as e:
print(e)
sys.exit()
# Bind socket to local host and port
try:
s.bind((HOST, PORT_IN))
except socket.error as e:
print(e)
sys.exit()
print('Socket bind complete')
#now keep talking with the client
while 1:
# receive data from client (data, addr)
d = s.recvfrom(1024)
data = d[0]
addr = d[1]
if not data:
break
reply = 'OK...' + str(data)
s.sendto(reply.encode('UTF-8'), ('localhost', PORT_OUT))
print('Message[' + addr[0] + ':' + str(addr[1]) + '] - ' + str(data).strip())
s.close()
Client:
'''
udp socket client
Silver Moon
'''
import socket #for sockets
import sys #for exit
# create dgram udp socket
try:
s1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
except socket.error:
print('Failed to create socket')
sys.exit()
host = 'localhost'
port_out = 8889
port_in = 8888
counter = 0
while(1) :
# msg = b'aoua'
msg = 'aoua' + str(counter)
try :
#Set the whole string
s1.sendto(msg.encode('UTF-8'), (host, port_out))
# receive data from client (data, addr)
s2.bind(('localhost', port_in))
d = s2.recvfrom(1472)
reply = d[0]
addr = d[1]
print('Server reply : ' + str(reply))
except socket.error as e:
print(e)
# sys.exit()
counter += 1
Problem is with the client which cannot receive any response from server and d = s2.recvfrom(1472) hangs with error [WinError 10022] An invalid argument was supplied.
I've noticed a slightly different behaviour with sock.settimeout(seconds), but I really can't figure why. Isn't d = s2.recvfrom(buffer) supposed to wait for incoming data?
What am I missing here?
Damn... Just saw it. Silly mistake. Calling s2.bind(('localhost', port_in)) in Client inside the loop.

Resources