What is the difference between getPort() and getLocalPort() of the Socket class?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Zaid181294
    New Member
    • Mar 2013
    • 7

    What is the difference between getPort() and getLocalPort() of the Socket class?

    Some may say that
    Code:
    getLocalPort()
    returns the "Local Port" and
    Code:
    getPort()
    returns the "remote Port" but what i find interesting yet ironically confusing is that how can be there two ports associated with the same Socket?
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    Because you connect to a port on the remote computer from a port on your computer. You connect to their port 80 from your port 8009 for example. Pretty much every web server uses port 80. If you have multiple websites loaded, they can't very well all use your port 80 as well. In fact, none of them use your port 80. It's reserved for if you want to run a web server yourself.

    Comment

    • Zaid181294
      New Member
      • Mar 2013
      • 7

      #3
      But isn't a Socket like an end point between two communicating entities.for instance,

      server--------------------|socket|-----------------client

      So the question arises that how can we have two end-points in a connection.( I seriously can't grab this one!!!)

      Comment

      • r035198x
        MVP
        • Sep 2006
        • 13225

        #4
        Ports exist on computers not inside some socket object. A computer (whether client or server) always needs to be able to open a port in order for it to communicate with another computer.
        The client computer and the server computer do not both have to open the same port number to be able to communicate. The client can use port X to communicate out but be connecting to port Y of the computer it is communicating with (if that computer is using port Y to communicate out).

        Comment

        • Rabbit
          Recognized Expert MVP
          • Jan 2007
          • 12517

          #5
          Your chart is wrong. It's more like this
          Code:
          ---------------------------socket-----------------------------
          | local socket address    protocol     remote socket address |
          | 10.1.87.251:8008          TCP        10.2.85.12:80         |
          --------------------------------------------------------------
          
          local socket----------------remote socket
          Yes, a socket is an end-point for data transmission. But each computer creates their own socket.

          Comment

          Working...