How to get the IP address of the server on which my C# application is running on?

前端 未结 26 1950
天命终不由人
天命终不由人 2020-11-22 06:01

I am running a server, and I want to display my own IP address.

What is the syntax for getting the computer\'s own (if possible, external) IP address?

Someon

相关标签:
26条回答
  • 2020-11-22 06:55

    If you are running in intranet you'll be able to get local machine IP address and if not you'll get external ip address with this: Web:

    //this will bring the IP for the current machine on browser
    System.Web.HttpContext.Current.Request.UserHostAddress
    

    Desktop:

    //This one will bring all local IPs for the desired namespace
    IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
    
    0 讨论(0)
  • 2020-11-22 06:55

    And this is to get all local IPs in csv format in VB.NET

    Imports System.Net
    Imports System.Net.Sockets
    
    Function GetIPAddress() As String
        Dim ipList As List(Of String) = New List(Of String)
        Dim host As IPHostEntry
        Dim localIP As String = "?"
        host = Dns.GetHostEntry(Dns.GetHostName())
        For Each ip As IPAddress In host.AddressList
            If ip.AddressFamily = AddressFamily.InterNetwork Then
                localIP = ip.ToString()
                ipList.Add(localIP)
            End If
        Next
        Dim ret As String = String.Join(",", ipList.ToArray)
        Return ret
    End Function
    
    0 讨论(0)
提交回复
热议问题