I'm working o a project that monitors the IP and HWID on a specific port by TCPListen sent from a client that kills a specific process.
Monitor works perfect, I receive ip and hwid and manage to save to .txt files but what I want to do is to implement a method in server how to block the ip by reading the hwid from a text file.
If some one can help me please I will appreciate it really.
Here is a part from code of client(send) , server (receive):
Server:
textFromClient = ("From: " + tcpClient.Client.RemoteEndPoint + " HWID:" + encoder.GetString(message, 0, bytesRead));
Client:
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(getUniqueID("C"));
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
I think I understand but maybe that I didn't explain right. Well, my server listen on any ip on port 8000 . Clients connects automaticly to server ip and port: exemple : 127.0.0.1:8000. Well clients works like this: When client is connected to server it runs a application".exe". Client is made to kill the process of some application by name. I made a timer for kill the process all the time client is running. When a process is killed client sends to server the IP from pc where process was killed and HWID code: byte[] outStream = System.Text.Encoding.ASCII.GetBytes(getUniqueID("C"));
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush(); and server recive on a listbox the ip and hwid. Well i'm thinking to do so . Example: On this recive message code where i get the HWID from client encoder.GetString(message, 0, bytesRead) to do something like:
if (encoder.GetString(message, 0, bytesRead) = LoadBlockHWID(new FileInfo(#"c:\testfileHWID.txt")));
{
//Code to block connection from specified IP on hwid.
}
I whant that server should not let the client connect to server by HWID. I think I must edit server to see ip and hwid connected and client to send hwid when connected.
Load your HWID into a List/Dictionary by reading your file before you start accepting connections.
in your code where you get tcpClient.Client.RemoteEndPoint, extract just the IPAddress out of that.
Then compare the IPAddress to the block list and if it matches, then see if the HWID matches if that matches then don't perform the task otherwise just do it.
mBlockCheck = new SO15147104();
Here is an example for you. Just instantiate the class and in your line where you Might want to block a request, just
if (!mBlockCheck.BlockRequest(ip, hwid))
{
//Do the operation
}
This is the class code you should be able to figure out from this.
using System.Collections.Generic;
using System.IO;
using System.Net;
public class SO15147104
{
private List<string> HWIDLookup;
private List<IPAddress> IPAddressLookup;
public SO15147104()
{
HWIDLookup = LoadBlockHWID(new FileInfo(#"c:\testfileHWID.txt"));
IPAddressLookup = LoadBlockIPAddresses(new FileInfo(
#"c:\testfileIPAddresses.txt"));
}
public bool BlockRequest(IPAddress ip, string HWIDtoCheck)
{
if (IPAddressLookup.Contains(ip) &&
HWIDLookup.Contains(HWIDtoCheck.ToUpperInvariant().Trim()))
{
return true;
}
return false;
}
private List<IPAddress> LoadBlockIPAddresses(FileInfo fi)
{
List<IPAddress> result = new List<IPAddress>();
using (StreamReader sr = fi.OpenText())
{
while (!sr.EndOfStream)
{
IPAddress theIP = IPAddress.Any;
string thisLine = sr.ReadLine().Trim();
//This should allow IPv6 and IPv4 to be listed 1IP per Line
if (IPAddress.TryParse(thisLine, out theIP))
{
result.Add(theIP);
}
}
}
return result;
}
private List<string> LoadBlockHWID(FileInfo fi)
{
List<string> result = new List<string>();
using (StreamReader sr = fi.OpenText())
{
while (!sr.EndOfStream)
{
result.Add(sr.ReadLine().Trim().ToUpperInvariant());
}
}
return result;
}
Related
So I have two Ruby programs, they are a client and server sockets programs and they work together exchanging messages. But a C# client does not work. I give MCVE, first the ruby client.
#socketClient.rb
#With thanks to https://code.likeagirl.io/socket-programming-in-ruby-f714131336fd
require "socket"
while sum = $stdin.gets.chomp # Read lines from the socket
socket = TCPSocket.open("localhost", 3000)
#puts "Starting the Client..................."
socket.puts sum
while message = socket.gets # Read lines from the socket
puts message.chomp
end
socket.close # Close the socket
end
#puts "Closing the Client..................."
and the server
#simplestSocketServer.rb
#With thanks to https://code.likeagirl.io/socket-programming-in-ruby-f714131336fd
require "socket"
port = 3000
ipAddress = "127.0.0.1"
server = TCPServer.open(ipAddress, port) # Server would listen on port 3000
loop { # Servers run forever
puts "Starting the Server, accepting connections on port " + port.to_s + "..................."
client_connection = server.accept # Establish client connect connection
begin
clientText = client_connection.gets.chomp
puts clientText
resp = "Acknowledged"
client_connection.puts("#{clientText}" + "#{resp}") # Send the answer to the client
client_connection.puts("Closing the connection with #{client_connection}")
rescue Exception => getException
puts "#{getException}"
end
client_connection.close # Disconnect from the client
}
and the C# console program
using System;
using System.Net.Sockets;
using System.Text;
namespace SimplestCSharpRubySocketsClient
{
class Program
{
static void Main(string[] args)
{
try
{
string ipAddress = "127.0.0.1";
Int16 portNumber = 3000;
TcpClient _client; _client = new TcpClient();
_client.Connect(ipAddress, portNumber);
System.Console.WriteLine("we have connected, seemingly ...");
NetworkStream stream;
stream = _client.GetStream();
Byte[] sendBytes = Encoding.UTF8.GetBytes("some text");
System.Console.WriteLine("writing and flushing some bytes ...");
stream.Write(sendBytes, 0, sendBytes.Length);
stream.Flush();
Byte[] recvBytes = new byte[_client.ReceiveBufferSize];
System.Console.WriteLine("_client.ReceiveBufferSize = " + _client.ReceiveBufferSize); // <--- this prints 65536
System.Console.WriteLine("waiting to read bytes ...");
stream.Read(recvBytes, 0, recvBytes.Length); //<--- hangs here
System.Console.WriteLine("comething came back ...");
string result = Encoding.UTF8.GetString(recvBytes);
string result2 = result.Substring(0, result.LastIndexOf("\r\n"));
_client.Close();
_client.Dispose();
_client = null;
}
catch (Exception ex)
{
//TODO figure out a better error handler
throw ex;
}
}
}
}
The C# program connects and writes bytes but when looking to read bytes it just hangs.
And be aware I am running the C# console program in Visual Studio with admin rights. The two ruby programs run in their own separate Windows console windows.
Folding in some feedback, I added another line in the ruby server to output the clientText. And it prints nothing, suggesting the server is not fully receiving the bytes. Is there a termination signal that C# is required to send?
Thanks in advance.
The problem here is that the C# client does not send a newline at the end of the string, like the Ruby version does (socket.puts sends a string with a newline at the end).
If you change your sendBytes array to include a \n in the payload like this:
Byte[] sendBytes = Encoding.UTF8.GetBytes("some text\n");
you will see that it prints comething came back ... on the console.
The newline is required because of the following gets in the Ruby server:
clientText = client_connection.gets.chomp
I'm still learning C#, so don't yell at me for not doing anything right. Also, i know I should probably be using WPF, but in my current condition I need to use winForms.
Client:
public void sendData(String dataIn)
{
String IP = textBox1.Text;
String Port = textBox2.Text;
net.Send(dataIn, IP, Port);
}
Server:
public string listenForData()
{
String dataOut = net.Listen();
return dataOut;
}
How do I create a method that takes a string and sends it to a server application. I know it has something to do with TCP sockets. I've looked but I don't understand any tutorials or videos i've found.
Thanks in advance, Noah.
You could try looking into the TCP Client Class.
https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient(v=vs.110).aspx
You can get the stream from tcp client and use that to write your string to, by converting the string to a byte[] first.
// Setup TCP Client with valid values first. Make Client and stream private or public variables/properties.
TCPClient client = new TCPClient(IP, (int)Port); // Following validation on Port & IP
NetworkStream stream = client.GetStream();
private void SendDataToServer(String dataIn) {
Byte[] StringToSend = Encoding.UTF8.GetBytes(dataIn);
stream.Write(StringToSend, 0, StringToSend.Length);
}
We have web application , it works as Socket Listner. I wanted to check before the AcceptSocket , whether there is any Client Socket available to connect to this listner. I want to display a message if there is no Client Socket to connect and cancel send/receive of data.
I am using TCPListner using ASP.net C# for the web application. The Client socket is windows VB6 application using Winsock control.
Socketing programme, ASP.Net C#, VS2008
Thanks you for the reply ,
see below my sample code for communicate with server
clsCommunication.cs, this class file imports into .aspx page. I tried using Console.WriteLine(), but cann't shown this message.
I wanted to display alert box , so that user understands there is no connection OR display on status bar or highlight a frame/box etc.
public void Communicationcation()
{
byte[] bytes = new byte[1024];
string strSiteID = "SiteID";
socket.Start();
if (!socket.Pending())
{
Console.WriteLine("Sorry, no connection requests have arrived");
}
else
{
client = socket.AcceptSocket();
if (client.Connected == true)
{
decimal dSiteID = decimal.Parse(GetSiteSetting(ref strSiteID).ToString());
IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
WriteLog(string.Format("Connected with {0} at port {1}", clientep.Address, clientep.Port));
string strWelcome = STARTMESSAGE + "WHOAMI" + " " + dSiteID + " " + dSiteID + FINISHMESSAGE;
byte[] data = new byte[1024];
data = Encoding.ASCII.GetBytes(strWelcome);
int i = client.Send(data, data.Length, SocketFlags.None);
WriteLog(String.Format("Message sent {0} bytes!", i));
//Get reply from the Connected cleint.
i = client.Receive(bytes, bytes.Length, SocketFlags.None);
if (i != -1)
{
WriteLog(string.Format(System.Text.Encoding.UTF8.GetString(bytes)));
}
}
}
}
You can use TcpListener's Pending method, see http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.pending.aspx
I want to send a file from a C# server to a AS3 Flash Client. My C# server code for sending the file is something like this:
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 5656);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(ipEnd);
sock.Listen(100);
//clientSock is the socket object of client, so we can use it now to transfer data to client
Socket clientSock = sock.Accept();
// This part gets the file and send the data in bytearray
byte[] fileData = File.ReadAllBytes("send/mypicture.jpg");
clientSock.Send(fileData);
Now I need a as3 client. I found this: http://flasharp.blogspot.pt/2010/03/socket-serverclient-chat.html and I constructed something like this:
public function Main():void {
...
socket.addEventListener(ProgressEvent.SOCKET_DATA, onResponse);
...
}
function onResponse(e:ProgressEvent):void {
var file:File;
var fs:FileStream;
var fileData:ByteArray = new ByteArray();
// Check if socket has data
if(socket.bytesAvailable > 0) {
while(socket.bytesAvailable) {
// read the socket data into the fileData
socket.readBytes(fileData,0,0);
}
}
file = File.documentsDirectory.resolvePath("teste.jpg");
fs = new FileStream();
fs.open(file, FileMode.WRITE);
// Writing the file
fs.writeBytes(fileData);
fs.close();
}
I've managed to send and receive a file, but it only saves up to 50kbs, anything bigger and you just gest a file with that size.
Any thoughts on how to transfer a file with any size?
I managed to solve this and updated this post with a sample.
UPDATED & SOLVED:
I wanted to send files from a C# server to AS3 Clients using sockets in a Local Network. I had some trouble finding out how to do it, but I managed to do so.
Server (C#):
1 - I create a TcpListener that listens for new clients with any IP in that network to the specified port number;
2 - When a new client connects I create a Thread to handle it;
3 - In that Thread I send the data I want to. In this case that data is divided in two parts, the first is a 4 bytearray that contains the size of the file I want to send, and the second is a bytearray of the file itself;
4 - After the data is sent I close that client connection;
Client (AS3):
1 - First of all I convert my bytearrays to LITTLE_ENDIAN, since AIR is by default BIG_ENDIAN and the data I get from the server is LITTLE_ENDIAN;
2 - Add the events to the socket connection and conect to the server;
3 - On the onResponse function I receive the socket packages to a bytearray;
4 - Save that bytearray into a file;
The last part on the client was the trickiest one, because it took me some time to figure out that AIR is BIG_ENDIAN by default, and how to read the packages.
So basically, what I do is, on the first package that comes in I read the first 4 bytes to a bytearray and then convert that to an int, which gives me my total file size. I use this to know when there are no more packages to receive and therefore finish the connection and save the file. The rest of the first package and subsequent packages are added to a bytearray that will store that file data itself. The workaround here is to start writing on the beggining the first time a package is received and then add the subsequent packages where the last one left off, i.e., first time I write from the 0 to 65321, second one I'll have to write from the 65321 to XXXX, and so on.
The file is being saved to the MyDocuments folder.
I'm unsure if this is the best method to do this, since I'm rather new to socket connection, however this works for me and I tested with files up to 165MB and it works. It supports multiple client connections and is pretty basic, but this is a starting point, not a finish line.
I hope this can help others as it helped me, since I did not find anything like it on the web (regarding file transfer not C# -> AS3 connection).
If someone wants to input some info or needs clarification on something, please feel free to ask.
Last but no least, sample can be downloaded here: http://sdrv.ms/W5mSs9 (Server in C# Express 2010 and Client in Flash Builder 4.6 with Flex SDK 4.6.0)
In case the sample in the link above ever dies out here is the
ActionScript 3 Source Code:
package
{
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.net.Socket;
import flash.system.Security;
import flash.utils.ByteArray;
import flash.utils.Endian;
import flash.text.TextField;
public class FileTransferLocal extends Sprite
{
private var socket:Socket = new Socket();
private var file:File;
private var fs:FileStream = new FileStream();
private var fileData:ByteArray = new ByteArray();
private var fileSize:ByteArray = new ByteArray();
private var fileDataPosition:int = new int();
private var fileDataFlag:int = new int();
private var fileSizeFlag:int = new int();
private var fileSizeCounter:int = new int();
private var fileDataPreviousPosition:int = new int();
private var myText:TextField = new TextField();
public function FileTransferLocal()
{
try {Security.allowDomain("*");}catch (e) { };
// Convert bytearray to Little Endian
fileSize.endian = Endian.LITTLE_ENDIAN;
fileData.endian = Endian.LITTLE_ENDIAN;
socket.endian = Endian.LITTLE_ENDIAN;
fileSizeFlag = 0;
fileDataFlag = 0;
myText.width = 150;
myText.height = 150;
myText.x = 200;
myText.y = 200;
socket.addEventListener(Event.CONNECT, onConnect);
socket.addEventListener(Event.CLOSE, onClose);
socket.addEventListener(IOErrorEvent.IO_ERROR, onError);
socket.addEventListener(ProgressEvent.SOCKET_DATA, onResponse);
socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecError);
// Put the IP and port of the server
socket.connect("10.1.1.211", 5656);
}
private function onConnect(e:Event):void {
trace("onConnect\n");
}
private function onClose(e:Event):void {
trace("onClose");
socket.close();
}
private function onError(e:IOErrorEvent):void {
trace("IO Error: "+e);
}
private function onSecError(e:SecurityErrorEvent):void {
trace("Security Error: "+e);
}
private function onResponse(e:ProgressEvent):void {
if(!fileSizeFlag) {
socket.readBytes(fileSize, 0, 4);
fileSize.position = 0;
fileSizeFlag = 1;
fileSizeCounter = fileSize.readInt();
trace("fileSizeCounter -> " + fileSizeCounter);
}
trace("---- New package ----> " + socket.bytesAvailable);
if(fileSizeCounter > 0) {
fileSizeCounter -= socket.bytesAvailable;
if(fileDataPosition != 0) {
fileDataPreviousPosition += fileDataPosition;
}
if(fileData.length == 0) {
fileDataPreviousPosition = socket.bytesAvailable;
socket.readBytes(fileData, 0, socket.bytesAvailable);
} else {
fileDataPosition = socket.bytesAvailable;
socket.readBytes(fileData, fileDataPreviousPosition, socket.bytesAvailable);
}
}
// Saves the file
if(fileSizeCounter == 0) {
trace("File total size" + fileData.length);
file = File.documentsDirectory.resolvePath("test.mp3");
fs.open(file, FileMode.WRITE);
fs.writeBytes(fileData);
fs.close();
myText.text = "File successefully\nreceived!";
addChild(myText);
}
// Is still receiving packages
else {
myText.text = "Receiving file...";
addChild(myText);
}
}
}
}
In C# create a new Windows Application
add a
ListBox call it statusList
Label call it port
Label call it status
C# Source code in Sample Above:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System.IO;
using System.Reflection;
namespace ServerThread
{
public partial class ServerThread : Form
{
private TcpListener tcpListener;
private Thread listenThread;
public ServerThread()
{
InitializeComponent();
// Port number
int portNumber = 5656;
port.Text = portNumber.ToString();
// Create a TcpListener to cover all existent IP addresses with that port
this.tcpListener = new TcpListener(IPAddress.Any, portNumber);
// Create a Thread to listen to clients
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
// Blocks until a client has conected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
// Create a Thread to handle the conected client communication
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
// Receive data
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
while (true)
{
try
{
// Sending data
string filePath = "send/mysong.mp3"; // Your File Path;
byte[] fileData = File.ReadAllBytes(filePath); // The size of your file
byte[] fileSize = BitConverter.GetBytes(fileData.Length); // The size of yout file converted to a 4 byte array
byte[] clientData = new byte[fileSize.Length + fileData.Length]; // The total byte size of the data to be sent
fileSize.CopyTo(clientData, 0); // Copy to the file size byte array to the sending array (clientData) beginning the in the 0 index
fileData.CopyTo(clientData, 4); // Copy to the file data byte array to the sending array (clientData) beginning the in the 4 index
// Send the data to the client
clientStream.Write(clientData, 0, clientData.Length);
clientStream.Flush();
// Debug for the ListBox
if (statusList.InvokeRequired)
{
statusList.Invoke(new MethodInvoker(delegate {
statusList.Items.Add("Client IP: " + tcpClient.Client.RemoteEndPoint.ToString());
statusList.Items.Add("Client Data size: " + clientData.Length);
}));
}
}
catch
{
//
break;
}
if (statusList.InvokeRequired)
{
statusList.Invoke(new MethodInvoker(delegate
{
statusList.Items.Add("File successefully sent!");
}));
}
// Close the client
tcpClient.Close();
}
}
}
}
I am trying to make a Minecraft fake client a.k.a Minecraft chatbot in c# using packets.
I already tried lots of different ways to acomplish this but no luck.
Everytime I send a packet it sends no data (Using a packetsniffer).
Although the packetsniffers says that the total size of the packet is: 190 bytes.
and the size is: 17 bytes.
Here is my code:
static TcpClient client = new TcpClient();
static void Main(string[] args)
{
Console.WriteLine("Start GATHERING INFO.....");
Console.Write("Write a ip: ");
IPAddress ip = IPAddress.Parse("192.168.178.11");
try
{
ip = IPAddress.Parse(Console.ReadLine());
}
catch
{
Console.Write("\nUnknown/Wrong ip entered redirecting to : 127.0.0.1 (AKA Localhost)");
ip = IPAddress.Parse("192.168.178.11");
}
Console.Write("\nWrite a port: ");
int port = int.Parse(Console.ReadLine());
Console.WriteLine("Connecting.....");
try
{
client.Connect(ip, port);
client.NoDelay = false;
Console.WriteLine("Connection succesfull!");
}catch
{
Console.WriteLine("--== ERROR WHILE TRYING TO CONNECT PLEASE RESTART PROGRAM ==--");
Console.ReadKey();
client.Close();
Main(args);
}
Stream stream = client.GetStream();
Console.Write("Please enter a username: ");
string usrn = Console.ReadLine();
Console.Write("\n");
byte[] data = new byte[3 + usrn.Length*2];
data[0] = (byte)2;
data[1] = (byte)29;
gb(usrn).CopyTo(data, 2);
stream.Write(data, 0, data.Length);
Console.ReadKey();
}
public static byte[] gb(String str)
{
return System.Text.ASCIIEncoding.ASCII.GetBytes(str);
}
Here is how the packet should look like:
http://www.wiki.vg/Protocol#Handshake_.280x02.29
I'm ignoring server host and server port since the other bots didnt use it. (although they didnt work to :/
Here's what the original client packet holds:
'shows weird goto: https://dl.dropbox.com/u/32828727/packetsocketsminecraft.txt '
timboiscool9 (my username)
192.168.178.1 (server ip)
There's more after that but this is what i need.
I am fairly new to sockets and tcpclients
I cleaned up your code a bit:
static void Main(string[] args)
{
bool keepTrying = true;
while (keepTrying)
{
Console.Write("Enter server IP Address: ");
IPAddress ip;
if(!IPAddress.TryParse(Console.ReadLine(), out ip))
{
Console.WriteLine("Invalid ip entered, defaulting to 192.168.178.11");
ip = IPAddress.Parse("192.168.178.11");
}
Console.Write("Enter server port: ");
Int16 port;
if(!Int16.TryParse(Console.ReadLine(), out port))
{
Console.WriteLine("Invalid port entered, defaulting to 1234");
port = 1234;
}
Console.WriteLine("Connecting.....");
try
{
TcpClient client = new TcpClient();
client.Connect(new IPEndPoint(ip, port));
client.NoDelay = false;
Console.WriteLine("Connection succesfull!");
List<byte> data = new List<byte>() { 2, 29 };
Console.Write("Please enter a username: ");
byte[] userName = ASCIIEncoding.ASCII.GetBytes(Console.ReadLine());
data.AddRange(userName);
using (var stream = client.GetStream())
{
stream.Write(data.ToArray(), 0, data.Count);
Console.Write("Data sent!");
}
keepTrying = false;
}
catch
{
Console.WriteLine("--== ERROR CONNECTING ==--");
Console.WriteLine();
}
}
}
As for your original question, we need more information. You say that the packet sniffer shows no data but then you say the data has a size. So are you seeing data or not? Are you sure the server is up? The code I posted works for me, meaning it connects to a server on my local system and sends the bytes.
This is a bit old, but I'll still see if I can help you out.
The Minecraft protocol is quite complicated, and you will not be able to connect to Minecraft servers without implementing the vast majority of it. The protocol details can be found here.
I suggest you consider going a different route. Because of how complex Minecraft is, I'd avoid implementing it yourself. Luckily, I'm a Minecraft enthusiast, and I've done most of the work for you. I suggest you take a look at the Craft.Net library. It contains a full protocol implementation and making a chat bot from it would be trivial. In fact, here's an example chat program using Craft.Net for you to peruse.