changing the port 80 if it was busy - python

i have an assignment to make a web server on the TCP by using LAN , the project is to make a request to localhost on port 80 and present "hi" in a browser and to present "404 not found" if the request is wrong, i have a problem with being port 80 is busy, it stop working when using any port but 80, the hint from the assignment is "If you run your server on a host that already has a Web server running on it, then you should use a different port than port 80 for your Web server." and my code is :
from socket import *
import os
def test():
serverPort = 80
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('', serverPort))
serverSocket.listen(1)
print("web server on port", serverPort)
while True:
print("ready to serve")
connectionSocket, addr = serverSocket.accept()
try:
message = connectionSocket.recv(1024)
print(message)
filename = message.split()[1]
print(filename[1:])
print(filename, '||', filename[1])
f = open(filename[1:])
outputdata = f.read()
connectionSocket.send(outputdata.encode())
connectionSocket.close()
except Exception:
print("404 Not Found")
connectionSocket.send("""404 Not Found\r\n""".encode())
pass
pass
if __name__ == "__main__":
test()

simply you need to check if port already in use or not
def check(port):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
return s.connect_ex(('localhost', serverPort)) == 0

Related

WinError 10061 when trying to connect to socket

In Python, I made a client.py and server.py with some simple socket code.
server.py:
import socket
HEADERSIZE = 10
PORT = 1235
ADDR = "192.168.198.1" # this is my local IP found from ipconfig in cmd
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((ADDR, PORT))
s.listen(5)
while True:
client, address = s.accept()
print(f'Connection from {address} established')
msg = "Hello Client"
msg = f'{len(msg):<{HEADERSIZE}}'+msg
client.send(bytes(msg, "utf-8"))
client.py:
import socket
HEADERSIZE = 10
ADDR = "67.xxx.xxx.xx" # my public IP found from whatsmyip.com
PORT = 1235
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ADDR, PORT))
while True:
full = ''
new = True
while True:
msg = s.recv(16)
if new:
msglen = int(msg[:HEADERSIZE])
new = False
full += msg.decode("utf-8")
if len(full) - HEADERSIZE == msglen:
new = True
full = ''
print(full)
Previously, I had the addresses in both programs set to socket.gethostname() because I was working on my computer only. When I sent the client to my friend to test it out with the updated information you see here, I get this error code:
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
The same thing happens when I run it on my computer.
I'm very new to sockets / networking, so I apologize if I'm missing something obvious, but I've been having issues with this and any help is appreciated

Check If Port is Open in Python3?

In python 3 Given an IP address, I want to check if a specefic port is open for TCP Connection. How can I do that?
Please Note, I don't want to wait at all. If no response was recieved immediately then just report it's closed.
This is a Python3 example I got from https://www.kite.com/python/answers/how-to-check-if-a-network-port-is-open-in-python
import socket
a_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 8080
location = ("127.0.0.1", port)
check = a_socket.connect_ex(location)
if check == 0:
print("Port is open")
else:
print("Port is not open")
You can use simple script
#!/usr/bin/python
import socket
host = "127.0.0.1"
port = 9003
# try to connect to a bind shell
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
print(f"Port {port} is open")
s.close()
except socket.error:
print(f"Port {port} closed.")
Constant socket.SOCK_STREAM here response for TCP connection.
You can do something like this to check if a port is taken or if it's open:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
location = ("127.0.0.1", 80)
result = sock.connect_ex(location)
if result == 0:
print("Port is open")
else:
print("Port is closed")
In this, the socket.AF_INET specifies the IP address family (IPv4) and socket.SOCK_STREAM specifies the socket type (TCP).

Please help me in socket programming in python

