Setting source port on a Java Socket?

后端 未结 5 1463
自闭症患者
自闭症患者 2021-02-20 09:03

I\'m very new to socket programming:

Is it possible to explicitly set the the source port on a Java Socket?

I am working on a client/server application in which

5条回答
  •  自闭症患者
    2021-02-20 09:55

    You can use this call to create socket,

    public Socket(InetAddress address,
                  int port,
                  InetAddress localAddr,
                  int localPort)
           throws IOException
    

    This is normally done for UDP and this is not advised for TCP connections. If you do this for TCP on both ends, you can only have one TCP connection. If you create one more, the socket layer will get confused and you will end up lose all your connections.

    For TCP, the common practice is to reply in the same connection. If you have to reply in a different connection, use a pre-defined ports on client also.

提交回复
热议问题