3

I have a DatagramSocket via which UDP packet are sent from client to server and vice versa. I have to include IP source address in reply packet to client. Is there a way to obtain such as IP address using Java?

I add some clarification I have no control in UDP client, this is a thirt party client. I can only have control in UDP server. So I cannot use DatagramPacket.getAddress() in client source code but only in server source code. I know that is not necessary to include IP Address source in the datagram packet since the source IP address is always available to the receiver (from UDP header I think) but in my case I have sort of handshake between client and server so I have to include server Address in UDP payload data.

CLIENT 192.168.x.x send UDP packet to SERVER 192.168.255.255:8010 in reply to this server should send back to client a replay datagramPacket in wich I should Add the server address (es 192.168.y.y)

pikimota
  • 241
  • 1
  • 4
  • 15

2 Answers2

2

Answer to your updated question:
Get the IP address of your server "Getting the IP address of the current machine using Java" and include it in the payload that you send to your client.

Community
  • 1
  • 1
TmTron
  • 17,012
  • 10
  • 94
  • 142
  • DatagramPacket.getAddress() returns IP client address, in my case I wish to have server IP address. Client send an UDP packet to my server (let's say **receivedPacket**), I have to create a reply packet for the client in wich I put the serverIpAddress – pikimota Feb 27 '17 at 09:01
  • @pikimota No it doesn't. It returns the *source* IP address. – user207421 Feb 27 '17 at 09:03
  • Ok, but I have to add this information to UPD payload, not just the UDP header – pikimota Feb 27 '17 at 09:04
  • @pikimota No you don't. The source IP address is always available to the receiver. If the receiver is Java, it is via exactly this method. If the receiver is calling the Berkeley Sockets API, it is available via the fourth parameter of `recvfrom()` and friends. You do not have to add it to the payload. – user207421 Feb 27 '17 at 09:05
0

I have to include IP source address in reply packet to client

No you don't. It's already in there. The client only has to call DatagramPacket.getAddress()/getPort()/getSocketAddress().

If this is for the purpose of sending a reply, the easy way is to reuse the received DatagramPacket and just change the data, leaving the address information alone.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • So what's your question? You know what your source IP address is, you have the `DatagramPacket`, what's the problem?? – user207421 Feb 27 '17 at 09:27