2

I have to write a simple java chat server where I store a list of peer IP addresses. When I send a message, I have to loop through each of the addresses and send it to each peer. Here is my code:

import java.util.*;
import java.net.*;
import java.io.*;

class ChatServer{

static LinkedList<String> peerList;
static int port;
private final static int PACKETSIZE = 100;

public static void main(String args[]){

    peerList = new LinkedList<String>();

    peerList.add("127.0.0.1");
    peerList.add("192.168.0.100");

    try{
        InetAddress inetAddress = InetAddress.getLocalHost();
        port = Integer.parseInt(args[0]);

        DatagramSocket clientSocket = new DatagramSocket(port, inetAddress);

        BufferedReader br = (new BufferedReader(new InputStreamReader(System.in)));
        String msg;

        byte[] sendData = new byte[PACKETSIZE];
        byte[] receiveData = new byte[PACKETSIZE];

        while(true){
            System.out.println("Enter your message: ");
            msg = br.readLine() + "\r\n";
            sendData = msg.getBytes();

            itr = peerList.listIterator(0);
            while (itr.hasNext()){
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, inetAddress.getByName(itr.next().toString()), port);
                clientSocket.send(sendPacket);
            }

            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length, inetAddress, port);
            clientSocket.receive(receivePacket);
            System.out.println("FROM:" + receivePacket.getAddress() + ":" + new String(receivePacket.getData()));

        }
    }
    catch(Exception e){
        System.out.println(e.getMessage());
    }
}
}

As you can see I tried it with localhost and my local IP address and I got the message :

"Cannot assign requested address: Datagram send failed".

I discovered that the problem lies with localhost, as if I take it out the message gets sent to my local address. I have checked and double checked my etc/hosts file and localhost is configured correctly i.e. "127.0.0.1 localhost". Console is definitely being run as administrator. I also tried it with my firewall disabled so that's not it.

Does anyone know what could be causing this?

Imane Fateh
  • 2,418
  • 3
  • 19
  • 23
Rob Gane
  • 21
  • 2
  • 1
    I tried your code on Windows and got the same exception using `127.0.0.1` address but it worked fine using `192.168.0.101` (my "real"ip address). In [this question](http://stackoverflow.com/questions/2381316/java-inetaddress-getlocalhost-returns-127-0-0-1-how-to-get-real-ip) @Eric posted some code that might help you to get a list with all your network interfaces and ip addresses. – dic19 Aug 24 '13 at 12:31

0 Answers0