Giter Club home page Giter Club logo

corercon's Introduction

CoreRcon

CI Nuget Nuget

CoreRCON is an implementation of the RCON protocol on .NET Core. It currently supports connecting to a server, sending commands and receiving their output, multi-packat responses, and receiving logs from logaddress.

Supports:

Quick Start

Connect to an RCON server and send a command

The IP address supplied here is the server you wish to connect to.

using CoreRCON;
using CoreRCON.Parsers.Standard;
using System.Net;
// ...

// Connect to a server
var rcon = new RCON(IPAddress.Parse("10.0.0.1"), 27015, "secret-password");
await rcon.ConnectAsync();

// Send a simple command and retrive response as string
string response = await rcon.SendCommandAsync("echo hi");

// Send "status" and try to parse the response
Status status = await rcon.SendCommandAsync<Status>("status");

Console.WriteLine($"Connected to: {status.Hostname}");

Listen for chat messages on the server

This assumes you have been added to the server's logaddress list. You do not need to make an rcon connection to receive logs from a server.

The port specified must be open (check your router settings) and unused. Pass a value of 0 to use the first-available port. Access log.ResolvedPort to see which port it chose.

Finally, pass an array (or list of params) of IPEndPoints to express which servers you would like to receive logs from. This is because any server can send your server logs if they know which port you are listening on, as it's just UDP.

using CoreRCON;
using CoreRCON.Parsers.Standard;
// ...

// Listen on port 50000 for log packets coming from 10.0.0.1:27015
var log = new LogReceiver(50000, new IPEndPoint(IPAddress.Parse("10.0.0.1"), 27015));
log.Listen<ChatMessage>(chat =>
{
	Console.WriteLine($"Chat message: {chat.Player.Name} said {chat.Message} on channel {chat.Channel}");
});

Troubleshooting

Can't install via NuGet

"Could not install package 'CoreRCON X.X.X'. You are trying to install this package into a project that targets '.NETFramework,Version=vy.y.y', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author."

If you are seeing an error similar to this, try changing your project's targeted .NET Framework version [#11]. If you are using Visual Studio 2015, the minimum resolvable framework version is 4.7. Visual Studio 2017 has improved support for .NET Core packages, allowing CoreRCON to resolve for versions as low as 4.6.1.

Changelog

See Github Releases

Big thanks to ScottKaye for developing the original version

corercon's People

Contributors

ceifa avatar chte avatar codingcontraption avatar cryptoc1 avatar dependabot[bot] avatar exusaltimus avatar frobinsonj avatar kasperk81 avatar kungraseri avatar pikeman avatar scottkaye avatar xobust avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

corercon's Issues

Parser not works on CS2

Hi, i'm trying to retrieve the chat on a cs2 gameserver. This is my code in VB.NET but does nothing... Can you help me?.

Dim log = New LogReceiver(GAMESERVERPORT, New IPEndPoint(IPAddress.Parse("GAMESERVERIP"), GAMESERVERPORT))

    log.Listen(Of ChatMessage)(Sub(chat)
                                   RichTextBox1.AppendText($"Chat message: {chat.Player.Name} said {chat.Message} on channel {chat.Channel}")
                                   MsgBox($"Chat message: {chat.Player.Name} said {chat.Message} on channel {chat.Channel}")
                               End Sub)

Exception Specified argument was out of the range of valid values

Hi,
i have a quick question. I created a RCON Client but if i add the TCP Timeout parameter and want to connect to a Server, i get this error:

Exception Specified argument was out of the range of valid values.
Parameter name: offset

I used this to create the client:

Private rconclient As New RCON(IPAddress.Parse(_ip), _port, _passwd, tcpTimeout:=10000)

Greetings :)

Provide package to include as third party library

Hello,
since the main library is unmaintained I would like to use this version, which has some great improvements ๐Ÿ˜ƒ

Could this repository provide a package to include this library in other projects. Best solution would be a package on NuGet.

Cheers ๐Ÿ‘‹

