java.net.SocketException: Can't assign requested address

问题描述

使用下面的代码创建一个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

简单的说

两种方法

  1. 关闭无线连接使用有线连接解决.
  2. 在jvm的启动参数中添加-Djava.net.preferIPv4Stack=true.

以上两种方法都可以解决这个问题

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值