User:JayJeckel/Servers.dat File Format
Jump to navigation
Jump to search
The servers.dat file uses a simple binary format and is composed of two sections: the header and the server data.
Type Formats
The types used in the servers.dat file are below, all are stored little-endian.
Types | Bytes | Notes |
---|---|---|
Int32 | 4 | Signed -2,147,483,648 .. 2,147,483,647 |
String | * | Pascal string. First byte contains the length of the string. |
Header
The header stores a single value, the integer representation of the Terraria version that wrote the servers.dat file.
Type | Description |
---|---|
Int32 | Terraria Release Version Integer |
Server List Data
The server list is composed of ten (10) entries, each entry being comprised of three (3) values.
Type | Description |
---|---|
String | Server Name |
String | Server IP |
Int32 | Server Port |
Example Code
C#
First, define a struct to hold the server entries.
public struct ServerData
{
public ServerData(string name, string ip, int port)
{
this.Name = name;
this.IP = ip;
this.Port = port;
}
public readonly string Name;
public readonly string IP;
public readonly int Port;
}
Second, define a static method to load a servers.dat file.
public static void LoadServersFile(string path, ref Int32 release, ref ServerData[] servers)
{
if (File.Exists(path))
{
using (FileStream stream = new FileStream(path, FileMode.Open))
{
using (BinaryReader reader = new BinaryReader(stream))
{
release = reader.ReadInt32();
for (int index = 0; index < servers.Length; index++)
{
servers[index] = new ServerData(reader.ReadString(), reader.ReadString(), reader.ReadInt32());
}
}
}
}
}
Third, define a static method to save a servers.dat file.
public static void SaveServersFile(string path, Int32 release, ServerData[] servers)
{
using (FileStream stream = new FileStream(path, FileMode.Create))
{
using (BinaryWriter writer = new BinaryWriter(stream))
{
writer.Write(release);
for (int index = 0; index < servers.Length; index++)
{
writer.Write(servers[index].Name);
writer.Write(servers[index].IP);
writer.Write(servers[index].Port);
}
}
}
}
Lastly, examples of how to use the methods.
string path = /* path to the servers.dat file */;
int release = 0;
ServerData[] servers = new ServerData[10];
LoadServersFile(path, ref release, ref servers);
SaveServersFile(path, release, servers);