Typo in example code

string respnose = await rcon.SendCommandAsync("echo hi");

respnose instead of response

Error reading RCON packet from server: Index was out of range.

When i send command trough RCON to my minecraft server it's successfully executed, but answer from server generate error: "Error reading RCON packet from server: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'startIndex')"

Sent command is an plugin's command. And error generated only with any plugin's commands.
With a command of the kernel of minecraft such an error isn't generated.

I know such program as "mcrcon". In this program all plugin's commands successfully return answer.

Perhaps I doing something wrong. Or CoreRcon can't get answer from such commands.

tcp timeout not working

TCP timeout not working. It takes about 20 seconds until a timeout is triggered.

try
{
var connection = new RCON(serveraddress, Port, serverpass, 1000, false);
await connection.ConnectAsync();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

Better error management

  • Throw an exception if trying to send a message on closed connection
  • Replace aggregate exception with something better

ServerQuery.Info hangs, never completes task

I'm writing a Discord bot to handle Minecraft servers for user communities, and I have a method called "Status" that represents a command to query a Minecraft server. To do this, I pull an object containing the address of the server from a database, get it's hostname through DNS, then sure the ServerQuery.Info() method, but it hangs every time.

Here's the code:

public async Task Status(CommandContext context) {
            MinecraftServer server = DBManager.GetMinecraftServerDocument(context.Guild.Id);

            DiscordEmbedBuilder embedBuilder = new DiscordEmbedBuilder();
            if (server == null) {
                embedBuilder.WithColor(DiscordColor.Red);
                embedBuilder.WithTitle("This Discord server does not have an associated Minecraft server");
                embedBuilder.WithFooter("Use the \"minecraft register <server address>\" command to register one!");
                await context.Channel.SendMessageAsync(embedBuilder.Build());

                return;
            }

            IPAddress serverAddress = Dns.GetHostAddresses(server.Address)[0];

            Console.WriteLine($"Performing server query on {serverAddress}");

            MinecraftQueryInfo status = ServerQuery.Info(serverAddress, 25575,   ServerQuery.ServerType.Minecraft).GetAwaiter().GetResult() as MinecraftQueryInfo;


            if (status.Players == null) {
                await context.Channel.SendMessageAsync("Something went wrong with the status request...");
                return;
            } else Console.WriteLine("Completed query");

            embedBuilder.Color = DiscordColor.Green;
            embedBuilder.Title = $"{status.HostIp} Status";
            // embedBuilder.Description = $"{status.}";
            embedBuilder.AddField("Version:", status.Version);
            embedBuilder.AddField("Game Type:", status.Gametype);
            embedBuilder.AddField("Players Online:", $"{status.NumPlayers} / {status.MaxPlayers}");
            DiscordEmbed embed = embedBuilder.Build();

            await context.Channel.SendMessageAsync(embed);
        }
// I don't think I'm using this incorrectly, but it's possible that I am. It gives the same result even when awaiting the Task the traditional way.  I really appreciate anyone who gives feedback on this, thanks for the help!

Not able to listen for command? Not able to send?

I have attempted to use your library with Project Zomboid and I see that it states that it works (#26); however, I cannot seem to get the listener to speak with my application. I am hosting the application, game server, and rcon cli on the same machine on the same network.

I have not found any packets through Wireshark, and I have not hit any breakpoints on any of the WriteLines.
My assumption is I am not understanding the listener port, or maybe there is something deeper that I do not understand about how to utilize your library.

I have been using rcon cli to speak with Zomboid without any raw or parsed packet responses.

I do see inside of Zomboid that I am successfully connecting to RCON:
image

I do see that the resolved port doesn't seem to match the ports from zomboid:
image

ConfigurationData used:

{
  "Address": "127.0.0.1",
  "RconPort": 27015,
  "Password": "1234",
  "ListenerPort": 0
}
    Logger.Log.Information("[Bot] - Starting RCON Connection");
    var endpoint = new IPEndPoint(IPAddress.Parse(ConfigurationData.Address), ConfigurationData.RconPort);
    _rconConnection = new RCON(endpoint, ConfigurationData.Password, sourceMultiPacketSupport: true, strictCommandPacketIdMatching: true, autoConnect: true, timeout: 20000);
    await _rconConnection.ConnectAsync();
    await _rconConnection.AuthenticateAsync();
    Logger.Log.Information($"[Bot] - RCON Connection made to Address: {ConfigurationData.Address}:{ConfigurationData.RconPort}");

    Logger.Log.Information("[Bot] - Starting RCON Packet Listener");
    _rconLogReceiver = new LogReceiver(ConfigurationData.ListenerPort, endpoint);

    _rconLogReceiver.Listen<ChatMessage>(async message =>
    {
        Console.WriteLine("");
    });

    _rconLogReceiver.Listen<KillFeed>(async kill =>
    {
        Console.WriteLine("");
    });

    _rconLogReceiver.Listen<PlayerConnected>(async playerConnected =>
    {
        Console.WriteLine("");
    });

    _rconLogReceiver.Listen<PlayerDisconnected>(async playerDisconnected =>
    {
        Console.WriteLine("");
    });

    _rconLogReceiver.Listen<Player>(async player =>
    {
        Console.WriteLine("");
    });

    _rconLogReceiver.Listen<Status>(async status =>
    {
        Console.WriteLine("");
    });

    _rconLogReceiver.ListenRaw(async value =>
    {
        Console.WriteLine("");
    });

    Logger.Log.Information("[Bot] - Started RCON Packet Listener");

Add automated testing

Add automated testing, this should include both Unit tests and Integration tests.
In the processes the testing code will need to be refactored so that some tests will be integration tests against specific game server containers and some will be unit tests that can run by themselves.

Log.Listen for more than Chat

            log.Listen<KillFeed>(kill =>
            {
                Console.WriteLine($"Player {kill.Killer.Name} ({kill.Killer.Team}) killed {kill.Killed.Name} ({kill.Killed.Team}) with {kill.Weapon}");
            });

I can't seem to get this to work?
Do CSGO only supports Chat?

Custom parse

Hey,

I have a problem with creating my custom command parsing, there is no way to set flags or override the parsing method.

Big packets (>4200) exceptions are swallowed

When issuing a command where the response are larger than 4200, the api does not surface the actual error ("Buffer is too large for an RCON packet."). But receiving a TimeoutException.

To reproduce on a CS2 server, run "cvarlist".

CSGO Failed to parse status

Status status = await Rcon.SendCommandAsync("status");

Is throwing an exception "Failed to parse server response"

Server response

hostname: test server | hostname version : 1.37.4.4/13744 1081/7776 secure [G:1:3059110] udp/ip : 111.11.111.111:22222 (public ip: 111.11.111.111) os : Linux type : community dedicated map : de_inferno gotv[0]: port 11223, delay 105.0s, rate 24.0 players : 1 humans, 1 bots (12/0 max) (not hibernating)

Looking at the Status Parser its not taking into consideration the (not hibernating) but that surely isn't causing an exception to be thrown

LogReceiver not working

*** SRCDS CSS/CSGO ***

var log = new LogReceiver(62449, new IPEndPoint(IPAddress.Parse("10.0.0.9"), 27016));
WriteLine($"Port: {log.ResolvedPort}"); // -> 62449

log.ListenRaw(message =>
{
	WriteLine($"Mssage: {message}");
});
logaddress_list: 5 entries
0.0.0.0:50000
0.0.0.0:27015
0.0.0.0:62449
10.0.0.9:62449
127.0.0.1:62449
status
hostname: Test
version : 1.37.8.3/13783 1245/8012 secure
udp/ip  : 10.0.0.9:27016
os      :  Windows
type    :  community dedicated
gotv[0]:  port 27021, delay 105.0s, rate 32.0
players : 1 humans, 3 bots (12/0 max) (not hibernating)

obraz

Wait a sec I need to check something

Missing constant

Hello,

I was trying to build the code to see what is going on since SendCommandAsync never returns for me.

But the constant: Constants.CHECK_STR is missing in the repository, so the code cannot be built. What is its value supposed to be ?

Using Log to receive chat messages

So, I've been struggling with this issue for the last few days.

I'm trying to set up my squad server so we can record chats in a txt file but I can't get anything to event print to console.

I followed an example from the tf2 and set it up, and change the log.listen to ListenRaw just to get anything but nothing printing out.

Not sure if I'm missing something, I have the port open and I can connect via rcon to send commands but receiving packets doesnt seem to be working and I'm not getting any errors.

Confirmed Working: Project Zomboid

I baked this into my Discord bot and can confirm it works with Project Zomboid Multiplayer Servers.

I made a secret channel and use it to kick off Helicopter events when I think its getting too easy.

Wasn't sure what was the best way to let you know it worked with PZ - hope this is ok.

Thank you.

telnet connections

I am unable to make a connection to a 7 Days to Die server, is there a toggle to enable telnet connections? I think 7 days to die telnet is a form of Rcon from what I have read.

I don't get any errors or anything but the connection will not establish.

LogAddressPacket does not support milliseconds in Timestamp

Context:
I'm building a custom log ingestion server (for use with logaddress_add_http in CS2), and am using the parsers in this library to handle certain logs being ingested.

Problem:
The format of the log "packet" slightly differs when using HTTP:

  • the log text does not start with L
  • the log's timestamp includes milliseconds

As a result, I was unable to use the LogAddressPacket type for parsing log content.

Workaround:

I created the following LogPacket type in my project to handle these differences (note that I'm on net8.0):

public sealed partial record LogPacket( string Body, DateTime Timestamp )
{
    [GeneratedRegex( @"^(\d{2}/\d{2}/\d{4} - \d{2}:\d{2}:\d{2}\.\d{3}) - " )]
    private static partial Regex Parser( );

    public static bool TryParse( string? value, [NotNullWhen( true )] out LogPacket? packet )
    {
        if( !string.IsNullOrWhiteSpace( value ) )
        {
            var match = Parser().Match( value );
            if( match.Success && DateTime.TryParseExact( match.Groups[ 1 ].Value, "MM/dd/yyyy - HH:mm:ss.fff", CultureInfo.InvariantCulture, default, out var timestamp ) )
            {
                var body = value[ match.Groups[ 0 ].Length.. ].Trim();
                if( body.Length is not 0 )
                {
                    packet = new( body, timestamp );
                    return true;
                }
            }
        }

        packet = default;
        return false;
    }
}

The LogPacket.Body can then be used with DefaultParser<> implementations as expected.

I considered opening a PR, but wasn't sure if this use case fit the "scope" of this project.

Ark Server

Hello,

I try a simple call for Ark Server, but i receive no response :

class Program { static async Task Main(string[] args) { var rcon = new RCON(IPAddress.Parse("my.server.ip"), 32330, "mypasswordadmin"); await rcon.ConnectAsync(); var players = await rcon.SendCommandAsync("listplayers"); Console.ReadKey(); } }

No error, no exception, just block without any response.

I can connect on RCON with other tools.

Any idea ?

doubt about rconserver

hi guys,

first of all, thank you so much for this library.

second, I'd like to understand and check if it's possible to get everything that is happening in the CSGO server, i.e. kills, players, rounds, chat among players and etc.

I am trying to use your example, but nothing happened as you can see in the print sreen below:

Capturar
Capturar2

I could see something related to logaddress_add to just connect and get the results, but i could not make this working.

Would you mind to explain to me or if you have some example that i can do it ?

thank you,
Marcelo.

"IPAddress" not found

if i add this code

var rcon = new RCON(IPAddress.Parse("10.0.0.1"), 27015, "secret-password");
await rcon.ConnectAsync();

it tells me that the "IPAddress" in not in the Context.

is it possible to send me a project which is working and using this libary

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.