1.Java UDP发送数据,自动获取本机地址,本文是获取Linux本地地址,代码实列入下:
package com.zjf.UDP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.net.*;
import java.util.Enumeration;
/**
* 默认发送方式*/
@Service
public class UdpSimpleClient {
private final static Logger logger = LoggerFactory.getLogger(UdpSimpleClient.class);
private org.apache.logging.log4j.Logger log;
public void sendMessage(byte[] message) {
//获取Linux本地地址
String localhost = "";
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) networkInterfaces.nextElement();
Enumeration<InetAddress> nias = ni.getInetAddresses();
while (nias.hasMoreElements()) {
InetAddress ia = (InetAddress) nias.nextElement();
if (!ia.isLinkLocalAddress() && !ia.isLoopbackAddress() && ia instanceof Inet4Address) {
if(ia.getHostAddress().startsWith("10.")){
localhost = ia.getHostAddress();
}
}
}
}
} catch (SocketException e) {
log.error("error",e);
}
//发送数据到指定的IP地址和端口
//InetSocketAddress inetSocketAddress = new InetSocketAddress("188.188.12.6", 3408);
//自动获取IP地址并发送到指定端口
DatagramPacket datagramPacket = null;
try (DatagramSocket datagramSocket = new DatagramSocket()) {
//datagramPacket = new DatagramPacket(message, message.length, inetSocketAddress);
datagramPacket = new DatagramPacket(message, message.length, InetAddress.getByName(localhost),3408);
datagramSocket.send(datagramPacket);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
//logger.info("发送成功");
}
}
2.项目源代码:Java UDP项目源码