Advertisement
Guest User

Ping.class

a guest
Jun 2nd, 2015
271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.77 KB | None | 0 0
  1. package me.mrpyro13.gamebridges.utils;
  2.  
  3. import java.io.DataOutputStream;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.io.OutputStream;
  7. import java.net.InetSocketAddress;
  8. import java.net.Socket;
  9. import java.nio.charset.Charset;
  10.  
  11. public class Pinging {
  12.  
  13. private String host;
  14. private int port;
  15.  
  16. public Pinging(String host, int port) {
  17. this.host = host;
  18. this.port = port;
  19. }
  20.  
  21. public Pinging(String host) {
  22. this.host = host;
  23. this.port = 25565;
  24. }
  25.  
  26. public Pinging() {
  27. this.host = "127.0.0.1";
  28. this.port = 25565;
  29. }
  30.  
  31. @SuppressWarnings("resource")
  32. public String parseData(Connection connection) {
  33. try {
  34. Socket socket = new Socket();
  35. OutputStream os;
  36. DataOutputStream dos;
  37. InputStream is;
  38. InputStreamReader isr;
  39.  
  40. socket.setSoTimeout(250);
  41. socket.connect(new InetSocketAddress(host, port));
  42.  
  43. os = socket.getOutputStream();
  44. dos = new DataOutputStream(os);
  45.  
  46. is = socket.getInputStream();
  47. isr = new InputStreamReader(is, Charset.forName("UTF-16BE"));
  48.  
  49. dos.write(new byte[] { (byte) 0xFE, (byte) 0x01 });
  50.  
  51. int packetID = is.read();
  52.  
  53. if(packetID == -1) {
  54. System.out.println("Invalid Packet ID! (End Of Stream)");
  55. }
  56. if(packetID != 0xFF) {
  57. System.out.println("Invalid Packet Id! " + packetID);
  58. }
  59.  
  60. int length = isr.read();
  61.  
  62. if(length == -1) {
  63. System.out.println("End Of Stream");
  64. }
  65.  
  66. if(length == 0) {
  67. System.out.println("Invalid length");
  68. }
  69.  
  70. char[] chars = new char[length];
  71.  
  72. if(isr.read(chars, 0, length) != length) {
  73. System.out.println("End Of Stream");
  74. }
  75.  
  76. String string = new String(chars);
  77. String[] data = string.split("\0");
  78.  
  79. if(connection == Connection.ONLINE_PLAYERS) {
  80. return data[4];
  81. } else if(connection == Connection.MOTD) {
  82. return data[3];
  83. } else if(connection == Connection.MAX_PLAYERS) {
  84. return data[5];
  85. } else {
  86. System.out.println("Connection value not handled!");
  87. }
  88.  
  89. } catch (Exception e) {}
  90. return null;
  91. }
  92.  
  93. public enum Connection {
  94. ONLINE_PLAYERS, MAX_PLAYERS, MOTD
  95. }
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement