X Y
X Y

Reputation: 259

I am getting a different port number than I use

I have 2 java programs, Server and Client.

I am trying to connect the client program to the server program using java socket programming.

Here is the Server program :

public class ServerX {
   public static void main(String[] args) {
    ServerSocket ss = new ServerSocket(987);
    Socket s = ss.accept();
    InetSocketAddress isa1 = (InetSocketAddress) s.getRemoteSocketAddress();
    System.out.println(isa1.getPort()); 
    ss.close();
  }
}

And here is the Client program :

public class ClientX {
   public static void main(String[] args) {
      Socket s = new Socket("ip of the server", 987);
      s.close();
   }
}

I expected that isa1.getPort() in the Server program gives 987, but it actually gives 52532 instead. So what is the problem, and what 53532 means?

Upvotes: 1

Views: 543

Answers (2)

Saiprasad Bane
Saiprasad Bane

Reputation: 487

Not sure on requirement over here. But if you wish to perform a sanity check on Static port and usage of Java is not a pre-cursor, then I feel below script must help you. I had referred to Python Docs (https://docs.python.org/2.6/library/socket.html) for getting help in past for one of my project requirement.

'''    Simple socket server using threads
'''
import socket
import sys
HOST = ''   # Symbolic name, meaning all available interfaces
PORT = 61901 # 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])
s.close()

Herein PORT = 61901 can be replaced with required port.

Upvotes: 1

Saeed Alizadeh
Saeed Alizadeh

Reputation: 1467

TCP is a full duplex communication protocol it means both side of an established connection allowed to send and received data.

so server is listening on port 987 but client side also need a port on it's own side to receive data that is being sent from server side and about the connection in case of ClientX, server will listen to incoming requests on port number 987 but if want sent something as reply to ClientX will write on port 53532 of the connection

Upvotes: 1

Related Questions