From a12cfb25f03549224b850a2569a422f00e82f498 Mon Sep 17 00:00:00 2001 From: devlights Date: Fri, 4 Aug 2023 09:16:49 +0000 Subject: [PATCH] Add GetLocalEndPointIpAddressWithSocket example --- .../GetLocalEndPointIpAddressWithSocket.cs | 40 +++++++++++++++++++ TryCSharp.Samples/NetWorking/PingSamples01.cs | 1 + 2 files changed, 41 insertions(+) create mode 100644 TryCSharp.Samples/NetWorking/GetLocalEndPointIpAddressWithSocket.cs diff --git a/TryCSharp.Samples/NetWorking/GetLocalEndPointIpAddressWithSocket.cs b/TryCSharp.Samples/NetWorking/GetLocalEndPointIpAddressWithSocket.cs new file mode 100644 index 0000000..fdf02fe --- /dev/null +++ b/TryCSharp.Samples/NetWorking/GetLocalEndPointIpAddressWithSocket.cs @@ -0,0 +1,40 @@ +using System.Net; +using System.Net.Sockets; +using TryCSharp.Common; + +namespace TryCSharp.Samples.NetWorking +{ + /// + /// UDPソケットを利用して自身のIPアドレスを取得するサンプルです。 + /// + [Sample] + public class GetLocalEndPointIpAddressWithSocket : IExecutable + { + public void Execute() + { + // + // UDPはコネクションレスプロトコルであるので、Connectを呼び出したタイミングでは + // 実際にはリモートエンドポイントへの接続は確率されていない。 + // + // Connectの呼び出しにより、実際の接続は行われていないが + // この操作によってOSは適切なネットワークインターフェースとローカルIPアドレスを選択する。 + // 選択されるIPアドレスは、指定したリモートエンドポイントにルートが存在するネットワークインターフェースに関連付けられたものとなる。 + // + // なので、このコードは指定したリモートIPアドレスに対して最も適切なローカルIPアドレスを選択するOSの動作を利用して + // そのIPアドレスを取得いる。したがって、複数のIPアドレスが存在する場合でも + // 特定のリモートエンドポイントに対して最も適切と判断されたIPアドレスが返される。 + // + IPEndPoint? ep; + using (var sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.IP)) + { + sock.Connect("8.8.8.8", 65530); + ep = sock.LocalEndPoint as IPEndPoint; + } + + if (ep != null) + { + Output.WriteLine($"[Address] {ep.Address.ToString()}"); + } + } + } +} \ No newline at end of file diff --git a/TryCSharp.Samples/NetWorking/PingSamples01.cs b/TryCSharp.Samples/NetWorking/PingSamples01.cs index a572ff7..7f71908 100644 --- a/TryCSharp.Samples/NetWorking/PingSamples01.cs +++ b/TryCSharp.Samples/NetWorking/PingSamples01.cs @@ -1,6 +1,7 @@ using System.Net.NetworkInformation; using System.Threading; using TryCSharp.Common; + // ReSharper disable PossibleNullReferenceException namespace TryCSharp.Samples.NetWorking