buechermarkt/BuechermarktClient/GetConnection.xaml.cs

91 lines
2.5 KiB
C#
Raw Permalink Normal View History

2017-09-27 13:57:10 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace BuechermarktClient
{
/// <summary>
/// Interaktionslogik für GetConnection.xaml
/// </summary>
public partial class GetConnection : Window
{
public const string ServerIdentifier = "BUECHERMARKTCLIENT00018946";
public GetConnection()
{
InitializeComponent();
Loaded += (sender, e) =>
{
ListenForServer();
};
}
private UdpClient UdpClient;
public void ListenForServer()
{
UdpClient = new UdpClient(3000);
UdpClient.BeginReceive(Recevie, new object());
}
public void Recevie(IAsyncResult ar)
{
var ip = new IPEndPoint(IPAddress.Any, 15000);
var bytes = UdpClient.EndReceive(ar, ref ip);
string message = Encoding.ASCII.GetString(bytes);
if(message == ServerIdentifier)
{
var cip = ip.Address.ToString();
if (IsLocalIpAddress(cip)) cip = "127.0.0.1";
MainWindow.MongoHost = cip;
2017-09-27 13:57:10 +00:00
Dispatcher.BeginInvoke(new Action(delegate () {
Close();
}));
//Success
} else
{
//Retry
ListenForServer();
}
}
private static bool IsLocalIpAddress(string host)
{
try
{ // get host IP addresses
IPAddress[] hostIPs = Dns.GetHostAddresses(host);
// get local IP addresses
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
// test if any host IP equals to any local IP or to localhost
foreach (IPAddress hostIP in hostIPs)
{
// is localhost
if (IPAddress.IsLoopback(hostIP)) return true;
// is local address
foreach (IPAddress localIP in localIPs)
{
if (hostIP.Equals(localIP)) return true;
}
}
}
catch { }
return false;
}
2017-09-27 13:57:10 +00:00
}
}