Problem while making connection with server.
server side:
import socket
import threading
import sys
ip = "let ip address of server, cant type real one for security purposes, example: 1.2.3.4"
port = 9999
def make_socket(ip, port):
global server
try:
server = socket.socket()
server.bind((ip, port))
except:
make_socket(ip, port)
def handle_client(conn, addr):
print(f"Connected with {addr}\n")
connected = True
while connected:
msg = conn.recv(1024).decode("utf-8")
if msg == "exit()":
connected = False
if len(msg) > 0:
print(f"CLIENT: {msg}")
if connected:
msg = input("You: ")
if len(msg) > 0:
conn.send(msg.encode("utf-8"))
conn.close()
def make_connection():
server.listen(2)
while True:
conn, addr = server.accept()
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
print(f"ACTIVE CONNECTIONS:{threading.activeCount() - 1}")
print("SERVER INITIATED.")
make_socket(ip, port)
make_connection()
client side:
import socket
ip = "same address as written in server side, example: 1.2.3.4"
port = 9999
client = socket.socket()
client.connect((ip, port))
def send(msg):
message = msg.encode("utf-8")
client.send(message)
run = True
while run:
msg = input("You: ")
if msg == "exit()":
send(msg)
run = False
else:
send(msg)
print(f"Server: {client.recv(100).decode('utf-8')}")
It runs as expected in the same pc.
But when I am running client script and server script in 2 different pcs, they are not connecting. Even though the address is same. I have to type the ip address of server in server.bind and client.connect, right? They both should be same, right?
The IP address you pass to client.connect() should be the IP address of the computer where the server is running (if it's the same computer as where the client is running, you can just pass 127.0.0.1 as that address always means localhost). For the bind() call I recommend passing in '' (i.e. an empty string) as the address, so that your server will accept incoming connections from any active network interface. You only need to pass in an explicit IP address to bind() if you want limit incoming connections to only those coming through the local network card that is associated with the specified IP address.

Python - error when making a socket connection (server - target)

(Using Python 3) I am trying to connect server and client and symply send a message from one to another but I don't know why I get this strange error: OSError: [WinError 10057]. Does anyone know why it happened? I did a bit of reaserch but didn't find anything, I think I made an error when making global variables, or is it somenthing with message encoding and decoding?
Here is my full error:
File "server_side.py", line 34, in
shell()
File "server_side.py", line 6, in shell
s.send(command.encode('utf-8'))
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a
sendto call) no address was supplied
Here is my server_side code:
import socket
def shell():
command = input('[+] Insert command: ')
s.send(command.encode('utf-8'))
message = target.recv(1024)
print(message.decode('utf-8'))
s = ''
target = ''
ip = ''
def server():
global s
global target
global ip
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
s.bind(('192.168.1.109', 54321))#target ip, port more bit isti
s.listen(5)
print('[+] Listening for connections')
target, ip = s.accept()
print('[+] Connection established from: %s' %str(ip))
server()
shell()
And this is my client_side code:
import socket
def shell():
command = sock.recv(1024)
message = 'Hello there'
sock.send(message.encode('utf-8'))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('192.168.1.109', 54321)) #home ip
shell()
sock.close()
My command input on server_side example vould be the word : Hello, or somenthing like that.
You have to put the shell() function in a infinite loop, and you have to run the server_side code and then the client_side code.
Here is a bit changed code:
Server side code:
import socket
def shell():
command = input('[+] Insert command: ')
s.send(command.encode('utf-8'))
message = target.recv(1024)
print(message.decode('utf-8'))
s = ''
target = ''
ip = ''
def server():
global s
global target
global ip
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
s.bind(('192.168.1.109', 54321))#target ip, port more bit isti
s.listen(5)
print('[+] Listening for connections')
target, ip = s.accept()
print('[+] Connection established from: %s' %str(ip))
while True:
server()
shell()
s.close()
Client side code:
import socket
def shell():
command = sock.recv(1024)
message = 'Hello there'
sock.send(message.encode('utf-8'))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('192.168.1.109', 54321)) #home ip
while True:
shell()
sock.close()

How to send messages to a remote computer using python socket module?

I'm trying to send a message from a computer to a another computer that is not connected to the other computer local network.
I did port forwarding (port 8080, TCP) and I didn't manage to get the remote computer to connect and to send the message.
when i try to connect it's just getting stuck on the connect method (client).
I also need to mention that I'm open to change anything in the router settings.
the client code (remote computer):
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("%My public IP address%", 8080))
msg = s.recv(1024)
msg = msg.decode("utf-8")
print(msg)
the server code:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("192.168.0.2", 8080))
s.listen(5)
while True:
clientsocket, address = s.accept()
print(f"Connection from {address} has been established.")
clientsocket.send(bytes("Hey there!!", "utf-8"))
clientsocket.close()
From my understanding, your aim is to connect to a server from a remote computer and send a message from the server to the client. As such, all it requires is the client to connect to the external-facing IP address of your server. Once that is done, router simply forwards the traffic according to the port forwarding rules.
Server:
import socket
def Main():
host = '10.0.0.140'
port = 42424
s = socket.socket()
s.bind((host, port))
s.listen(1)
c, addr = s.accept()
while True:
data = c.recv(1024)
if not data:
break
data = str(data).upper()
c.send(data)
c.close()
if __name__ == '__main__':
Main()
Client:
import socket
def Main():
host = '10.0.0.140' #The host on your client needs to be the external-facing IP address of your router. Obtain it from here https://www.whatismyip.com/
port = 42424
s = socket.socket()
s.connect((host,port))
message = raw_input("->")
while message != 'q':
s.send(message)
data = s.recv(1024)
message = raw_input("->")
s.close()
if __name__ == '__main__':
Main()
Also do note that, When connecting to a server behind a NAT firewall/router, in addition to port forwarding, the client should be directed to the IP address of the router. As far as the client is concerned, the IP address of the router is the server. The router simply forwards the traffic according to the port forwarding rules.

Categories

Resources