0

On my server machine (S.O. Windows server 2008) there are two different ip addresses because there are two network sockets.

This server sends email messages periodically using C# ASPNET and System.Net.Mail.

How to do determine with which IP address, of two available, these email messages are sent from the server?

I have tried using this code but the IP address getted is only the first of the two, also if command ping myserver the output is the second ip value.

Any suggestion?

string hostName = Dns.GetHostName();
string myIP = Dns.GetHostByName(hostName).AddressList[0].ToString();
Response.Write(myIP.ToString());

update #01

private static IPEndPoint QueryRoutingInterface(
          Socket socket,
          IPEndPoint remoteEndPoint)
{
    SocketAddress address = remoteEndPoint.Serialize();

    byte[] remoteAddrBytes = new byte[address.Size];
    for (int i = 0; i < address.Size; i++)
    {
        remoteAddrBytes[i] = address[i];
    }

    byte[] outBytes = new byte[remoteAddrBytes.Length];
    socket.IOControl(
                IOControlCode.RoutingInterfaceQuery,
                remoteAddrBytes,
                outBytes);
    for (int i = 0; i < address.Size; i++)
    {
        address[i] = outBytes[i];
    }

    EndPoint ep = remoteEndPoint.Create(address);
    return (IPEndPoint)ep;
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        IPAddress remoteIp = IPAddress.Parse("192.168.1.55");
        IpEndPoint remoteEndPoint = new IPEndPoint(remoteIp, 0);
        Socket socket = new Socket(
                              AddressFamily.InterNetwork,
                              SocketType.Dgram,
                              ProtocolType.Udp);
        IPEndPoint localEndPoint = QueryRoutingInterface(socket, remoteEndPoint);
        Console.WriteLine("Local EndPoint is: {0}", localEndPoint);
    }
}
  • You need your local routing lookup table and the IP Address of your destination: https://stackoverflow.com/questions/15625023/ip-routing-table-lookup-in-net Look at `route print` in the console to see the configuration of the routing table. – Michael Aug 14 '21 at 09:14
  • @Michael thanks for help. I have tried but I have error on this line of my code `IpEndPoint remoteEndPoint = new IPEndPoint(remoteIp, 0);` Please see **update #01** on my first question. – Edward Sheriff Curtis Aug 14 '21 at 09:29
  • I think there is a typo in the referenced answer, `IPEndPoint` (uppercase P) or `var` will work. – Michael Aug 14 '21 at 09:34

0 Answers0