Java UDP server not decoding correct IP address
I am trying to make a client server application using java UDP. when the server takes in the message from the client it should decode the IP address and port number so that it can send back the data. the problem is when the IP address is decoded from the packet is has a / in the front so it cannot return a message. the output for the program is as follows
waiting for data RECEIVED: message /178.179.35.1 56798
how should I remove the / from the begining o开发者_如何学Cf the IP address being decoded from the packet? THANKS!
import java.io.*;
import java.net.*;
class UDPServer {
public static void main(String args[]) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true) {
System.out.println("waiting for data");
DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
System.out.println(IPAddress);
SocketAddress newtry = receivePacket.getSocketAddress();
int port = receivePacket.getPort();
System.out.println(port);
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, newtry);
serverSocket.send(sendPacket);
}
}
}
Use InetAddress.getHostAddress() to get the textual representation of the IP.
However, looking at your code, can you paste the error that you're getting. You should just be using the InetAddress object anyway, so something else might be happening.
You don't need to do any of that. The DatagramPacket already has the source IP address and port in it. Just alter the data and send the same DatagramPacket. Actually your code should probably work as-is - if it is failing the reason is not the /, that's only what's being displayed.
I have used the program. I was not able to get the IP address when my IP address was dynamic. Then I upgraded my system IP and took a static IP for this purpose.
精彩评论