Skip to content

Commit 203dbdb

Browse files
committed
First attempt to get local IP
1 parent 97e8db6 commit 203dbdb

File tree

1 file changed

+43
-3
lines changed

1 file changed

+43
-3
lines changed

modNetwork.cs

+43-3
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
using System;
2+
using System.Collections.Generic;
23
using System.Diagnostics;
34
using System.IO;
5+
using System.Linq;
46
using System.Net;
57
using System.Net.NetworkInformation;
8+
using System.Net.Sockets;
69
using System.Text;
710
using System.Threading;
811
using System.Timers;
@@ -41,8 +44,8 @@ public static void Load()
4144
PingTimer.Enabled = true;
4245
modLogging.LogEvent("Connectivity checks scheduled", EventLogEntryType.Information);
4346

44-
Thread InitialGetPublicIP = new Thread(InitialGetPublicIPHandler);
45-
InitialGetPublicIP.Start();
47+
Thread InitialGetIP = new Thread(InitialGetIPHandler);
48+
InitialGetIP.Start();
4649
}
4750

4851
/// <summary>
@@ -56,6 +59,42 @@ public static void Unload()
5659
}
5760
}
5861

62+
/// <summary>
63+
/// Gets this agent's local network address
64+
/// </summary>
65+
/// <returns>(string) Local IP address</returns>
66+
public static string GetLocalIPAddress()
67+
{
68+
if (IsOnline == true)
69+
{
70+
// https://stackoverflow.com/a/44226831
71+
// TODO: We need to account for wireless adapters too.
72+
List<string> iplist = NetworkInterface.GetAllNetworkInterfaces()
73+
.Where(x => x.NetworkInterfaceType == NetworkInterfaceType.Ethernet && x.OperationalStatus == OperationalStatus.Up)
74+
.SelectMany(x => x.GetIPProperties().UnicastAddresses)
75+
.Where(x => x.Address.AddressFamily == AddressFamily.InterNetwork)
76+
.Select(x => x.Address.ToString())
77+
.ToList();
78+
79+
foreach (string ip in iplist)
80+
{
81+
string newLocalIP = ip;
82+
83+
string oldLocalIP = modDatabase.GetConfig("Ping_LastKnownLocalIP");
84+
if (oldLocalIP != newLocalIP)
85+
{
86+
modLogging.LogEvent("Local IP address changed from " + oldLocalIP + " to " + newLocalIP, EventLogEntryType.Warning);
87+
modDatabase.AddOrUpdateConfig(new modDatabase.Config { Key = "Ping_LastKnownLocalIP", Value = newLocalIP });
88+
}
89+
90+
return newLocalIP;
91+
}
92+
93+
return "No valid local IP address found";
94+
}
95+
else return "Not online";
96+
}
97+
5998
/// <summary>
6099
/// Checks a public service for this agent's public IP address
61100
/// </summary>
@@ -141,8 +180,9 @@ public static string SendPing(string Host, int repeat = 1)
141180
/// <summary>
142181
/// Handler to launch initial public IP check on a new Thread
143182
/// </summary>
144-
private static void InitialGetPublicIPHandler()
183+
private static void InitialGetIPHandler()
145184
{
185+
GetLocalIPAddress();
146186
GetPublicIPAddress();
147187
}
148188

0 commit comments

Comments
 (0)