-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathPing.java
More file actions
67 lines (51 loc) · 1.9 KB
/
Copy pathPing.java
File metadata and controls
67 lines (51 loc) · 1.9 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
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
public class Ping {
public final static int BASE_PACKET_LENGTH = 14;
short port;
String IP;
int numFiles;
int sizeOfFiles;
public Ping(short port, String IP, int numFiles, int sizeOfFiles) {
this.port = port;
this.IP = IP;
this.numFiles = numFiles;
this.sizeOfFiles = sizeOfFiles;
}
public Ping(byte[] bytes) throws UnknownHostException {
ByteBuffer buffer = ByteBuffer.wrap(bytes);
this.port = buffer.getShort();
byte[] ip = new byte[4];
buffer.get(ip);
this.IP = InetAddress.getByAddress(ip).getHostAddress();
this.numFiles = buffer.getInt();
this.sizeOfFiles = buffer.getInt();
}
public byte[] toBytes() throws UnknownHostException {
byte[] bytes = new byte[BASE_PACKET_LENGTH];
ByteBuffer portBuf = ByteBuffer.allocate(2);
portBuf.putShort(this.port);
System.arraycopy(portBuf.array(), 0, bytes, 0, portBuf.capacity());
byte[] ipBuf = InetAddress.getByName(this.IP).getAddress();
System.arraycopy(ipBuf, 0, bytes, 2, ipBuf.length);
ByteBuffer numBuf = ByteBuffer.allocate(8);
numBuf.putInt(this.numFiles);
numBuf.putInt(this.sizeOfFiles);
System.arraycopy(numBuf.array(), 0, bytes, portBuf.capacity() + ipBuf.length, numBuf.capacity());
return bytes;
}
public boolean equals(Object obj) {
if (obj == null)
return false;
if (obj.getClass() != this.getClass())
return false;
Ping p = (Ping) obj;
return p.IP.equals(this.IP) && p.port == this.port;
}
// for debugging
public String toString() {
return "Port: " + this.port + " IP: " + this.IP + " numFiles: " + this.numFiles + " sizeOfFiles: "
+ this.sizeOfFiles;
}
}