Reza Azimi
Reza Azimi

Reputation: 56

Socket uses random ports and I need a certain one

Here is the problem, I want to create a connection between two computer in two networks in a certain port but when I am running the run I got this message that shows me every single time different ports:

Accepted a connection request from 192.168.1.2:**12345**
DATA

This is the listening code:

import socket
import logging 


serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

serverSocket.bind(("**server's Local ip**",6464))

serverSocket.listen(1)

while(True):
    
    (clientConnected, clientAddress) = serverSocket.accept()
    print("Accepted a connection request from %s:%s"%(clientAddress[0], clientAddress[1])) #[0], ...[1]
    dataFromClient = clientConnected.recv(1024)
    print(dataFromClient.decode())

    clientConnected.send("Hello User".encode())
    user = dataFromClient
    cip = clientAddress
    LOG_FILENAME = '/home/user/listenlog.txt'
    logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
    logging.debug(cip)
    logging.debug(user)
    logging.debug("--------------------------------------------------------")

and this is the client code:

import socket

clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

clientSocket.connect(("**Server's IP**",6464))


data = 'Hello'


clientSocket.send(data.encode())

dataFromServer = clientSocket.recv(1024)

print(dataFromServer.decode())

How should I make the using port static?

Upvotes: 1

Views: 251

Answers (2)

mehran maroofi
mehran maroofi

Reputation: 73

if the connection that you got is public and behind nat it is usual to be a random port because it is from isp or nat device so else i dont think that would be local

Upvotes: 1

Jeremy Friesner
Jeremy Friesner

Reputation: 73101

If you want your client’s socket to be bound to a specific port, you can call bind() on the socket before you call connect() on it.

Note that there is typically no benefit to doing that, however. The downside is that if that port is already in use, the bind() call will fail.

Upvotes: 1

Related Questions