DNSService.java
back to DNS queries in Java
01 //
02 // DNSService.java
03 //
04 // DNS Service wrapper.
05 //
06 // Copyright 1997 W. Scott Means (http://smeans.com)
07 //
08 // Licensed under the Apache License, Version 2.0 (the "License");
09 // you may not use this file except in compliance with the License.
10 // You may obtain a copy of the License at
11 //
12 // http://www.apache.org/licenses/LICENSE-2.0
13 //
14 // Unless required by applicable law or agreed to in writing, software
15 // distributed under the License is distributed on an "AS IS" BASIS,
16 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 // See the License for the specific language governing permissions and
18 // limitations under the License.
19 //
20
21 import java.net.Socket;
22 import java.net.InetAddress;
23 import java.io.ByteArrayOutputStream;
24 import java.io.BufferedInputStream;
25 import java.io.IOException;
26
27 public class DNSService
28 {
29 public static int DNS_SOCKET = 53;
30 private static InetAddress m_iaDNS = null;
31 private static InetAddress m_iaAltDNS = null;
32 private static Socket m_sockService = null;
33 private static byte[] m_abReceive = new byte[512];
34
35 private static int m_iQuerySerial = 0x1234;
36
37 public static void SetDNSAddress(InetAddress iaDNS, InetAddress iaDNSAlt) {
38 m_iaDNS = iaDNS;
39 m_iaAltDNS = iaDNSAlt;
40
41 if (m_sockService == null) {
42 try {
43 m_sockService = new Socket(m_iaDNS, DNS_SOCKET, false);
44 } catch (IOException ioe) {
45 System.err.println("exception: " + ioe.getMessage());
46 }
47 }
48 }
49
50 public static boolean PerformDNSQuery(DNSQuery dns) {
51 if (m_iaDNS == null || dns == null) {
52 return false;
53 }
54
55 ByteArrayOutputStream bas = new ByteArrayOutputStream();
56
57 dns.WriteQuery(bas);
58
59 try {
60 m_sockService.getOutputStream().write(bas.toByteArray());
61 } catch (IOException ioe) {
62 return false;
63 }
64
65 try {
66 BufferedInputStream bis = new BufferedInputStream(m_sockService.getInputStream(), 512);
67
68 int cRetry = 5;
69 int cbAvail = 0;
70
71 while (cRetry-- > 0 && ((cbAvail = bis.available()) <= 0)) {
72 try {
73 Thread.currentThread().sleep(2000);
74 } catch (InterruptedException ie) {
75 System.err.println("exception: " + ie.getMessage());
76 }
77 }
78
79 if (cbAvail > 0) {
80 int cbRead = bis.read(m_abReceive, 0, cbAvail);
81
82 m_iQuerySerial++;
83
84 if (cbRead > 0) {
85 dns.ReadQuery(m_abReceive, cbRead);
86 } else {
87 return false;
88 }
89 } else {
90 return false;
91 }
92 } catch (IOException ioe) {
93 return false;
94 }
95
96 return true;
97 }
98 }
|
|
Java2html
|