问题描述
使用下面的代码创建一个udp的接收的时候抛了异常.注意我的电脑操作系统是macOS;
package com.test;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
public class EgdwUdpServer {
public static void main(String[] args) throws IOException {
MulticastSocket socket = new MulticastSocket(8888);
socket.joinGroup(InetAddress.getByName("225.0.0.1"));
byte[] bytes = new byte[30];
DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
socket.receive(packet);
System.out.println(new String(packet.getData(), 0, packet.getLength()));
socket.close();
}
}
Exception in thread "main" java.net.SocketException: Can't assign requested address
at java.net.PlainDatagramSocketImpl.join(Native Method)
at java.net.AbstractPlainDatagramSocketImpl.join(AbstractPlainDatagramSocketImpl.java:178)
at java.net.MulticastSocket.joinGroup(MulticastSocket.java:323)
at com.test.EgdwUdpServer.main(EgdwUdpServer.java:13)
解决方法
stackoverflow的解决方法
This was caused by an IPv6 address being returned from java.net.NetworkInterface.getDefault(). I’m on a Macbook and was using wireless – p2p0 (used for AirDrop) was returned as the default network interface but my p2p0 only has an IPv6 ether entry (found by running ipconfig).
Two solutions, both of which worked for me (I prefer the first because it works whether you are using a wired or wireless connection)
Start the JVM with -Djava.net.preferIPv4Stack=true. This caused java.net.NetworkInterface.getDefault() to return my vboxnet0 network interface – not sure what you’ll get if you’re not running a host-only VM.
Turn off wireless and use a wired connection
简单的说
两种方法
- 关闭无线连接使用有线连接解决.
- 在jvm的启动参数中添加-Djava.net.preferIPv4Stack=true.
以上两种方法都可以解决这个问题