android udp获取ip,安卓开发 局域网UDP获取服务器Ip地址

  • Post author:
  • Post category:其他

try {

mHandler.post(new myRunnable(“开始UDP连接”));

InetAddress serverAddress = InetAddress.getByName(“255.255.255.255”);//广泛广播地址

byte[] bytesToSend = “test_client”.getBytes();

int servPort = 6000;//与服务端一致的port

try {

DatagramSocket socket = new DatagramSocket();

socket.setSoTimeout(TIMEOUT);

DatagramPacket sendPacket = new DatagramPacket(bytesToSend,bytesToSend.length,serverAddress,servPort);

byte[] buf = new byte[1024];

DatagramPacket receivePacket = new DatagramPacket(buf, buf.length);

int tries = 0;

boolean receivedResponse = false;

do{

socket.send(sendPacket);

try{

socket.receive(receivePacket);

if(!receivePacket.getAddress().equals(serverAddress)){

System.out.println(“接收到了一个个未知来源的数据包”);

}

receivedResponse = true;

}catch(InterruptedIOException e){

tries +=1;

System.out.println(“Time out,”+(MAXTRIES – tries)+ ” more tries….”);

}

}

dae015a5505100014874551dfae5f6df.png

3.结果

if(receivedResponse){

String rcvd = “Received from ” + receivePacket.getAddress() + “, Data=”

+ new String(receivePacket.getData(), 0, receivePacket.getLength());

mHandler.post(new myRunnable(rcvd));

//System.out.println(“Received:”+new String(receivePacket.getData()));

//mHandler.post(new myRunnable(“Received:”+new String(receivePacket.getData())));

}else{

System.out.println(“NO response — giving up.”);

mHandler.post(new myRunnable(“NO response — giving up.”));

}

socket.close();

f1fb162eb4bd047595a82668efe670c4.png