-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathUDPPoke.java
More file actions
75 lines (65 loc) · 2.15 KB
/
UDPPoke.java
File metadata and controls
75 lines (65 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import java.io.*;
import java.net.*;
public class UDPPoke {
private int bufferSize; // in bytes
private int timeout; // in milliseconds
private InetAddress host;
private int port;
public UDPPoke(InetAddress host, int port, int bufferSize, int timeout) {
this.bufferSize = bufferSize;
this.host = host;
if (port < 1 || port > 65535) {
throw new IllegalArgumentException("Port out of range");
}
this.port = port;
this.timeout = timeout;
}
public UDPPoke(InetAddress host, int port, int bufferSize) {
this(host, port, bufferSize, 30000);
}
public UDPPoke(InetAddress host, int port) {
this(host, port, 8192, 30000);
}
public byte[] poke() {
try (DatagramSocket socket = new DatagramSocket(0)) {
DatagramPacket outgoing = new DatagramPacket(new byte[1], 1, host, port);
socket.connect(host, port);
socket.setSoTimeout(timeout);
socket.send(outgoing);
DatagramPacket incoming
= new DatagramPacket(new byte[bufferSize], bufferSize);
// next line blocks until the response is received
socket.receive(incoming);
int numBytes = incoming.getLength();
byte[] response = new byte[numBytes];
System.arraycopy(incoming.getData(), 0, response, 0, numBytes);
return response;
} catch (IOException ex) {
return null;
}
}
public static void main(String[] args) {
InetAddress host;
int port = 0;
try {
host = InetAddress.getByName(args[0]);
port = Integer.parseInt(args[1]);
} catch (RuntimeException | UnknownHostException ex) {
System.out.println("Usage: java UDPPoke host port");
return;
}
try {
UDPPoke poker = new UDPPoke(host, port);
byte[] response = poker.poke();
if (response == null) {
System.out.println("No response within allotted time");
return;
}
String result = new String(response, "US-ASCII");
System.out.println(result);
} catch (UnsupportedEncodingException ex) {
// Really shouldn't happen
ex.printStackTrace();
}
}
}