Setting source port on a Java Socket?

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

    When using datagram sockets, the source address and port is set by the socket when the datagram is sent.

    InetAddress sourceAddr = InetAddress.getLocalHost();
    DatagramSocket sock = new DatagramSocket(sourcePort, sourceAddr);
    DatagramPacket msg = new DatagramPacket(mbuf, mbuf.length, dstIP, dstPort);
    
    sock.send(msg); // sent from sourcePort to dstPort
    

    sourceAddr is a little redundant in this example, new DatagramSocket(sourcePort) would bind to the preferred best-choice address, but if you need to specify the source IP in addition to port, that's how.

    For both types of socket, using bind(new InetSocketAddress(port)) will choose an appropriate local source address and the specified port, and port 0 will choose an appropriate local port as well.

    All retrievable with getLocalAddress() and getLocalPort().

提交回复
热议问题