Setting source port on a Java Socket?

后端 未结 5 1443
自闭症患者
自闭症患者 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:50

    First, I will totally recomend you to use Java NIO.

    DatagramChannel udpchannel = DatagramChannel.open();
    DatagramSocket udpsocket = udpchannel.socket();
    SocketAddress sa = new InetSocketAddress(BIND_ADDRESS, BIND_PORT);
    udpsocket.bind(sa);
    

    Second, by using the binding to a socket address you will also be able to define to which network address you will be connected to. It means that if you set BIND_ADDRESS to "0.0.0.0" you will be able to listen from every network card connected to your server; but if you set BIND_ADDRESS to, for example, "10.190.0.1" you will only receive requests listened on such address.

提交回复
热议问题