mardi 27 janvier 2015

Python/Sockets - How to bind external ports?


Below is the code I'm using to try to connect to an external IP address using sockets in Python 3.4.


Server Code:



from socket import *
from threading import *

print(gethostname() + "\n" + gethostbyname(gethostname()))
serversocket = socket(AF_INET, SOCK_STREAM)
host = "localhost"
port = 44000
print("Address: %s\nPort: %s" % (host, 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 True:
print("Client:", self.sock.recv(1024).decode())
self.sock.send(b"Server: Message received.")

serversocket.listen(5)
print("Server: Started and listening...")
while True:
clientsocket, address = serversocket.accept()
client(clientsocket, address)


Client Code:



from socket import *

s = socket(AF_INET, SOCK_STREAM)
host = input("Server address: ")
port = int(input("Server port: "))
try:
s.connect((host, port))
s.send(b"Connection Established")
except Exception as e:
print(e)

def send(str):
s.send(message.encode())
data = s.recv(1024).decode()
print(data)

while True:
message = input("> ")
send(s)

s.close()


The problem I face is that whenever I attempt to bind to a port that is not "localhost" or "127.0.0.1", I get the "[WinError 10049] The requested address is not valid in its context". Does anyone know how to bind to external ports? If port forwarding is necessary, can Python port forward itself?





Aucun commentaire:

Enregistrer un commentaire