MCPcopy Create free account
hub / github.com/0linlin0/CyberBox / NetcatUDPServer

Class NetcatUDPServer

Skay_Exp/src/tools/nc/NetcatUDPServer.java:14–87  ·  view source on GitHub ↗

Establishes a connection to the server on the given host name (or IP address) and port number and operates in one of two modes: download and upload. @author tlmader.dev@gmail.com @since 2017-02-27

Source from the content-addressed store, hash-verified

12 * @since 2017-02-27
13 */
14@SuppressWarnings("JavaDoc")
15public class NetcatUDPServer {
16
17 private static DatagramSocket serverSocket;
18 private static DatagramPacket pingPacket;
19 private static boolean downloadMode;
20 private static boolean pinged;
21
22 /**
23 * Creates welcome socket and starts update loop to handle arbitrary sequence of clients making requests.
24 *
25 * @param port a port number
26 * @throws Exception
27 */
28 @SuppressWarnings("InfiniteLoopStatement")
29 private static void start(int port) throws Exception {
30 serverSocket = new DatagramSocket(port);
31 if (System.in.available() > 0) {
32 downloadMode = true;
33 }
34 while (true) {
35 if (downloadMode) {
36 download();
37 } else {
38 upload();
39 }
40 }
41 }
42
43 /**
44 * In download mode, server reads data from the socket and writes it to standard output.
45 *
46 * @throws Exception
47 */
48 private static void download() throws Exception {
49 if (!pinged) {
50 byte[] receiveData = new byte[1024];
51 pingPacket = new DatagramPacket(receiveData, receiveData.length);
52 serverSocket.receive(pingPacket);
53 pinged = true;
54 }
55 Scanner input = new Scanner(System.in);
56 while (input.hasNextLine()) {
57 byte[] sendData = input.nextLine().getBytes();
58 serverSocket.send(new DatagramPacket(sendData, sendData.length, pingPacket.getAddress(), pingPacket.getPort()));
59 }
60 }
61
62 /**
63 * In upload mode, server reads data from its standard input device and writes it to the socket.
64 *
65 * @throws Exception
66 */
67 private static void upload() throws Exception {
68 byte[] receiveData = new byte[4096];
69 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
70 serverSocket.receive(receivePacket);
71 System.out.println(new String(receivePacket.getData()).trim());

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected