I have UDP socket as below. I need to send back data to the client. I tried to capture both the ip and port but it shows me as Port is : -1 and InetAddress : null. What can I do to rectify on this?

class ReceiverThread implements Runnable {
    private DatagramSocket  receivedSocketConn1;
    ReceiverThread(DatagramSocket  receivedSocketConn1) {
      System.out.println("Thread Received");
    public void run(){
        while (true){
             InetAddress IPAddress = receivedSocketConn1.getInetAddress();
             int port = receivedSocketConn1.getPort();

             final byte[] buffer = new byte[1024];
             final DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
             String sentence = new String( receivePacket.getData());                   
             System.out.println("RECEIVED: " + sentence); 
             byte[] sendData = new byte[50];
             String capitalizedSentence = "OK\r\n\n";
             sendData = capitalizedSentence.getBytes();
             System.out.println("Port is : "+port);
             System.out.println("InetAddress : "+IPAddress);

             DatagramPacket sendPacket =  new DatagramPacket(sendData, sendData.length, IPAddress, port);                   
            catch(Exception e){
                System.out.println("MyError:Socket Accepting has been caught in main loop."+e.toString());
   public static void main(String[] args) {
       new commUDP9000();
   commUDP9000() {     
               final DatagramSocket  serverSocketConn = new DatagramSocket (9000);
               new Thread(new ReceiverThread(serverSocketConn)).start();                            

      catch (Exception e) 
         System.out.println("MyError:Socket Conn has been caught in main loop."+e.toString());

Recommended Answers

Try getRemoteSocketAddress() instead of getInetAddress()

Jump to Post

All 3 Replies

Try getRemoteSocketAddress() instead of getInetAddress()

Dear James,
           How about the port number ? 

The returned value is really a InetSocketAddress, so cast the returned value to that, then call its getPort() method

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.