Crear una comunicación entre un cliente en PowerShell de Windows y un servidor en Node.js utilizando TCP/IP
Servidor en Node.js
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 | var net = require('net'); var HOST = '127.0.0.1'; var PORT = 6969; // Create a server instance, and chain the listen function to it // The function passed to net.createServer() becomes the event handler for the 'connection' event // The sock object the callback function receives UNIQUE for each connection net.createServer(function(sock) { // We have a connection - a socket object is assigned to the connection automatically console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort); // Add a 'data' event handler to this instance of socket sock.on('data', function(data) { console.log('DATA ' + sock.remoteAddress + ': ' + data); // Write the data back to the socket, the client will receive it as data from the server sock.write('You said "' + data + '"'); }); // Add a 'close' event handler to this instance of socket sock.on('close', function(data) { console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort); }); }).listen(PORT, HOST); console.log('Server listening on ' + HOST +':'+ PORT); |
Cliente en PowerShell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | ##Client $port=6969 $TcpClient=New-Object System.Net.Sockets.TcpClient([IPAddress]::Loopback, $port) $GetStream = $TcpClient.GetStream() $StreamWriter = New-Object System.IO.StreamWriter $GetStream $positions='Hi' $StreamWriter.Write($positions) $StreamWriter.Dispose() $GetStream.Dispose() $TcpClient.Dispose() |
Enviar mensajes constantemente entre cliente y servidor con Java
Servidor
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 | import java.io.*; import java.net.*; public class Server { public static void main(String[] args) { int port=2050; while(true) { try { ServerSocket serverSocket = new ServerSocket(port); Socket clientSocket = serverSocket.accept(); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine = in.readLine(); System.out.println("Receive: " + inputLine); String outputLine = inputLine.toUpperCase(); System.out.println("Send: " + outputLine); out.println(outputLine); out.close(); in.close(); clientSocket.close(); serverSocket.close(); } catch (UnknownHostException e) { System.out.println(e); } catch (IOException e) { System.out.println(e); } } } } |
Cliente
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 | import java.io.*; import java.net.*; public class Client { public static void main(String[] args) { int port=2050; while(true) { try { Socket clientSocket = new Socket("localhost", port); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); System.out.println("Send: Hi"); out.println("Hi"); System.out.println("Receive: " + in.readLine()); out.close(); in.close(); clientSocket.close(); } catch (UnknownHostException e) { System.out.println(e); } catch (IOException e) { System.out.println(e); } } } } |
Enviar una imagen entre un cliente y un servidor con Java (Sockets TCP)
Servidor
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 | import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.*; import java.net.*; import java.nio.ByteBuffer; public class Server { public static void main(String[] args) { int port=2050; try { ServerSocket serverSocket = new ServerSocket(port); Socket clientSocket = serverSocket.accept(); InputStream inputStream = clientSocket.getInputStream(); System.out.println(inputStream); byte[] imageAr = new byte[62100]; inputStream.read(imageAr); BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageAr)); System.out.println("Received " + image.getHeight() + "x" + image.getWidth() + ": " + System.currentTimeMillis()); ImageIO.write(image, "jpg", new File("C:\\Users\\juan\\Desktop\\recono\\coche2.png")); inputStream.close(); clientSocket.close(); serverSocket.close(); } catch (UnknownHostException e){ System.out.println(e); } catch (IOException e) { System.out.println(e); } } } |
Cliente
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 | import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.*; import java.net.*; import java.nio.ByteBuffer; public class Client { public static void main(String[] args) { int port=2050; try { Socket clientSocket = new Socket("localhost",port); OutputStream outputStream = clientSocket.getOutputStream(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); BufferedImage image = ImageIO.read(new File("C:\\Users\\juan\\Desktop\\recono\\coche.png")); ImageIO.write(image, "jpg", byteArrayOutputStream); byte[] size = ByteBuffer.allocate(4).putInt(byteArrayOutputStream.size()).array(); System.out.println(byteArrayOutputStream.size()); outputStream.write(byteArrayOutputStream.toByteArray()); Thread.sleep(2000); outputStream.close(); clientSocket.close(); } catch (UnknownHostException e){ System.out.println(e); } catch (IOException e) { System.out.println(e); } catch (InterruptedException e) { e.printStackTrace(); } } } |
Realizar conexiones con Java
Red Analizar direcciones IP para detectar puertos abiertos (versión 1) Analizar direcciones IP para detectar puertos abiertos (versión 2) TCP Comprobar si un puerto TCP está abierto Server and client (Sockets TCP) Multiserver and clients (Sockets TCP and threads) Enviar una imagen entre un cliente y un servidor con Java (Sockets TCP) Enviar mensajes constantemente entre cliente y servidor con Java UDP Server and client (Datagram Socket UDP) MulticastSocket (Datagram Socket UDP) URL Conectar con una URL en Java Conectar con una URL en Java cambiando el User-Agent Realizar petición HTTP mediante el método POST utilizando librerías de Apache
Escanear un puerto con Python
1 2 3 4 5 6 7 8 | import socket s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) result=s.connect_ex(("www.jesusninoc.com",22)) if result == 0: print("Puerto abierto") else: print("Puerto no abierto") s.close() |
Curso de Java con ejemplos
Procesos Create operating system processes Create and destroy operating system processes Crear un proceso utilizando Runtime Crear un proceso utilizando ProcessBuilder Lanzar un programa del sistema operativo como argumento desde la línea de comandos Ejecutar y guardar el comando ‘arp’ utilizando ProcessBuilder Hilos Crear un hilo implementando el interfaz Runnable Crear un hilo heredando de la clase Thread Automatizar Obtener la posición del ratón en la pantalla con Java Ver la resolución de pantalla con Java Mover el ratón a una posición con Java Mover el ratón con duración a varias posiciones de la pantalla con Java Hacer clic en […]
Escanear puertos con Python
1 2 3 4 5 6 7 8 9 | import socket for port in range(80,90): s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) result=s.connect_ex(("www.jesusninoc.com",port)) if result == 0: print("Puerto abierto") else: print("Puerto no abierto") s.close() |
Server and client (Sockets TCP and IPv6)
Server
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | ##Server $port=2050 $IPEndPoint=New-Object System.Net.IPEndPoint([IPAddress]::IPv6Any,$port) #The TcpListener class provides simple methods that listen for and accept incoming connection requests in blocking synchronous mode. You can use either a TcpClient or a Socket to connect with a TcpListener. Create a TcpListener using an IPEndPoint, a Local IP address and port number, or just a port number. Specify Any for the local IP address and 0 for the local port number if you want the underlying service provider to assign those values for you. If you choose to do this, you can use the LocalEndpoint property to identify the assigned information, after the socket has connected. $TcpListener=New-Object System.Net.Sockets.TcpListener $IPEndPoint #Use the Start method to begin listening for incoming connection requests. Start will queue incoming connections until you either call the Stop method or it has queued MaxConnections. Use either AcceptSocket or AcceptTcpClient to pull a connection from the incoming connection request queue. These two methods will block. If you want to avoid blocking, you can use the Pending method first to determine if connection requests are available in the queue. $TcpListener.Start() $AcceptTcpClient=$TcpListener.AcceptTcpClient() $GetStream=$AcceptTcpClient.GetStream() $StreamReader=New-Object System.IO.StreamReader $GetStream $StreamReader.ReadLine() $StreamReader.Dispose() $GetStream.Dispose() $AcceptTcpClient.Dispose() #Call the Stop method to close the TcpListener. $TcpListener.Stop() |
Client
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | ##Client $port=2050 $TcpClient=New-Object System.Net.Sockets.TcpClient([IPAddress]::"fe80::40dd:9d4:3238:472%4", $port) $GetStream = $TcpClient.GetStream() $StreamWriter = New-Object System.IO.StreamWriter $GetStream $positions='Hi' $StreamWriter.Write($positions) $StreamWriter.Dispose() $GetStream.Dispose() $TcpClient.Dispose() |
Análisis de conexiones TCP con Wireshark (número de secuencia)
Pasos necesarios para analizar las conexiones TCP con Wireshark: Enviar un mensaje entre un cliente y un servidor Capturar, analizar y filtrar el tráfico capturado detectando los números de secuencia Enviar un mensaje entre un cliente y un servidor Cliente envía un mensaje al servidor: Enviar un mensaje mediante PowerShell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | ##Client $port=5556 $TcpClient=New-Object System.Net.Sockets.TcpClient "192.168.1.56", $port $GetStream = $TcpClient.GetStream() $StreamWriter = New-Object System.IO.StreamWriter $GetStream $positions='Hi you' $StreamWriter.Write($positions) $StreamWriter.Dispose() $GetStream.Dispose() $TcpClient.Dispose() |
Servidor que recibe el mensaje que envía el cliente: Recibir el mensaje mediante PowerShell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | ##Server $port=5556 $IPEndPoint=New-Object System.Net.IPEndPoint([System.Net.IPAddress]::any,$port) #The TcpListener class provides simple methods that listen for and accept incoming connection requests in blocking synchronous mode. You can use either a TcpClient or a Socket to connect with a TcpListener. Create a TcpListener using an IPEndPoint, a Local IP address and port number, or just a port number. Specify Any for the local IP address and 0 for the local port number if you want the underlying service provider to assign those values for you. If you choose to do this, you can use the LocalEndpoint property to identify the assigned information, after the socket has connected. $TcpListener=New-Object System.Net.Sockets.TcpListener $IPEndPoint #Use the Start method to begin listening for incoming connection requests. Start will queue incoming connections until you either call the Stop method or it has queued MaxConnections. Use either AcceptSocket or AcceptTcpClient to pull a connection from the incoming connection request queue. These two methods will block. If you want to avoid blocking, you can use the Pending method first to determine if connection requests are available in the queue. $TcpListener.Start() $AcceptTcpClient=$TcpListener.AcceptTcpClient() $GetStream=$AcceptTcpClient.GetStream() $StreamReader=New-Object System.IO.StreamReader $GetStream $StreamReader.ReadLine() $StreamReader.Dispose() $GetStream.Dispose() $AcceptTcpClient.Dispose() #Call the Stop method to close the TcpListener. $TcpListener.Stop() |
Capturar, analizar y filtrar el tráfico capturado detectando los números de secuencia