JAVA获取本地IP和PORT

项目中要用到DatagramSocket,同时也要获取本地的IP和PORT,直接创建并获取端口获取的IP总是0.0.0.0,代码如下:

	private static void testGetDatagramSocket() {
		try {
			DatagramSocket socket = new DatagramSocket();
			System.out.println(socket.getLocalSocketAddress());
			socket.close();
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}

输出结果:

0.0.0.0/0.0.0.0:55816

查了些资料,比如查询可用端口并绑定,没有现成方法,好像实现不了。个中原因也没太多时间去细究,好像是还没和网卡关联(纯属个人YY)。由于项目对本地端口没有特别要求,自己写了一个方法获取DatagramSocket,如下:

	/**
	 * 从最大端口开始向下遍历,有可能端口就返回
	 * @return DatagramSocket,为null的可能性极小
	 */
	public static DatagramSocket getDatagramSocket(){
		DatagramSocket socket = null;
		int port = 65535;
		while(port>0){
			try {
				socket = new DatagramSocket(new InetSocketAddress(InetAddress.getLocalHost(), --port));
				System.out.println(port);
				break;
			} catch (SocketException e) {
				e.printStackTrace();
				continue;
			} catch (UnknownHostException e) {
				e.printStackTrace();
				continue;
			}
		}
		return socket; 
	}

出现异常继续运行,代价使用者自行斟酌。

附上全部测试代码:

package com.ttdevs.java.test;

import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class MainTest {

	public static void main(String[] args) {
		testGetDatagramSocket();
		testGetUDPSocketInfo();
		testGetLocalHost();
	}

	private static void testGetDatagramSocket() {
		try {
			DatagramSocket socket = new DatagramSocket();
			System.out.println(socket.getLocalSocketAddress());
			socket.close();
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}

	private static void testGetUDPSocketInfo() {
		DatagramSocket socket = getDatagramSocket();
 		System.out.println(socket.getLocalSocketAddress());
 		socket.close();
	}
	/**
	 * 从最大端口开始向下遍历,有可能端口就返回
	 * @return DatagramSocket,为null的可能性极小
	 */
	public static DatagramSocket getDatagramSocket(){
		DatagramSocket socket = null;
		int port = 65535;
		while(port>0){
			try {
				socket = new DatagramSocket(new InetSocketAddress(InetAddress.getLocalHost(), --port));
				System.out.println(port);
				break;
			} catch (SocketException e) {
				e.printStackTrace();
				continue;
			} catch (UnknownHostException e) {
				e.printStackTrace();
				continue;
			}
		}
		return socket; 
	}
	
	private static void testGetLocalHost() {
		try {
			InetAddress address = InetAddress.getLocalHost();
			System.out.println(address.getHostAddress());
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值