Java聊天服务器-";无法分配请求的地址:数据报发送失败;?

Java聊天服务器-";无法分配请求的地址:数据报发送失败;?,java,Java,我必须编写一个简单的java聊天服务器,在其中存储对等IP地址列表。当我发送消息时,我必须循环遍历每个地址并将其发送给每个对等方。这是我的代码: import java.util.*; import java.net.*; import java.io.*; class ChatServer{ static LinkedList<String> peerList; static int port; private final static int PACKETSIZE = 100

我必须编写一个简单的java聊天服务器,在其中存储对等IP地址列表。当我发送消息时,我必须循环遍历每个地址并将其发送给每个对等方。这是我的代码:

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());
    }
}
}
我发现问题出在localhost上,就好像我把它取出来一样,消息会被发送到我的本地地址。我已经检查并再次检查了我的etc/hosts文件,并且localhost配置正确,即“
127.0.0.1 localhost
”。控制台肯定是以管理员身份运行的。我还尝试了我的防火墙禁用,所以这不是它


有人知道这是什么原因吗?

我在Windows上尝试了你的代码,使用
127.0.0.1
地址得到了相同的异常,但使用
192.168.0.101
(我的“真实”ip地址)效果很好。在@Eric中发布了一些代码,这些代码可能会帮助您获得包含所有网络接口和ip地址的列表。
"Cannot assign requested address: Datagram send failed".