1package de.gultsch.chat.utils;
2
3import java.io.ByteArrayOutputStream;
4import java.io.IOException;
5import java.net.DatagramPacket;
6import java.net.DatagramSocket;
7import java.net.InetAddress;
8import java.util.Random;
9
10import android.os.Bundle;
11import android.util.Log;
12
13public class DNSHelper {
14 public static Bundle getSRVRecord(String host) {
15 Bundle namePort = new Bundle();
16 try {
17 String[] hostParts = host.split("\\.");
18 byte[] transId = new byte[2];
19 Random random = new Random();
20 random.nextBytes(transId);
21 byte[] header = { 0x01, 0x20, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
22 0x00, 0x01, 0x0c, 0x5f, 0x78, 0x6d, 0x70, 0x70, 0x2d, 0x63,
23 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x04, 0x5f, 0x74, 0x63, 0x70 };
24 byte[] rest = { 0x00, 0x00, 0x21, 0x00, 0x01, 0x00, 0x00, 0x29,
25 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
26 ByteArrayOutputStream output = new ByteArrayOutputStream();
27 output.write(transId);
28 output.write(header);
29 for (int i = 0; i < hostParts.length; ++i) {
30 char[] tmpChars = hostParts[i].toCharArray();
31 byte[] tmp = new byte[tmpChars.length];
32 for (int j = 0; j < tmpChars.length; ++j) {
33 tmp[j] = (byte) tmpChars[j];
34 }
35 output.write(tmp.length);
36 output.write(tmp);
37 }
38 output.write(rest);
39 byte[] sendPaket = output.toByteArray();
40 byte[] addr = { 0x8, 0x8, 0x8, 0x8 };
41 int realLenght = sendPaket.length - 11;
42 DatagramPacket packet = new DatagramPacket(sendPaket,
43 sendPaket.length, InetAddress.getByAddress(addr), 53);
44 DatagramSocket datagramSocket = new DatagramSocket();
45 datagramSocket.send(packet);
46 byte[] receiveData = new byte[1024];
47
48 DatagramPacket receivePacket = new DatagramPacket(receiveData,
49 receiveData.length);
50 datagramSocket.setSoTimeout(2000);
51 datagramSocket.receive(receivePacket);
52 if (receiveData[3]!=-128) {
53 namePort.putString("error", "nosrv");
54 return namePort;
55 }
56 namePort.putInt("port",calcPort(receiveData[realLenght + 16],
57 receiveData[realLenght + 17]));
58 int i = realLenght + 18;
59 int wordLenght = 0;
60 StringBuilder builder = new StringBuilder();
61 while (receiveData[i] != 0) {
62 if (wordLenght > 0) {
63 builder.append((char) receiveData[i]);
64 --wordLenght;
65 } else {
66 wordLenght = receiveData[i];
67 builder.append(".");
68 }
69 ++i;
70 }
71 builder.replace(0, 1, "");
72 namePort.putString("name",builder.toString());
73 } catch (IOException e) {
74 Log.d("xmppService","gut" + e.getMessage());
75 }
76 return namePort;
77 }
78
79 static int calcPort(byte hb, byte lb) {
80 return ((int) hb << 8) | ((int) lb & 0xFF);
81 }
82
83 final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
84 public static String bytesToHex(byte[] bytes) {
85 char[] hexChars = new char[bytes.length * 2];
86 for ( int j = 0; j < bytes.length; j++ ) {
87 int v = bytes[j] & 0xFF;
88 hexChars[j * 2] = hexArray[v >>> 4];
89 hexChars[j * 2 + 1] = hexArray[v & 0x0F];
90 }
91 return new String(hexChars);
92 }
93}