Related
I'm trying to start my "webserver" on all local IP's. So I have to send a string to WebServer ws = new WebServer(SendResponse, IPs.GetIPs("program"));, and a Array to static string[] uris.
Now it only receives one IP, tried some other ways like sending a string to WebServer ws = new WebServer(SendResponse, IPs.GetIPs("program")); but that also didn't work with multiple IP's.
It needs to return a string for program and a array for webserver.
The string should be something like this: "http://192.168.0.107:1337/", "http://192.168.56.1:1337/" for program.
How would I send more then 1 argument to a function and to a array. I know this code doesn't work but I'm desperate right now to get this working.
IPs.cs:
public static string GetIPs(string args)
{
string[] combinedString = { };
List<string> IPAdressenLijst = new List<string>();
IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress ip in ips)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
if (args == "program")
{
IPAdressenLijst.Add("http://" + ip + ":1337/");
combinedString = IPAdressenLijst.ToArray();
}
else if (args == "webserver")
{
IPAdressenLijst.Add("http://" + ip + ":1337/start/");
IPAdressenLijst.Add("http://" + ip + ":1337/stop/");
combinedString = IPAdressenLijst.ToArray();
}
}
}
return combinedString[0];
}
Program.cs:
static void Main(string[] args)
{
Console.WriteLine(DateTime.Now + " Press any key to exit.");
//WebServer ws = new WebServer(SendResponse, "http://192.168.0.107:1337/", "http://localhost:1337/");
WebServer ws = new WebServer(SendResponse, IPs.GetIPs("program"));
ws.Run();
Console.ReadKey();
ws.Stop();
}
public static string SendResponse(HttpListenerRequest request)
{
return string.Format("TEST");
}
WebServer.cs:
public class WebServer
{
//static string[] uris =
//{
// "http://192.168.0.107:1337/start/",
// "http://192.168.0.107:1337/stop/"
//};
static string[] uris =
{
IPs.GetIPs("webserver")
};
}
To start a TcpListener (for your webserver) you can use the IPAddress.Any address like below:
var server = new TcpListener(IPAddress.Any, port);
Now, to your code: The GetIPs function has bunch of issues. While you loop, you keep overwriting combinedString, every time. To top it, you actually just return the first item from combinedString. From the context of the question, I gather that you want to return all IP addresses and not just one
This is how that function should be
public static List<string> GetIPs(string args) {
var ipAdressenLijst = new List<string>();
IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress ip in ips) {
if (ip.AddressFamily == AddressFamily.InterNetwork) {
if (args == "program") {
ipAdressenLijst.Add("http://" + ip + ":1337/");
} else if (args == "webserver") {
ipAdressenLijst.Add("http://" + ip + ":1337/start/");
ipAdressenLijst.Add("http://" + ip + ":1337/stop/");
}
}
}
return ipAdressenLijst;
}
Your Webserver.cs code should look like this to handle the incoming array of URIs.
public class WebServer {
string[] Uris;
public WebServer(Func<HttpListenerRequest, string> sendResponse, IEnumerable<string> ipAdressenLijst)
{
Uris = ipAdressenLijst.ToArray();
}
}
In Main function in Program.cs, your call should look like
WebServer ws = new WebServer(SendResponse, IPs.GetIPs("webserver"));
There is a lot of guess work on my side, as not all information is available in your question.. Let me know if that makes sense and works for you
I want the public IP address of the client who is using my website.
The code below is showing the local IP in the LAN, but I want the public IP of the client.
//get mac address
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
String sMacAddress = string.Empty;
foreach (NetworkInterface adapter in nics)
{
if (sMacAddress == String.Empty)// only return MAC Address from first card
{
IPInterfaceProperties properties = adapter.GetIPProperties();
sMacAddress = adapter.GetPhysicalAddress().ToString();
}
}
// To Get IP Address
string IPHost = Dns.GetHostName();
string IP = Dns.GetHostByName(IPHost).AddressList[0].ToString();
Output:
Ip Address : 192.168.1.7
Please help me to get the public IP address.
This is what I use:
protected void GetUser_IP()
{
string VisitorsIPAddr = string.Empty;
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
}
uip.Text = "Your IP is: " + VisitorsIPAddr;
}
"uip" is the name of the label in the aspx page that shows the user IP.
You can use "HTTP_X_FORWARDED_FOR" or "REMOTE_ADDR" header attribute.
Refer method GetVisitorIPAddress from Machine Syntax blog .
/// <summary>
/// method to get Client ip address
/// </summary>
/// <param name="GetLan"> set to true if want to get local(LAN) Connected ip address</param>
/// <returns></returns>
public static string GetVisitorIPAddress(bool GetLan = false)
{
string visitorIPAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (String.IsNullOrEmpty(visitorIPAddress))
visitorIPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (string.IsNullOrEmpty(visitorIPAddress))
visitorIPAddress = HttpContext.Current.Request.UserHostAddress;
if (string.IsNullOrEmpty(visitorIPAddress) || visitorIPAddress.Trim() == "::1")
{
GetLan = true;
visitorIPAddress = string.Empty;
}
if (GetLan && string.IsNullOrEmpty(visitorIPAddress))
{
//This is for Local(LAN) Connected ID Address
string stringHostName = Dns.GetHostName();
//Get Ip Host Entry
IPHostEntry ipHostEntries = Dns.GetHostEntry(stringHostName);
//Get Ip Address From The Ip Host Entry Address List
IPAddress[] arrIpAddress = ipHostEntries.AddressList;
try
{
visitorIPAddress = arrIpAddress[arrIpAddress.Length - 2].ToString();
}
catch
{
try
{
visitorIPAddress = arrIpAddress[0].ToString();
}
catch
{
try
{
arrIpAddress = Dns.GetHostAddresses(stringHostName);
visitorIPAddress = arrIpAddress[0].ToString();
}
catch
{
visitorIPAddress = "127.0.0.1";
}
}
}
}
return visitorIPAddress;
}
Combination of all of these suggestions, and the reasons behind them. Feel free to add more test cases too. If getting the client IP is of utmost importance, than you might wan to get all of theses are run some comparisons on which result might be more accurate.
Simple check of all suggestions in this thread plus some of my own code...
using System.IO;
using System.Net;
public string GetUserIP()
{
string strIP = String.Empty;
HttpRequest httpReq = HttpContext.Current.Request;
//test for non-standard proxy server designations of client's IP
if (httpReq.ServerVariables["HTTP_CLIENT_IP"] != null)
{
strIP = httpReq.ServerVariables["HTTP_CLIENT_IP"].ToString();
}
else if (httpReq.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
strIP = httpReq.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
//test for host address reported by the server
else if
(
//if exists
(httpReq.UserHostAddress.Length != 0)
&&
//and if not localhost IPV6 or localhost name
((httpReq.UserHostAddress != "::1") || (httpReq.UserHostAddress != "localhost"))
)
{
strIP = httpReq.UserHostAddress;
}
//finally, if all else fails, get the IP from a web scrape of another server
else
{
WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
using (WebResponse response = request.GetResponse())
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
strIP = sr.ReadToEnd();
}
//scrape ip from the html
int i1 = strIP.IndexOf("Address: ") + 9;
int i2 = strIP.LastIndexOf("</body>");
strIP = strIP.Substring(i1, i2 - i1);
}
return strIP;
}
That code gets you the IP address of your server not the address of the client who is accessing your website. Use the HttpContext.Current.Request.UserHostAddress property to the client's IP address.
For Web Applications ( ASP.NET MVC and WebForm )
/// <summary>
/// Get current user ip address.
/// </summary>
/// <returns>The IP Address</returns>
public static string GetUserIPAddress()
{
var context = System.Web.HttpContext.Current;
string ip = String.Empty;
if (context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
ip = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
else if (!String.IsNullOrWhiteSpace(context.Request.UserHostAddress))
ip = context.Request.UserHostAddress;
if (ip == "::1")
ip = "127.0.0.1";
return ip;
}
For Windows Applications ( Windows Form, Console, Windows Service , ... )
static void Main(string[] args)
{
HTTPGet req = new HTTPGet();
req.Request("http://checkip.dyndns.org");
string[] a = req.ResponseBody.Split(':');
string a2 = a[1].Substring(1);
string[] a3=a2.Split('<');
string a4 = a3[0];
Console.WriteLine(a4);
Console.ReadLine();
}
So many of these code snippets are really big and could confuse new programmers looking for help.
How about this simple and compact code to fetch the IP address of the visitor?
string ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
{
ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
Simple, short and compact.
I have an extension method:
public static string GetIp(this HttpContextBase context)
{
if (context == null || context.Request == null)
return string.Empty;
return context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
?? context.Request.UserHostAddress;
}
Note: "HTTP_X_FORWARDED_FOR" is for ip behind proxy. context.Request.UserHostAddress is identical to "REMOTE_ADDR".
But bear in mind it is not necessary the actual IP though.
Sources:
IIS Server Variables
Link
My version handles both ASP.NET or LAN IPs:
/**
* Get visitor's ip address.
*/
public static string GetVisitorIp() {
string ip = null;
if (HttpContext.Current != null) { // ASP.NET
ip = string.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"])
? HttpContext.Current.Request.UserHostAddress
: HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
}
if (string.IsNullOrEmpty(ip) || ip.Trim() == "::1") { // still can't decide or is LAN
var lan = Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(r => r.AddressFamily == AddressFamily.InterNetwork);
ip = lan == null ? string.Empty : lan.ToString();
}
return ip;
}
private string GetClientIpaddress()
{
string ipAddress = string.Empty;
ipAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (ipAddress == "" || ipAddress == null)
{
ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
return ipAddress;
}
else
{
return ipAddress;
}
}
On MVC 5 you can use this:
string cIpAddress = Request.UserHostAddress; //Gets the client ip address
or
string cIpAddress = Request.ServerVariables["REMOTE_ADDR"]; //Gets the client ip address
In MVC IP can be obtained by the following Code
string ipAddress = Request.ServerVariables["REMOTE_ADDR"];
string IP = HttpContext.Current.Request.Params["HTTP_CLIENT_IP"] ?? HttpContext.Current.Request.UserHostAddress;
just use this..................
public string GetIP()
{
string externalIP = "";
externalIP = (new WebClient()).DownloadString("http://checkip.dyndns.org/");
externalIP = (new Regex(#"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")).Matches(externalIP)[0].ToString();
return externalIP;
}
We connect to servers that give us our external IP address and try to parse the IP from returning HTML pages. But when servers make small changes on these pages or remove them, these methods stop working properly.
Here is a method that takes the external IP address using a server which has been alive for years and returns a simple response rapidly...
https://www.codeproject.com/Tips/452024/Getting-the-External-IP-Address
Private string getExternalIp()
{
try
{
string externalIP;
externalIP = (new
WebClient()).DownloadString("http://checkip.dyndns.org/");
externalIP = (new Regex(#"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
.Matches(externalIP)[0].ToString();
return externalIP;
}
catch { return null; }
}
VB.NET
Imports System.Net
Private Function GetExternalIp() As String
Try
Dim ExternalIP As String
ExternalIP = (New WebClient()).DownloadString("http://checkip.dyndns.org/")
ExternalIP = (New Regex("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")) _
.Matches(ExternalIP)(0).ToString()
Return ExternalIP
Catch
Return Nothing
End Try
End Function
lblmessage.Text =Request.ServerVariables["REMOTE_HOST"].ToString();
You can download xNet at: https://drive.google.com/open?id=1fmUosINo8hnDWY6s4IV4rDnHKLizX-Hq
First, you need import xNet, code:
using xNet;
Code:
void LoadpublicIP()
{
HttpRequest httprequest = new HttpRequest();
String HTML5 = httprequest.Get("https://whoer.net/").ToString();
MatchCollection collect = Regex.Matches(HTML5, #"<strong data-clipboard-target="".your-ip(.*?)</strong>", RegexOptions.Singleline);
foreach (Match match in collect)
{
var val = Regex.Matches(match.Value, #"(?<ip>(\d|\.)+)");
foreach (Match m in val)
{
richTextBox1.Text = m.Groups[2].Value;
}
}
}
I guess it's already time that I ask others. Is it possible to create a websocket server using C# and server request from HTML5 codes?
I am currently using the System package for websocket. I have a code that I downloaded over the internet and here it is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WebSocketChatServer
{
using WebSocketServer;
class ChatServer
{
WebSocketServer wss;
List<User> Users = new List<User>();
string unknownName = "john doe";
public ChatServer()
{
// wss = new WebSocketServer(8181, "http://localhost:8080", "ws://localhost:8181/chat");
wss = new WebSocketServer(8080, "http://localhost:8080", "ws://localhost:8080/dotnet/Chats");
wss.Logger = Console.Out;
wss.LogLevel = ServerLogLevel.Subtle;
wss.ClientConnected += new ClientConnectedEventHandler(OnClientConnected);
wss.Start();
KeepAlive();
}
private void KeepAlive()
{
string r = Console.ReadLine();
while (r != "quit")
{
if(r == "users")
{
Console.WriteLine(Users.Count);
}
r = Console.ReadLine();
}
}
void OnClientConnected(WebSocketConnection sender, EventArgs e)
{
Console.WriteLine("test");
Users.Add(new User() { Connection = sender });
sender.Disconnected += new WebSocketDisconnectedEventHandler(OnClientDisconnected);
sender.DataReceived += new DataReceivedEventHandler(OnClientMessage);
}
void OnClientMessage(WebSocketConnection sender, DataReceivedEventArgs e)
{
Console.WriteLine(sender);
User user = Users.Single(a => a.Connection == sender);
if (e.Data.Contains("/nick"))
{
string[] tmpArray = e.Data.Split(new char[] { ' ' });
if (tmpArray.Length > 1)
{
string myNewName = tmpArray[1];
while (Users.Where(a => a.Name == myNewName).Count() != 0)
{
myNewName += "_";
}
if (user.Name != null)
wss.SendToAll("server: '" + user.Name + "' changed name to '" + myNewName + "'");
else
sender.Send("you are now know as '" + myNewName + "'");
user.Name = myNewName;
}
}
else
{
string name = (user.Name == null) ? unknownName : user.Name;
wss.SendToAllExceptOne(name + ": " + e.Data, sender);
sender.Send("me: " + e.Data);
}
}
void OnClientDisconnected(WebSocketConnection sender, EventArgs e)
{
try
{
User user = Users.Single(a => a.Connection == sender);
string name = (user.Name == null) ? unknownName : user.Name;
wss.SendToAll("server: "+name + " disconnected");
Users.Remove(user);
}
catch (Exception exc)
{
Console.WriteLine("ehm...");
}
}
}
}
And I have this code for client side:
<!HTML>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script language="javascript" type="text/javascript">
jQuery(document).ready(function(){
var socket = new WebSocket("ws://localhost:8080");
socket.onopen = function(){
alert("Socket has been opened!");
}
});
</script>
</head>
</HTML>
As I run my C# console app and load the client page, the app tells me that there's someone who connected in the port it is listening to. But on my client side, as I look in firebug's console, it gives me the beginner's classic error:
Firefox can't establish a connection to the server at ws://localhost:8080/
What I would like to achieve is establish first a successful websocket connection and push value to my client coming from my server.
I have considered Alchemy but the version I have is Visual Studio express 2010, the free version, and it says that "solution folders are not supported in this version of application".
Any help will be very much appreciated.
I've been developing a server for a JavaScript/HTML 5 game for about 7 months now have you looked into Alchemy Websockets? its pretty easy to use.
Example:
using Alchemy;
using Alchemy.Classes;
namespace GameServer
{
static class Program
{
public static readonly ConcurrentDictionary<ClientPeer, bool> OnlineUsers = new ConcurrentDictionary<ClientPeer, bool>();
static void Main(string[] args)
{
var aServer = new WebSocketServer(4530, IPAddress.Any)
{
OnReceive = context => OnReceive(context),
OnConnected = context => OnConnect(context),
OnDisconnect = context => OnDisconnect(context),
TimeOut = new TimeSpan(0, 10, 0),
FlashAccessPolicyEnabled = true
};
}
private static void OnConnect(UserContext context)
{
var client = new ClientPeer(context);
OnlineUsers.TryAdd(client, false);
//Do something with the new client
}
}
}
As you can see its pretty easy to work with and I find their documentation very good (note ClientPeer is a custom class of mine just using it as an example).
What you are trying to achieve will be far easier if you take a look at ASP.NET SignalR
It has support for high level hubs to implement realtime communication and also has a persistent connection low level class to have a finely grained control over the communication.
Support for multiple client types and fallback if websockets isn't supported at both ends of the communication (it can optionally use long polling or forever frames).
The reason for this error is ( probably ) because you are not responding to the handshake. Once the connection is established browser sends some data and the server must respond appropriately ( otherwise browser will close the connection ). You can read more about this on wiki or directly in specification.
I modified a code i downloaded online and here's what I got now:
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Security.Cryptography;
using System.Threading;
namespace WebSocketServer
{
public enum ServerLogLevel { Nothing, Subtle, Verbose };
public delegate void ClientConnectedEventHandler(WebSocketConnection sender, EventArgs e);
public class WebSocketServer
{
#region private members
private string webSocketOrigin; // location for the protocol handshake
private string webSocketLocation; // location for the protocol handshake
#endregion
static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
static IPEndPoint ipLocal;
public event ClientConnectedEventHandler ClientConnected;
/// <summary>
/// TextWriter used for logging
/// </summary>
public TextWriter Logger { get; set; } // stream used for logging
/// <summary>
/// How much information do you want, the server to post to the stream
/// </summary>
public ServerLogLevel LogLevel = ServerLogLevel.Subtle;
/// <summary>
/// Gets the connections of the server
/// </summary>
public List<WebSocketConnection> Connections { get; private set; }
/// <summary>
/// Gets the listener socket. This socket is used to listen for new client connections
/// </summary>
public Socket ListenerSocker { get; private set; }
/// <summary>
/// Get the port of the server
/// </summary>
public int Port { get; private set; }
public WebSocketServer(int port, string origin, string location)
{
Port = port;
Connections = new List<WebSocketConnection>();
webSocketOrigin = origin;
webSocketLocation = location;
}
/// <summary>
/// Starts the server - making it listen for connections
/// </summary>
public void Start()
{
// create the main server socket, bind it to the local ip address and start listening for clients
ListenerSocker = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
ipLocal = new IPEndPoint(IPAddress.Loopback, Port);
ListenerSocker.Bind(ipLocal);
ListenerSocker.Listen(100);
LogLine(DateTime.Now + "> server stated on " + ListenerSocker.LocalEndPoint, ServerLogLevel.Subtle);
ListenForClients();
}
// look for connecting clients
private void ListenForClients()
{
ListenerSocker.BeginAccept(new AsyncCallback(OnClientConnect), null);
}
private void OnClientConnect(IAsyncResult asyn)
{
byte[] buffer = new byte[1024];
string headerResponse = "";
// create a new socket for the connection
var clientSocket = ListenerSocker.EndAccept(asyn);
var i = clientSocket.Receive(buffer);
headerResponse = (System.Text.Encoding.UTF8.GetString(buffer)).Substring(0, i);
//Console.WriteLine(headerResponse);
if (clientSocket != null)
{
// Console.WriteLine("HEADER RESPONSE:"+headerResponse);
var key = headerResponse.Replace("ey:", "`")
.Split('`')[1] // dGhlIHNhbXBsZSBub25jZQ== \r\n .......
.Replace("\r", "").Split('\n')[0] // dGhlIHNhbXBsZSBub25jZQ==
.Trim();
var test1 = AcceptKey(ref key);
var newLine = "\r\n";
var name = "Charmaine";
var response = "HTTP/1.1 101 Switching Protocols" + newLine
+ "Upgrade: websocket" + newLine
+ "Connection: Upgrade" + newLine
+ "Sec-WebSocket-Accept: " + test1 + newLine + newLine
+ "Testing lang naman po:" + name
;
// which one should I use? none of them fires the onopen method
clientSocket.Send(System.Text.Encoding.UTF8.GetBytes(response));
}
// keep track of the new guy
var clientConnection = new WebSocketConnection(clientSocket);
Connections.Add(clientConnection);
// clientConnection.Disconnected += new WebSocketDisconnectedEventHandler(ClientDisconnected);
Console.WriteLine("New user: " + ipLocal);
// invoke the connection event
if (ClientConnected != null)
ClientConnected(clientConnection, EventArgs.Empty);
if (LogLevel != ServerLogLevel.Nothing)
clientConnection.DataReceived += new DataReceivedEventHandler(DataReceivedFromClient);
// listen for more clients
ListenForClients();
}
void ClientDisconnected(WebSocketConnection sender, EventArgs e)
{
Connections.Remove(sender);
LogLine(DateTime.Now + "> " + sender.ConnectionSocket.LocalEndPoint + " disconnected", ServerLogLevel.Subtle);
}
void DataReceivedFromClient(WebSocketConnection sender, DataReceivedEventArgs e)
{
Log(DateTime.Now + "> data from " + sender.ConnectionSocket.LocalEndPoint, ServerLogLevel.Subtle);
Log(": " + e.Data + "\n" + e.Size + " bytes", ServerLogLevel.Verbose);
LogLine("", ServerLogLevel.Subtle);
}
/// <summary>
/// send a string to all the clients (you spammer!)
/// </summary>
/// <param name="data">the string to send</param>
public void SendToAll(string data)
{
Connections.ForEach(a => a.Send(data));
}
/// <summary>
/// send a string to all the clients except one
/// </summary>
/// <param name="data">the string to send</param>
/// <param name="indifferent">the client that doesn't care</param>
public void SendToAllExceptOne(string data, WebSocketConnection indifferent)
{
foreach (var client in Connections)
{
if (client != indifferent)
client.Send(data);
}
}
/// <summary>
/// Takes care of the initial handshaking between the the client and the server
/// </summary>
private void Log(string str, ServerLogLevel level)
{
if (Logger != null && (int)LogLevel >= (int)level)
{
Logger.Write(str);
}
}
private void LogLine(string str, ServerLogLevel level)
{
Log(str + "\r\n", level);
}
private static string AcceptKey(ref string key)
{
string longKey = key + guid;
byte[] hashBytes = ComputeHash(longKey);
return Convert.ToBase64String(hashBytes);
}
static SHA1 sha1 = SHA1CryptoServiceProvider.Create();
private static byte[] ComputeHash(string str)
{
return sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(str));
}
private void ShakeHands(Socket conn)
{
using (var stream = new NetworkStream(conn))
using (var reader = new StreamReader(stream))
using (var writer = new StreamWriter(stream))
{
//read handshake from client (no need to actually read it, we know its there):
LogLine("Reading client handshake:", ServerLogLevel.Verbose);
string r = null;
while (r != "")
{
r = reader.ReadLine();
LogLine(r, ServerLogLevel.Verbose);
}
// send handshake to the client
writer.WriteLine("HTTP/1.1 101 Web Socket Protocol Handshake");
writer.WriteLine("Upgrade: WebSocket");
writer.WriteLine("Connection: Upgrade");
writer.WriteLine("WebSocket-Origin: " + webSocketOrigin);
writer.WriteLine("WebSocket-Location: " + webSocketLocation);
writer.WriteLine("");
}
// tell the nerds whats going on
LogLine("Sending handshake:", ServerLogLevel.Verbose);
LogLine("HTTP/1.1 101 Web Socket Protocol Handshake", ServerLogLevel.Verbose);
LogLine("Upgrade: WebSocket", ServerLogLevel.Verbose);
LogLine("Connection: Upgrade", ServerLogLevel.Verbose);
LogLine("WebSocket-Origin: " + webSocketOrigin, ServerLogLevel.Verbose);
LogLine("WebSocket-Location: " + webSocketLocation, ServerLogLevel.Verbose);
LogLine("", ServerLogLevel.Verbose);
LogLine("Started listening to client", ServerLogLevel.Verbose);
//conn.Listen();
}
}
}
Connection issue resolved, next would be SENDING DATA to client.
just change shakehands in WebSocketServer.cs file in solution with below code and your error will gone..
private void ShakeHands(Socket conn)
{
using (var stream = new NetworkStream(conn))
using (var reader = new StreamReader(stream))
using (var writer = new StreamWriter(stream))
{
//read handshake from client (no need to actually read it, we know its there):
LogLine("Reading client handshake:", ServerLogLevel.Verbose);
string r = null;
Dictionary<string, string> headers = new Dictionary<string, string>();
while (r != "")
{
r = reader.ReadLine();
string[] tokens = r.Split(new char[] { ':' }, 2);
if (!string.IsNullOrWhiteSpace(r) && tokens.Length > 1)
{
headers[tokens[0]] = tokens[1].Trim();
}
LogLine(r, ServerLogLevel.Verbose);
}
//string line = string.Empty;
//while ((line = reader.ReadLine()) != string.Empty)
//{
// string[] tokens = line.Split(new char[] { ':' }, 2);
// if (!string.IsNullOrWhiteSpace(line) && tokens.Length > 1)
// {
// headers[tokens[0]] = tokens[1].Trim();
// }
//}
string responseKey = "";
string key = string.Concat(headers["Sec-WebSocket-Key"], "258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
using (SHA1 sha1 = SHA1.Create())
{
byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(key));
responseKey = Convert.ToBase64String(hash);
}
// send handshake to the client
writer.WriteLine("HTTP/1.1 101 Web Socket Protocol Handshake");
writer.WriteLine("Upgrade: WebSocket");
writer.WriteLine("Connection: Upgrade");
writer.WriteLine("WebSocket-Origin: " + webSocketOrigin);
writer.WriteLine("WebSocket-Location: " + webSocketLocation);
//writer.WriteLine("Sec-WebSocket-Protocol: chat");
writer.WriteLine("Sec-WebSocket-Accept: " + responseKey);
writer.WriteLine("");
}
// tell the nerds whats going on
LogLine("Sending handshake:", ServerLogLevel.Verbose);
LogLine("HTTP/1.1 101 Web Socket Protocol Handshake", ServerLogLevel.Verbose);
LogLine("Upgrade: WebSocket", ServerLogLevel.Verbose);
LogLine("Connection: Upgrade", ServerLogLevel.Verbose);
LogLine("WebSocket-Origin: " + webSocketOrigin, ServerLogLevel.Verbose);
LogLine("WebSocket-Location: " + webSocketLocation, ServerLogLevel.Verbose);
LogLine("", ServerLogLevel.Verbose);
LogLine("Started listening to client", ServerLogLevel.Verbose);
//conn.Listen();
}
You may also take a look at the WebSocketRPC library which should be pretty simple to use, for both the "raw" connection and the RPC connections (the messages can also be mixed).
The following can be useful to you:
The code responsible for sending/receiving raw messages is located in the Connection class.
In the repository you can also find how a base JavaScript client is implemented.
Disclaimer: I am the author.
Here's what's going on. I have an ASP.NET MVC 4 Web API web application. I can call API resources via URL. One of these functions get performance monitoring data for a specified amount of time and returns it in JSON once it has completed. However, what I want to do is return
It is IMPORTANT to note that I am working with a the browser and API resources in the model, not with a View. Please don't casually tell me to use Javascript in a View, because there is no view, or tell me to look at the SignalR wiki because the information for ".NET" sections is meant for desktop applications, not web apps. For example, you can't "Console.WriteLine()" to a browser.
To reiterate, I am using ASP.NET MVC 4 Web API to develop an API, and am calling the API via URL in the browser and it is returning JSON. I am attempting to use SignalR to have the app send JSON to the browser, but it is not doing anything at all. Rather, the application simply returns the completed JSON from the controller action with all of the performance data values once the process has completed. In other words, SignalR is not working.
So what I'm trying to do is while the API resource is gathering all the information, SignalR sends JSON to the browser every second so that the client can see what's going on in real time.
What I need to find out is why SignalR isn't sending it, and how I can send information to be displayed in the browser without Javascript, since I'm working from a model class, not from a view.
As you can see, I subscribe to the event using On, and then use Invoke to call the server-side hub method SendToClient.
Please let me know if I'm trying to do is impossible. I have never heard of a "real-time", dynamic API call via URL.
Here is my hub class. It is located in ~/signalr/hubs and is in a file called LiveHub.cs. The method Send is what I am trying to invoke in the method seen in the next code block.
namespace PerfMon2.signalr.hubs
{
public class LiveHub : Hub
{
public void SendToClient(List<DataValueInfo> json)
{
Clients.showValue(json);
}
}
}
Here is the method from LogDBRepository.cs that includes the SignalR calls.
public List<LogInfo> LogTimedPerfData(string macName, string categoryName, string counterName,
string instanceName, string logName, string live, long? seconds)
{
iModsDBRepository modsDB = new iModsDBRepository();
List<MachineInfo> theMac = modsDB.GetMachineByName(macName);
if (theMac.Count == 0)
return new List<LogInfo>();
else if (instanceName == null)
{
if (!PerformanceCounterCategory.Exists(categoryName, macName) ||
!PerformanceCounterCategory.CounterExists(counterName, categoryName, macName) )
{
return new List<LogInfo>();
}
}
else if (instanceName != null)
{
if (!PerformanceCounterCategory.Exists(categoryName, macName) ||
!PerformanceCounterCategory.CounterExists(counterName, categoryName, macName) ||
!PerformanceCounterCategory.InstanceExists(instanceName, categoryName, macName))
{
return new List<LogInfo>();
}
}
else if (logName == null)
{
return new List<LogInfo>();
}
// Check if entered log name is a duplicate for the authenticated user
List<LogInfo> checkDuplicateLog = this.GetSingleLog(logName);
if (checkDuplicateLog.Count > 0)
{
return new List<LogInfo>();
}
PerformanceCounterCategory category = new PerformanceCounterCategory(categoryName, theMac[0].MachineName);
if (category.CategoryName == null || category.MachineName == null)
{
return new List<LogInfo>();
}
List<LogInfo> logIt = new List<LogInfo>();
if (category.CategoryType != PerformanceCounterCategoryType.SingleInstance)
{
List<InstanceInfo> instances = modsDB.GetInstancesFromCatMacName(theMac[0].MachineName, category.CategoryName);
foreach (InstanceInfo inst in instances)
{
if (!category.InstanceExists(inst.InstanceName))
{
continue;
}
else if (inst.InstanceName.Equals(instanceName, StringComparison.OrdinalIgnoreCase))
{
PerformanceCounter perfCounter = new PerformanceCounter(categoryName, counterName,
inst.InstanceName, theMac[0].MachineName);
//CounterSample data = perfCounter.NextSample();
//double value = CounterSample.Calculate(data, perfCounter.NextSample());
string data = "";
List<UserInfo> currUser = this.GetUserByName(WindowsIdentity.GetCurrent().Name);
string timeStarted = DateTime.Now.ToString("MM/dd/yyyy - h:mm:ss tt");
//string[] dataValues = new string[(int)seconds];
List<string> dataValues = new List<string>();
var hubConnection = new HubConnection("http://localhost/PerfMon2/");
hubConnection.Credentials = CredentialCache.DefaultNetworkCredentials;
var perfMon = hubConnection.CreateProxy("LiveHub");
// perfMon.On("sendValue", message => Console.WriteLine(message));
perfMon.On("showValue", json => Console.WriteLine(json));
hubConnection.Start().Wait();
List<DataValueInfo> lol = new List<DataValueInfo>();
for (int i = 0; i < seconds; i++)
{
data = "Value " + i + ": " + perfCounter.NextValue().ToString();
//dataValues[i] = data;
dataValues.Add(data);
lol.Add(new DataValueInfo
{
Value = perfCounter.NextValue().ToString()
});
// perfMon.Invoke<List<DataValueInfo>>("Send", lol);
perfMon.Invoke("SendToClient", lol);
Thread.Sleep(1000);
}
string timeFinished = DateTime.Now.ToString("MM/dd/yyyy - h:mm:ss tt");
Log log = new Log
{
LogName = logName,
CounterName = perfCounter.CounterName,
InstanceName = perfCounter.InstanceName,
CategoryName = perfCounter.CategoryName,
MachineName = perfCounter.MachineName,
TimeStarted = timeStarted,
TimeFinished = timeFinished,
PerformanceData = string.Join(",", dataValues),
UserID = currUser[0].UserID
};
this.CreateLog(log);
logIt.Add(new LogInfo
{
LogName = logName,
CounterName = perfCounter.CounterName,
InstanceName = perfCounter.InstanceName,
CategoryName = perfCounter.CategoryName,
MachineName = perfCounter.MachineName,
TimeStarted = timeStarted,
TimeFinished = timeFinished,
PerformanceData = dataValues.ToList<string>()
});
break;
}
}
}
else
{
PerformanceCounter perfCounter = new PerformanceCounter(categoryName, counterName,
"", theMac[0].MachineName);
string data = "";
List<UserInfo> currUser = this.GetUserByName(WindowsIdentity.GetCurrent().Name);
string timeStarted = DateTime.Now.ToString("MM/dd/yyyy - h:mm:ss tt");
//string[] dataValues = new string[(int)seconds];
List<string> dataValues = new List<string>();
var hubConnection = new HubConnection("http://localhost/PerfMon2/");
hubConnection.Credentials = CredentialCache.DefaultNetworkCredentials;
var perfMon = hubConnection.CreateProxy("LiveHub");
// perfMon.On("sendValue", message => Console.WriteLine(message));
perfMon.On("showValue", json => Console.WriteLine(json));
hubConnection.Start().Wait();
List<DataValueInfo> lol = new List<DataValueInfo>();
for (int i = 0; i < seconds; i++)
{
data = "Value " + i + ": " + perfCounter.NextValue().ToString();
//dataValues[i] = data;
dataValues.Add(data);
lol.Add(new DataValueInfo
{
Value = perfCounter.NextValue().ToString()
});
// perfMon.Invoke<List<DataValueInfo>>("Send", lol);
perfMon.Invoke("SendToClient", lol);
Thread.Sleep(1000);
}
string timeFinished = DateTime.Now.ToString("MM/dd/yyyy - h:mm:ss tt");
Log log = new Log
{
LogName = logName,
CounterName = perfCounter.CounterName,
InstanceName = perfCounter.InstanceName,
CategoryName = perfCounter.CategoryName,
MachineName = perfCounter.MachineName,
TimeStarted = timeStarted,
TimeFinished = timeFinished,
PerformanceData = string.Join(",", dataValues),
UserID = currUser[0].UserID
};
this.CreateLog(log);
logIt.Add(new LogInfo
{
LogName = logName,
CounterName = perfCounter.CounterName,
InstanceName = perfCounter.InstanceName,
CategoryName = perfCounter.CategoryName,
MachineName = perfCounter.MachineName,
TimeStarted = timeStarted,
TimeFinished = timeFinished,
PerformanceData = dataValues.ToList<string>()
});
}
return logIt;
}
Here is the controller for the method in LogController.cs :
[AcceptVerbs("GET", "POST")]
public List<LogInfo> Log_Perf_Data(string machine_name, string category_name, string counter_name, string instance_name,
string log_name, long? seconds, string live, string enforceQuery)
{
LogController.CheckUser();
// POST api/log/post_data?machine_name=&category_name=&counter_name=&instance_name=&log_name=&seconds=
if (machine_name != null && category_name != null && counter_name != null && log_name != null && seconds.HasValue && enforceQuery == null)
{
List<LogInfo> dataVal = logDB.LogTimedPerfData(machine_name, category_name, counter_name, instance_name,
log_name, live, seconds);
logDB.SaveChanges();
return dataVal;
}
return new List<LogInfo>();
}
Maybe you can implement it in push technique. Here is how I do it:
Class with message
public class Message
{
/// <summary>
/// The name who will receive this message.
/// </summary>
public string RecipientName { get; set; }
/// <summary>
/// The message content.
/// </summary>
public string MessageContent { get; set; }
}
Class that will represent client:
public class Client
{
private ManualResetEvent messageEvent = new ManualResetEvent(false);
private Queue<Message> messageQueue = new Queue<Message>();
/// <summary>
/// This method is called by a sender to send a message to this client.
/// </summary>
/// <param name="message">the new message</param>
public void EnqueueMessage(Message message)
{
lock (messageQueue)
{
messageQueue.Enqueue(message);
// Set a new message event.
messageEvent.Set();
}
}
/// <summary>
/// This method is called by the client to receive messages from the message queue.
/// If no message, it will wait until a new message is inserted.
/// </summary>
/// <returns>the unread message</returns>
public Message DequeueMessage()
{
// Wait until a new message.
messageEvent.WaitOne();
lock (messageQueue)
{
if (messageQueue.Count == 1)
{
messageEvent.Reset();
}
return messageQueue.Dequeue();
}
}
}
Class to send messages to clients:
public class ClientAdapter
{
/// <summary>
/// The recipient list.
/// </summary>
private Dictionary<string, Client> recipients = new Dictionary<string,Client>();
/// <summary>
/// Send a message to a particular recipient.
/// </summary>
public void SendMessage(Message message)
{
if (recipients.ContainsKey(message.RecipientName))
{
Client client = recipients[message.RecipientName];
client.EnqueueMessage(message);
}
}
/// <summary>
/// Called by a individual recipient to wait and receive a message.
/// </summary>
/// <returns>The message content</returns>
public string GetMessage(string userName)
{
string messageContent = string.Empty;
if (recipients.ContainsKey(userName))
{
Client client = recipients[userName];
messageContent = client.DequeueMessage().MessageContent;
}
return messageContent;
}
/// <summary>
/// Join a user to the recipient list.
/// </summary>
public void Join(string userName)
{
recipients[userName] = new Client();
}
/// <summary>
/// Singleton pattern.
/// This pattern will ensure there is only one instance of this class in the system.
/// </summary>
public static ClientAdapter Instance = new ClientAdapter();
private ClientAdapter() { }
}
Sending messages:
Message message = new Message
{
RecipientName = tbRecipientName.Text.Trim(),
MessageContent = tbMessageContent.Text.Trim()
};
if (!string.IsNullOrWhiteSpace(message.RecipientName) && !string.IsNullOrEmpty(message.MessageContent))
{
// Call the client adapter to send the message to the particular recipient instantly.
ClientAdapter.Instance.SendMessage(message);
}
Receive messages (this is JavaScript functions written in test page. They render content of the message on ASPX page. Here you should implement your logic):
// This method will persist a http request and wait for messages.
function waitEvent() {
CSASPNETReverseAJAX.Dispatcher.WaitMessage("<%= Session["userName"] %>",
function (result) {
displayMessage(result);
// Keep looping.
setTimeout(waitEvent, 0);
}, function () {
// Keep looping.
setTimeout(waitEvent, 0);
});
}
// Append a message content to the result panel.
function displayMessage(message) {
var panel = document.getElementById("<%= lbMessages.ClientID %>");
panel.innerHTML += currentTime() + ": " + message + "<br />";
}
// Return a current time string.
function currentTime() {
var currentDate = new Date();
return currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds();
}
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?
Someone wrote the following code.
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily.ToString() == "InterNetwork")
{
localIP = ip.ToString();
}
}
return localIP;
However, I generally distrust the author, and I don't understand this code. Is there a better way to do so?
Nope, that is pretty much the best way to do it. As a machine could have several IP addresses you need to iterate the collection of them to find the proper one.
Edit: The only thing I would change would be to change this:
if (ip.AddressFamily.ToString() == "InterNetwork")
to this:
if (ip.AddressFamily == AddressFamily.InterNetwork)
There is no need to ToString an enumeration for comparison.
The only way to know your public IP is to ask someone else to tell you; this code may help you:
public string GetPublicIP()
{
String direction = "";
WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
using (WebResponse response = request.GetResponse())
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
direction = stream.ReadToEnd();
}
//Search for the ip in the html
int first = direction.IndexOf("Address: ") + 9;
int last = direction.LastIndexOf("</body>");
direction = direction.Substring(first, last - first);
return direction;
}
Cleaner and an all in one solution :D
//This returns the first IP4 address or null
return Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);
If you can't rely on getting your IP address from a DNS server (which has happened to me), you can use the following approach:
The System.Net.NetworkInformation namespace contains a NetworkInterface class, which has a static GetAllNetworkInterfaces method.
This method will return all "network interfaces" on your machine, and there are generally quite a few, even if you only have a wireless adapter and/or an ethernet adapter hardware installed on your machine. All of these network interfaces have valid IP addresses for your local machine, although you probably only want one.
If you're looking for one IP address, then you'll need to filter the list down until you can identify the right address. You will probably need to do some experimentation, but I had success with the following approach:
Filter out any NetworkInterfaces that are inactive by checking for OperationalStatus == OperationalStatus.Up. This will exclude your physical ethernet adapter, for instance, if you don't have a network cable plugged in.
For each NetworkInterface, you can get an IPInterfaceProperties object using the GetIPProperties method, and from an IPInterfaceProperties object you can access the UnicastAddresses property for a list of UnicastIPAddressInformation objects.
Filter out non-preferred unicast addresses by checking for DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred
Filter out "virtual" addresses by checking for AddressPreferredLifetime != UInt32.MaxValue.
At this point I take the address of the first (if any) unicast address that matches all of these filters.
EDIT:
[revised code on May 16, 2018 to include the conditions mentioned in the text above for duplicate address detection state and preferred lifetime]
The sample below demonstrates filtering based on operational status, address family, excluding the loopback address (127.0.0.1), duplicate address detection state, and preferred lifetime.
static IEnumerable<IPAddress> GetLocalIpAddresses()
{
// Get the list of network interfaces for the local computer.
var adapters = NetworkInterface.GetAllNetworkInterfaces();
// Return the list of local IPv4 addresses excluding the local
// host, disconnected, and virtual addresses.
return (from adapter in adapters
let properties = adapter.GetIPProperties()
from address in properties.UnicastAddresses
where adapter.OperationalStatus == OperationalStatus.Up &&
address.Address.AddressFamily == AddressFamily.InterNetwork &&
!address.Equals(IPAddress.Loopback) &&
address.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred &&
address.AddressPreferredLifetime != UInt32.MaxValue
select address.Address);
}
WebClient webClient = new WebClient();
string IP = webClient.DownloadString("http://myip.ozymo.com/");
using System.Net;
string host = Dns.GetHostName();
IPHostEntry ip = Dns.GetHostEntry(host);
Console.WriteLine(ip.AddressList[0].ToString());
Just tested this on my machine and it works.
If you want to avoid using DNS:
List<IPAddress> ipList = new List<IPAddress>();
foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces())
{
foreach (var address in netInterface.GetIPProperties().UnicastAddresses)
{
if (address.Address.AddressFamily == AddressFamily.InterNetwork)
{
Console.WriteLine("found IP " + address.Address.ToString());
ipList.Add(address.Address);
}
}
}
Don't rely on InterNetwork all the time because you can have more than one device which also uses IP4 which would screw up the results in getting your IP.
Now, if you would like you may just copy this and please review it or update it to how you see fit.
First I get the address of the router (gateway)
If it comes back that I am connected to a gateway (which mean not connected directly into the modem wireless or not) then we have our gateway address as IPAddress else we a null pointer IPAddress reference.
Then we need to get the computer's list of IPAddresses. This is where things are not that hard because routers (all routers) use 4 bytes (...). The first three are the most important because any computer connected to it will have the IP4 address matching the first three bytes. Ex: 192.168.0.1 is standard for router default IP unless changed by the adminstrator of it. '192.168.0' or whatever they may be is what we need to match up. And that is all I did in IsAddressOfGateway function.
The reason for the length matching is because not all addresses (which are for the computer only) have the length of 4 bytes. If you type in netstat in the cmd, you will find this to be true. So there you have it. Yes, it takes a little more work to really get what you are looking for. Process of elimination.
And for God's sake, do not find the address by pinging it which takes time because first you are sending the address to be pinged and then it has to send the result back. No, work directly with .Net classes which deal with your system environment and you will get the answers you are looking for when it has to solely do with your computer.
Now if you are directly connected to your modem, the process is almost the same because the modem is your gateway but the submask is not the same because your getting the information directly from your DNS Server via modem and not masked by the router serving up the Internet to you although you still can use the same code because the last byte of the IP assigned to the modem is 1. So if IP sent from the modem which does change is 111.111.111.1' then you will get 111.111.111.(some byte value). Keep in mind the we need to find the gateway information because there are more devices which deal with internet connectivity than your router and modem.
Now you see why you DON'T change your router's first two bytes 192 and 168. These are strictly distinguished for routers only and not internet use or we would have a serious issue with IP Protocol and double pinging resulting in crashing your computer. Image that your assigned router IP is 192.168.44.103 and you click on a site with that IP as well. OMG! Your computer would not know what to ping. Crash right there. To avoid this issue, only routers are assigned these and not for internet usage. So leave the first two bytes of the router alone.
static IPAddress FindLanAddress()
{
IPAddress gateway = FindGetGatewayAddress();
if (gateway == null)
return null;
IPAddress[] pIPAddress = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress address in pIPAddress) {
if (IsAddressOfGateway(address, gateway))
return address;
return null;
}
static bool IsAddressOfGateway(IPAddress address, IPAddress gateway)
{
if (address != null && gateway != null)
return IsAddressOfGateway(address.GetAddressBytes(),gateway.GetAddressBytes());
return false;
}
static bool IsAddressOfGateway(byte[] address, byte[] gateway)
{
if (address != null && gateway != null)
{
int gwLen = gateway.Length;
if (gwLen > 0)
{
if (address.Length == gateway.Length)
{
--gwLen;
int counter = 0;
for (int i = 0; i < gwLen; i++)
{
if (address[i] == gateway[i])
++counter;
}
return (counter == gwLen);
}
}
}
return false;
}
static IPAddress FindGetGatewayAddress()
{
IPGlobalProperties ipGlobProps = IPGlobalProperties.GetIPGlobalProperties();
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
IPInterfaceProperties ipInfProps = ni.GetIPProperties();
foreach (GatewayIPAddressInformation gi in ipInfProps.GatewayAddresses)
return gi.Address;
}
return null;
}
I just thought that I would add my own, one-liner (even though there are many other useful answers already).
string ipAddress = new WebClient().DownloadString("http://icanhazip.com");
For getting the current public IP address, all you need to do is create an ASPX page with the following line on the page load event:
Response.Write(HttpContext.Current.Request.UserHostAddress.ToString());
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());
namespace NKUtilities
{
using System;
using System.Net;
using System.Net.Sockets;
public class DNSUtility
{
public static int Main(string [] args)
{
string strHostName = "";
try {
if(args.Length == 0)
{
// Getting Ip address of local machine...
// First get the host name of local machine.
strHostName = Dns.GetHostName();
Console.WriteLine ("Local Machine's Host Name: " + strHostName);
}
else
{
// Otherwise, get the IP address of the host provided on the command line.
strHostName = args[0];
}
// Then using host name, get the IP address list..
IPHostEntry ipEntry = Dns.GetHostEntry (strHostName);
IPAddress [] addr = ipEntry.AddressList;
for(int i = 0; i < addr.Length; i++)
{
Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
}
return 0;
}
catch(SocketException se)
{
Console.WriteLine("{0} ({1})", se.Message, strHostName);
return -1;
}
catch(Exception ex)
{
Console.WriteLine("Error: {0}.", ex.Message);
return -1;
}
}
}
}
Look here for details.
You have to remember your computer can have more than one IP (actually it always does) - so which one are you after.
Try this:
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
String MyIp = localIPs[0].ToString();
Maybe by external IP you can consider (if you are in a Web server context) using this
Request.ServerVariables["LOCAL_ADDR"];
I was asking the same question as you and I found it in this stackoverflow article.
It worked for me.
namespace NKUtilities
{
using System;
using System.Net;
public class DNSUtility
{
public static int Main (string [] args)
{
String strHostName = new String ("");
if (args.Length == 0)
{
// Getting Ip address of local machine...
// First get the host name of local machine.
strHostName = Dns.GetHostName ();
Console.WriteLine ("Local Machine's Host Name: " + strHostName);
}
else
{
strHostName = args[0];
}
// Then using host name, get the IP address list..
IPHostEntry ipEntry = DNS.GetHostByName (strHostName);
IPAddress [] addr = ipEntry.AddressList;
for (int i = 0; i < addr.Length; i++)
{
Console.WriteLine ("IP Address {0}: {1} ", i, addr[i].ToString ());
}
return 0;
}
}
}
using System;
using System.Net;
namespace IPADDRESS
{
class Program
{
static void Main(string[] args)
{
String strHostName = string.Empty;
if (args.Length == 0)
{
/* First get the host name of local machine.*/
strHostName = Dns.GetHostName();
Console.WriteLine("Local Machine's Host Name: " + strHostName);
}
else
{
strHostName = args[0];
}
/* Then using host name, get the IP address list..*/
IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
IPAddress[] addr = ipEntry.AddressList;
for (int i = 0; i < addr.Length; i++)
{
Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
}
Console.ReadLine();
}
}
}
return Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);
Simple single line of code that returns the first internal IPV4 address or null if there are none. Added as a comment above, but may be useful to someone (some solutions above will return multiple addresses that need further filtering).
It's also easy to return loopback instead of null I guess with:
return Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork) ?? new IPAddress( new byte[] {127, 0, 0, 1} );
To find IP address list I have used this solution
public static IEnumerable<string> GetAddresses()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
return (from ip in host.AddressList where ip.AddressFamily == AddressFamily.lo select ip.ToString()).ToList();
}
But I personally like below solution to get local valid IP address
public static IPAddress GetIPAddress(string hostName)
{
Ping ping = new Ping();
var replay = ping.Send(hostName);
if (replay.Status == IPStatus.Success)
{
return replay.Address;
}
return null;
}
public static void Main()
{
Console.WriteLine("Local IP Address: " + GetIPAddress(Dns.GetHostName()));
Console.WriteLine("Google IP:" + GetIPAddress("google.com");
Console.ReadLine();
}
The LINQ solution:
Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork).Select(ip => ip.ToString()).FirstOrDefault() ?? ""
Here is how i solved it. i know if you have several physical interfaces this might not select the exact eth you want.
private string FetchIP()
{
//Get all IP registered
List<string> IPList = new List<string>();
IPHostEntry host;
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
IPList.Add(ip.ToString());
}
}
//Find the first IP which is not only local
foreach (string a in IPList)
{
Ping p = new Ping();
string[] b = a.Split('.');
string ip2 = b[0] + "." + b[1] + "." + b[2] + ".1";
PingReply t = p.Send(ip2);
p.Dispose();
if (t.Status == IPStatus.Success && ip2 != a)
{
return a;
}
}
return null;
}
The question doesn't say ASP.NET MVC but I'm just leaving this here anyway:
Request.UserHostAddress
Get all IP addresses as strings using LINQ:
using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
...
string[] allIpAddresses = NetworkInterface.GetAllNetworkInterfaces()
.SelectMany(c=>c.GetIPProperties().UnicastAddresses
.Where(d=>d.Address.AddressFamily == AddressFamily.InterNetwork)
.Select(d=>d.Address.ToString())
).ToArray();
TO FILTER OUT PRIVATE ONES...
First, define an extension method IsPrivate():
public static class IPAddressExtensions
{
// Collection of private CIDRs (IpAddress/Mask)
private static Tuple<int, int>[] _privateCidrs = new []{"10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"}
.Select(c=>Tuple.Create(BitConverter.ToInt32(IPAddress
.Parse(c.Split('/')[0]).GetAddressBytes(), 0)
, IPAddress.HostToNetworkOrder(-1 << (32-int.Parse(c.Split('/')[1])))))
.ToArray();
public static bool IsPrivate(this IPAddress ipAddress)
{
int ip = BitConverter.ToInt32(ipAddress.GetAddressBytes(), 0);
return _privateCidrs.Any(cidr=>(ip & cidr.Item2)==(cidr.Item1 & cidr.Item2));
}
}
... And then use it to filter out private IPs:
string[] publicIpAddresses = NetworkInterface.GetAllNetworkInterfaces()
.SelectMany(c=>c.GetIPProperties().UnicastAddresses
.Where(d=>d.Address.AddressFamily == AddressFamily.InterNetwork
&& !d.Address.IsPrivate() // Filter out private ones
)
.Select(d=>d.Address.ToString())
).ToArray();
It works for me... and should be faster in most case (if not all) than querying a DNS server. Thanks to Dr. Wily's Apprentice (here).
// ************************************************************************
/// <summary>
/// Will search for the an active NetworkInterafce that has a Gateway, otherwise
/// it will fallback to try from the DNS which is not safe.
/// </summary>
/// <returns></returns>
public static NetworkInterface GetMainNetworkInterface()
{
List<NetworkInterface> candidates = new List<NetworkInterface>();
if (NetworkInterface.GetIsNetworkAvailable())
{
NetworkInterface[] NetworkInterfaces =
NetworkInterface.GetAllNetworkInterfaces();
foreach (
NetworkInterface ni in NetworkInterfaces)
{
if (ni.OperationalStatus == OperationalStatus.Up)
candidates.Add(ni);
}
}
if (candidates.Count == 1)
{
return candidates[0];
}
// Accoring to our tech, the main NetworkInterface should have a Gateway
// and it should be the ony one with a gateway.
if (candidates.Count > 1)
{
for (int n = candidates.Count - 1; n >= 0; n--)
{
if (candidates[n].GetIPProperties().GatewayAddresses.Count == 0)
{
candidates.RemoveAt(n);
}
}
if (candidates.Count == 1)
{
return candidates[0];
}
}
// Fallback to try by getting my ipAdress from the dns
IPAddress myMainIpAdress = null;
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork) // Get the first IpV4
{
myMainIpAdress = ip;
break;
}
}
if (myMainIpAdress != null)
{
NetworkInterface[] NetworkInterfaces =
NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface ni in NetworkInterfaces)
{
if (ni.OperationalStatus == OperationalStatus.Up)
{
IPInterfaceProperties props = ni.GetIPProperties();
foreach (UnicastIPAddressInformation ai in props.UnicastAddresses)
{
if (ai.Address.Equals(myMainIpAdress))
{
return ni;
}
}
}
}
}
return null;
}
// ******************************************************************
/// <summary>
/// AddressFamily.InterNetwork = IPv4
/// Thanks to Dr. Wilys Apprentice at
/// http://stackoverflow.com/questions/1069103/how-to-get-the-ip-address-of-the-server-on-which-my-c-sharp-application-is-runni
/// using System.Net.NetworkInformation;
/// </summary>
/// <param name="mac"></param>
/// <param name="addressFamily">AddressFamily.InterNetwork = IPv4, AddressFamily.InterNetworkV6 = IPv6</param>
/// <returns></returns>
public static IPAddress GetIpFromMac(PhysicalAddress mac, AddressFamily addressFamily = AddressFamily.InterNetwork)
{
NetworkInterface[] NetworkInterfaces =
NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface ni in NetworkInterfaces)
{
if (ni.GetPhysicalAddress().Equals(mac))
{
if (ni.OperationalStatus == OperationalStatus.Up)
{
IPInterfaceProperties props = ni.GetIPProperties();
foreach (UnicastIPAddressInformation ai in props.UnicastAddresses)
{
if (ai.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred)
{
if (ai.Address.AddressFamily == addressFamily)
{
return ai.Address;
}
}
}
}
}
}
return null;
}
// ******************************************************************
/// <summary>
/// Return the best guess of main ipAdress. To get it in the form aaa.bbb.ccc.ddd just call
/// '?.ToString() ?? ""' on the result.
/// </summary>
/// <returns></returns>
public static IPAddress GetMyInternetIpAddress()
{
NetworkInterface ni = GetMainNetworkInterface();
IPAddress ipAddress = GetIpFromMac(ni.GetPhysicalAddress());
if (ipAddress == null) // could it be possible ?
{
ipAddress = GetIpFromMac(ni.GetPhysicalAddress(), AddressFamily.InterNetworkV6);
}
return ipAddress;
}
// ******************************************************************
Just as reference this is the full class code where I defined it:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace TcpMonitor
{
/*
Usage:
var cons = TcpHelper.GetAllTCPConnections();
foreach (TcpHelper.MIB_TCPROW_OWNER_PID c in cons) ...
*/
public class NetHelper
{
[DllImport("iphlpapi.dll", SetLastError = true)]
static extern uint GetExtendedUdpTable(IntPtr pUdpTable, ref int dwOutBufLen, bool sort, int ipVersion, UDP_TABLE_CLASS tblClass, uint reserved = 0);
public enum UDP_TABLE_CLASS
{
UDP_TABLE_BASIC,
UDP_TABLE_OWNER_PID,
UDP_TABLE_OWNER_MODULE
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_UDPTABLE_OWNER_PID
{
public uint dwNumEntries;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 1)]
public MIB_UDPROW_OWNER_PID[] table;
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_UDPROW_OWNER_PID
{
public uint localAddr;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] localPort;
public uint owningPid;
public uint ProcessId
{
get { return owningPid; }
}
public IPAddress LocalAddress
{
get { return new IPAddress(localAddr); }
}
public ushort LocalPort
{
get { return BitConverter.ToUInt16(localPort.Take(2).Reverse().ToArray(), 0); }
}
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_UDP6TABLE_OWNER_PID
{
public uint dwNumEntries;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 1)]
public MIB_UDP6ROW_OWNER_PID[] table;
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_UDP6ROW_OWNER_PID
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public byte[] localAddr;
public uint localScopeId;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] localPort;
public uint owningPid;
public uint ProcessId
{
get { return owningPid; }
}
public IPAddress LocalAddress
{
get { return new IPAddress(localAddr, localScopeId); }
}
public ushort LocalPort
{
get { return BitConverter.ToUInt16(localPort.Take(2).Reverse().ToArray(), 0); }
}
}
public static List<MIB_UDPROW_OWNER_PID> GetAllUDPConnections()
{
return GetUDPConnections<MIB_UDPROW_OWNER_PID, MIB_UDPTABLE_OWNER_PID> (AF_INET);
}
public static List<MIB_UDP6ROW_OWNER_PID> GetAllUDPv6Connections()
{
return GetUDPConnections<MIB_UDP6ROW_OWNER_PID, MIB_UDP6TABLE_OWNER_PID>(AF_INET6);
}
private static List<IPR> GetUDPConnections<IPR, IPT>(int ipVersion)//IPR = Row Type, IPT = Table Type
{
List<IPR> result = null;
IPR[] tableRows = null;
int buffSize = 0;
var dwNumEntriesField = typeof(IPT).GetField("dwNumEntries");
// how much memory do we need?
uint ret = GetExtendedUdpTable(IntPtr.Zero, ref buffSize, true, ipVersion, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID);
IntPtr udpTablePtr = Marshal.AllocHGlobal(buffSize);
try
{
ret = GetExtendedUdpTable(udpTablePtr, ref buffSize, true, ipVersion, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID);
if (ret != 0)
return new List<IPR>();
// get the number of entries in the table
IPT table = (IPT)Marshal.PtrToStructure(udpTablePtr, typeof(IPT));
int rowStructSize = Marshal.SizeOf(typeof(IPR));
uint numEntries = (uint)dwNumEntriesField.GetValue(table);
// buffer we will be returning
tableRows = new IPR[numEntries];
IntPtr rowPtr = (IntPtr)((long)udpTablePtr + 4);
for (int i = 0; i < numEntries; i++)
{
IPR tcpRow = (IPR)Marshal.PtrToStructure(rowPtr, typeof(IPR));
tableRows[i] = tcpRow;
rowPtr = (IntPtr)((long)rowPtr + rowStructSize); // next entry
}
}
finally
{
result = tableRows?.ToList() ?? new List<IPR>();
// Free the Memory
Marshal.FreeHGlobal(udpTablePtr);
}
return result;
}
[DllImport("iphlpapi.dll", SetLastError = true)]
static extern uint GetExtendedTcpTable(IntPtr pTcpTable, ref int dwOutBufLen, bool sort, int ipVersion, TCP_TABLE_CLASS tblClass, uint reserved = 0);
public enum MIB_TCP_STATE
{
MIB_TCP_STATE_CLOSED = 1,
MIB_TCP_STATE_LISTEN = 2,
MIB_TCP_STATE_SYN_SENT = 3,
MIB_TCP_STATE_SYN_RCVD = 4,
MIB_TCP_STATE_ESTAB = 5,
MIB_TCP_STATE_FIN_WAIT1 = 6,
MIB_TCP_STATE_FIN_WAIT2 = 7,
MIB_TCP_STATE_CLOSE_WAIT = 8,
MIB_TCP_STATE_CLOSING = 9,
MIB_TCP_STATE_LAST_ACK = 10,
MIB_TCP_STATE_TIME_WAIT = 11,
MIB_TCP_STATE_DELETE_TCB = 12
}
public enum TCP_TABLE_CLASS
{
TCP_TABLE_BASIC_LISTENER,
TCP_TABLE_BASIC_CONNECTIONS,
TCP_TABLE_BASIC_ALL,
TCP_TABLE_OWNER_PID_LISTENER,
TCP_TABLE_OWNER_PID_CONNECTIONS,
TCP_TABLE_OWNER_PID_ALL,
TCP_TABLE_OWNER_MODULE_LISTENER,
TCP_TABLE_OWNER_MODULE_CONNECTIONS,
TCP_TABLE_OWNER_MODULE_ALL
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_TCPTABLE_OWNER_PID
{
public uint dwNumEntries;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 1)]
public MIB_TCPROW_OWNER_PID[] table;
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_TCP6TABLE_OWNER_PID
{
public uint dwNumEntries;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 1)]
public MIB_TCP6ROW_OWNER_PID[] table;
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_TCPROW_OWNER_PID
{
public uint state;
public uint localAddr;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] localPort;
public uint remoteAddr;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] remotePort;
public uint owningPid;
public uint ProcessId
{
get { return owningPid; }
}
public IPAddress LocalAddress
{
get { return new IPAddress(localAddr); }
}
public ushort LocalPort
{
get
{
return BitConverter.ToUInt16(new byte[2] { localPort[1], localPort[0] }, 0);
}
}
public IPAddress RemoteAddress
{
get { return new IPAddress(remoteAddr); }
}
public ushort RemotePort
{
get
{
return BitConverter.ToUInt16(new byte[2] { remotePort[1], remotePort[0] }, 0);
}
}
public MIB_TCP_STATE State
{
get { return (MIB_TCP_STATE)state; }
}
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_TCP6ROW_OWNER_PID
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public byte[] localAddr;
public uint localScopeId;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] localPort;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public byte[] remoteAddr;
public uint remoteScopeId;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] remotePort;
public uint state;
public uint owningPid;
public uint ProcessId
{
get { return owningPid; }
}
public long LocalScopeId
{
get { return localScopeId; }
}
public IPAddress LocalAddress
{
get { return new IPAddress(localAddr, LocalScopeId); }
}
public ushort LocalPort
{
get { return BitConverter.ToUInt16(localPort.Take(2).Reverse().ToArray(), 0); }
}
public long RemoteScopeId
{
get { return remoteScopeId; }
}
public IPAddress RemoteAddress
{
get { return new IPAddress(remoteAddr, RemoteScopeId); }
}
public ushort RemotePort
{
get { return BitConverter.ToUInt16(remotePort.Take(2).Reverse().ToArray(), 0); }
}
public MIB_TCP_STATE State
{
get { return (MIB_TCP_STATE)state; }
}
}
public const int AF_INET = 2; // IP_v4 = System.Net.Sockets.AddressFamily.InterNetwork
public const int AF_INET6 = 23; // IP_v6 = System.Net.Sockets.AddressFamily.InterNetworkV6
public static Task<List<MIB_TCPROW_OWNER_PID>> GetAllTCPConnectionsAsync()
{
return Task.Run(() => GetTCPConnections<MIB_TCPROW_OWNER_PID, MIB_TCPTABLE_OWNER_PID>(AF_INET));
}
public static List<MIB_TCPROW_OWNER_PID> GetAllTCPConnections()
{
return GetTCPConnections<MIB_TCPROW_OWNER_PID, MIB_TCPTABLE_OWNER_PID>(AF_INET);
}
public static Task<List<MIB_TCP6ROW_OWNER_PID>> GetAllTCPv6ConnectionsAsync()
{
return Task.Run(()=>GetTCPConnections<MIB_TCP6ROW_OWNER_PID, MIB_TCP6TABLE_OWNER_PID>(AF_INET6));
}
public static List<MIB_TCP6ROW_OWNER_PID> GetAllTCPv6Connections()
{
return GetTCPConnections<MIB_TCP6ROW_OWNER_PID, MIB_TCP6TABLE_OWNER_PID>(AF_INET6);
}
private static List<IPR> GetTCPConnections<IPR, IPT>(int ipVersion)//IPR = Row Type, IPT = Table Type
{
List<IPR> result = null;
IPR[] tableRows = null;
int buffSize = 0;
var dwNumEntriesField = typeof(IPT).GetField("dwNumEntries");
// how much memory do we need?
uint ret = GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, ipVersion, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);
IntPtr tcpTablePtr = Marshal.AllocHGlobal(buffSize);
try
{
ret = GetExtendedTcpTable(tcpTablePtr, ref buffSize, true, ipVersion, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);
if (ret != 0)
return new List<IPR>();
// get the number of entries in the table
IPT table = (IPT)Marshal.PtrToStructure(tcpTablePtr, typeof(IPT));
int rowStructSize = Marshal.SizeOf(typeof(IPR));
uint numEntries = (uint)dwNumEntriesField.GetValue(table);
// buffer we will be returning
tableRows = new IPR[numEntries];
IntPtr rowPtr = (IntPtr)((long)tcpTablePtr + 4);
for (int i = 0; i < numEntries; i++)
{
IPR tcpRow = (IPR)Marshal.PtrToStructure(rowPtr, typeof(IPR));
tableRows[i] = tcpRow;
rowPtr = (IntPtr)((long)rowPtr + rowStructSize); // next entry
}
}
finally
{
result = tableRows?.ToList() ?? new List<IPR>();
// Free the Memory
Marshal.FreeHGlobal(tcpTablePtr);
}
return result;
}
public static string GetTcpStateName(MIB_TCP_STATE state)
{
switch (state)
{
case MIB_TCP_STATE.MIB_TCP_STATE_CLOSED:
return "Closed";
case MIB_TCP_STATE.MIB_TCP_STATE_LISTEN:
return "Listen";
case MIB_TCP_STATE.MIB_TCP_STATE_SYN_SENT:
return "SynSent";
case MIB_TCP_STATE.MIB_TCP_STATE_SYN_RCVD:
return "SynReceived";
case MIB_TCP_STATE.MIB_TCP_STATE_ESTAB:
return "Established";
case MIB_TCP_STATE.MIB_TCP_STATE_FIN_WAIT1:
return "FinWait 1";
case MIB_TCP_STATE.MIB_TCP_STATE_FIN_WAIT2:
return "FinWait 2";
case MIB_TCP_STATE.MIB_TCP_STATE_CLOSE_WAIT:
return "CloseWait";
case MIB_TCP_STATE.MIB_TCP_STATE_CLOSING:
return "Closing";
case MIB_TCP_STATE.MIB_TCP_STATE_LAST_ACK:
return "LastAck";
case MIB_TCP_STATE.MIB_TCP_STATE_TIME_WAIT:
return "TimeWait";
case MIB_TCP_STATE.MIB_TCP_STATE_DELETE_TCB:
return "DeleteTCB";
default:
return ((int)state).ToString();
}
}
private static readonly ConcurrentDictionary<string, string> DicOfIpToHostName = new ConcurrentDictionary<string, string>();
public const string UnknownHostName = "Unknown";
// ******************************************************************
public static string GetHostName(IPAddress ipAddress)
{
return GetHostName(ipAddress.ToString());
}
// ******************************************************************
public static string GetHostName(string ipAddress)
{
string hostName = null;
if (!DicOfIpToHostName.TryGetValue(ipAddress, out hostName))
{
try
{
if (ipAddress == "0.0.0.0" || ipAddress == "::")
{
hostName = ipAddress;
}
else
{
hostName = Dns.GetHostEntry(ipAddress).HostName;
}
}
catch (Exception ex)
{
Debug.Print(ex.ToString());
hostName = UnknownHostName;
}
DicOfIpToHostName[ipAddress] = hostName;
}
return hostName;
}
// ************************************************************************
/// <summary>
/// Will search for the an active NetworkInterafce that has a Gateway, otherwise
/// it will fallback to try from the DNS which is not safe.
/// </summary>
/// <returns></returns>
public static NetworkInterface GetMainNetworkInterface()
{
List<NetworkInterface> candidates = new List<NetworkInterface>();
if (NetworkInterface.GetIsNetworkAvailable())
{
NetworkInterface[] NetworkInterfaces =
NetworkInterface.GetAllNetworkInterfaces();
foreach (
NetworkInterface ni in NetworkInterfaces)
{
if (ni.OperationalStatus == OperationalStatus.Up)
candidates.Add(ni);
}
}
if (candidates.Count == 1)
{
return candidates[0];
}
// Accoring to our tech, the main NetworkInterface should have a Gateway
// and it should be the ony one with a gateway.
if (candidates.Count > 1)
{
for (int n = candidates.Count - 1; n >= 0; n--)
{
if (candidates[n].GetIPProperties().GatewayAddresses.Count == 0)
{
candidates.RemoveAt(n);
}
}
if (candidates.Count == 1)
{
return candidates[0];
}
}
// Fallback to try by getting my ipAdress from the dns
IPAddress myMainIpAdress = null;
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork) // Get the first IpV4
{
myMainIpAdress = ip;
break;
}
}
if (myMainIpAdress != null)
{
NetworkInterface[] NetworkInterfaces =
NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface ni in NetworkInterfaces)
{
if (ni.OperationalStatus == OperationalStatus.Up)
{
IPInterfaceProperties props = ni.GetIPProperties();
foreach (UnicastIPAddressInformation ai in props.UnicastAddresses)
{
if (ai.Address.Equals(myMainIpAdress))
{
return ni;
}
}
}
}
}
return null;
}
// ******************************************************************
/// <summary>
/// AddressFamily.InterNetwork = IPv4
/// Thanks to Dr. Wilys Apprentice at
/// http://stackoverflow.com/questions/1069103/how-to-get-the-ip-address-of-the-server-on-which-my-c-sharp-application-is-runni
/// using System.Net.NetworkInformation;
/// </summary>
/// <param name="mac"></param>
/// <param name="addressFamily">AddressFamily.InterNetwork = IPv4, AddressFamily.InterNetworkV6 = IPv6</param>
/// <returns></returns>
public static IPAddress GetIpFromMac(PhysicalAddress mac, AddressFamily addressFamily = AddressFamily.InterNetwork)
{
NetworkInterface[] NetworkInterfaces =
NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface ni in NetworkInterfaces)
{
if (ni.GetPhysicalAddress().Equals(mac))
{
if (ni.OperationalStatus == OperationalStatus.Up)
{
IPInterfaceProperties props = ni.GetIPProperties();
foreach (UnicastIPAddressInformation ai in props.UnicastAddresses)
{
if (ai.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred)
{
if (ai.Address.AddressFamily == addressFamily)
{
return ai.Address;
}
}
}
}
}
}
return null;
}
// ******************************************************************
/// <summary>
/// Return the best guess of main ipAdress. To get it in the form aaa.bbb.ccc.ddd just call
/// '?.ToString() ?? ""' on the result.
/// </summary>
/// <returns></returns>
public static IPAddress GetMyInternetIpAddress()
{
NetworkInterface ni = GetMainNetworkInterface();
IPAddress ipAddress = GetIpFromMac(ni.GetPhysicalAddress());
if (ipAddress == null) // could it be possible ?
{
ipAddress = GetIpFromMac(ni.GetPhysicalAddress(), AddressFamily.InterNetworkV6);
}
return ipAddress;
}
// ******************************************************************
public static bool IsBroadcastAddress(IPAddress ipAddress)
{
if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
{
return ipAddress.GetAddressBytes()[3] == 255;
}
if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
{
return false; // NO broadcast in IPv6
}
return false;
}
// ******************************************************************
public static bool IsMulticastAddress(IPAddress ipAddress)
{
if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
{
// Source: https://technet.microsoft.com/en-us/library/cc772041(v=ws.10).aspx
return ipAddress.GetAddressBytes()[0] >= 224 && ipAddress.GetAddressBytes()[0] <= 239;
}
if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
{
return ipAddress.IsIPv6Multicast;
}
return false;
}
// ******************************************************************
}
}
Yet another way to get your public IP address is to use OpenDNS's resolve1.opendns.com server with myip.opendns.com as the request.
On the command line this is:
nslookup myip.opendns.com resolver1.opendns.com
Or in C# using the DNSClient nuget:
var lookup = new LookupClient(new IPAddress(new byte[] { 208, 67, 222, 222 }));
var result = lookup.Query("myip.opendns.com", QueryType.ANY);
This is a bit cleaner than hitting http endpoints and parsing responses.
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
To get the remote ip address the quickest way possible. You must have to use a downloader, or create a server on your computer.
The downsides to using this simple code: (which is recommended) is that it will take 3-5 seconds to get your Remote IP Address because the WebClient when initialized always takes 3-5 seconds to check for your proxy settings.
public static string GetIP()
{
string externalIP = "";
externalIP = new WebClient().DownloadString("http://checkip.dyndns.org/");
externalIP = (new Regex(#"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
.Matches(externalIP)[0].ToString();
return externalIP;
}
Here is how I fixed it.. (first time still takes 3-5 seconds) but after that it will always get your Remote IP Address in 0-2 seconds depending on your connection.
public static WebClient webclient = new WebClient();
public static string GetIP()
{
string externalIP = "";
externalIP = webclient.DownloadString("http://checkip.dyndns.org/");
externalIP = (new Regex(#"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
.Matches(externalIP)[0].ToString();
return externalIP;
}
private static string GetLocalIpAdresse()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach(var ip in host.AddressList)
{
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception ("No network adapters with an IPv4 address in the system");
}