// If argument contains a "/" we assume it is on the form: subnet-address/subnet-mask // In that case we loop over all interfaces and take the first one that matches // i.e. the one whos interface address is on the subnet public static string DoSubnetTranslation(string ip) { int index = ip.IndexOf('/'); if (index < 0) { return(ip); } string subnetIp = ip.Substring(0, index); string subnetMask = ip.Substring(index + 1); byte[] mask = System.Net.IPAddress.Parse(subnetMask).GetAddressBytes(); System.Net.NetworkInformation.IPGlobalProperties computerProperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties(); System.Net.NetworkInformation.NetworkInterface[] nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); if (nics != null && nics.Length > 0) { foreach (System.Net.NetworkInformation.NetworkInterface adapter in nics) { System.Net.NetworkInformation.IPInterfaceProperties properties = adapter.GetIPProperties(); System.Net.NetworkInformation.UnicastIPAddressInformationCollection uniCast = properties.UnicastAddresses; if (uniCast == null) { continue; } foreach (System.Net.NetworkInformation.UnicastIPAddressInformation uni in uniCast) { if (uni.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) //IPV4 { byte[] addr = uni.Address.GetAddressBytes(); for (int j = 0; j < addr.Length; j++) { addr[j] = (byte)((int)addr[j] & (int)mask[j]); } string Subnet = new System.Net.IPAddress(addr).ToString(); if (Subnet.Equals(subnetIp)) { return(uni.Address.ToString()); } } } } } return(subnetIp); //// This only works on Vista and later //System.Net.NetworkInformation.IPGlobalProperties gp = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties(); //System.Net.NetworkInformation.UnicastIPAddressInformationCollection x = gp.GetUnicastAddresses(); //for (int i = 0; i < x.Count; i++) //{ // if (x[i].Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) //IPV4 // { // byte[] addr = x[i].Address.GetAddressBytes(); // byte[] mask = x[i].IPv4Mask.GetAddressBytes(); // for (int j = 0; j < addr.Length; j++) addr[j] = (byte)((int)addr[j] & (int)mask[j]); // string Subnet = new System.Net.IPAddress(addr).ToString(); // if (Subnet.Equals(subnetIp)) // { // return x[i].Address.ToString(); // } // } //} //return subnetIp; }
// If argument contains a "/" we assume it is on the form: subnet-address/subnet-mask // e.g "192.168.10.0/255.255.255.0" or "192.168.10.0/24" // In that case we loop over all interfaces and take the first one that matches // i.e. the one whos interface address is on the subnet public static string DoSubnetTranslation(string ip) { int index = ip.IndexOf('/'); if (index < 0) { return(ip); } string subnetIp = ip.Substring(0, index); string subnetMask = ip.Substring(index + 1); byte[] bip = System.Net.IPAddress.Parse(subnetIp).GetAddressBytes(); byte[] bmask; if (subnetMask.Length <= 2) { // Expand to the number of bits given int numBits = int.Parse(subnetMask); long binMask = (((1 << numBits) - 1) << (32 - numBits)) & 0xFFFFFFFF; bmask = new byte[4]; bmask[0] = (byte)((binMask >> 24) & 0xFF); bmask[1] = (byte)((binMask >> 16) & 0xFF); bmask[2] = (byte)((binMask >> 8) & 0xFF); bmask[3] = (byte)((binMask) & 0xFF); } else { bmask = System.Net.IPAddress.Parse(subnetMask).GetAddressBytes(); } for (int j = 0; j < bip.Length; j++) { bip[j] = (byte)((int)bip[j] & (int)bmask[j]); } // System.Net.NetworkInformation.IPGlobalProperties computerProperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties(); System.Net.NetworkInformation.NetworkInterface[] nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); if (nics != null && nics.Length > 0) { foreach (System.Net.NetworkInformation.NetworkInterface adapter in nics) { System.Net.NetworkInformation.IPInterfaceProperties properties = adapter.GetIPProperties(); System.Net.NetworkInformation.UnicastIPAddressInformationCollection uniCast = properties.UnicastAddresses; if (uniCast == null) { continue; } foreach (System.Net.NetworkInformation.UnicastIPAddressInformation uni in uniCast) { if (uni.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) //IPV4 { byte[] addr = uni.Address.GetAddressBytes(); for (int j = 0; j < addr.Length; j++) { addr[j] = (byte)((int)addr[j] & (int)bmask[j]); } bool eq = true; for (int j = 0; j < addr.Length; j++) { eq = eq & (addr[j] == bip[j]); } if (eq) { return(uni.Address.ToString()); } } } } } return(subnetIp); //// This only works on Vista and later //System.Net.NetworkInformation.IPGlobalProperties gp = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties(); //System.Net.NetworkInformation.UnicastIPAddressInformationCollection x = gp.GetUnicastAddresses(); //for (int i = 0; i < x.Count; i++) //{ // if (x[i].Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) //IPV4 // { // byte[] addr = x[i].Address.GetAddressBytes(); // byte[] mask = x[i].IPv4Mask.GetAddressBytes(); // for (int j = 0; j < addr.Length; j++) addr[j] = (byte)((int)addr[j] & (int)mask[j]); // string Subnet = new System.Net.IPAddress(addr).ToString(); // if (Subnet.Equals(subnetIp)) // { // return x[i].Address.ToString(); // } // } //} //return subnetIp; }
/// <summary> /// 从网卡获取ip设置信息 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public static string GetNetWorkIPAddress() { System.Net.NetworkInformation.NetworkInterface[] nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); foreach (System.Net.NetworkInformation.NetworkInterface adapter in nics) { bool Pd1 = (adapter.NetworkInterfaceType == System.Net.NetworkInformation.NetworkInterfaceType.Ethernet); //判断是否是以太网连接 if (Pd1) { System.Net.NetworkInformation.IPInterfaceProperties ip = adapter.GetIPProperties(); //IP配置信息 //获取单播地址集 System.Net.NetworkInformation.UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses; var ipv4 = ipCollection.Where(w => w.Address.AddressFamily == AddressFamily.InterNetwork).FirstOrDefault(); if (ipv4 != null) { return(ipv4.Address.ToString()); } else { return(ipCollection.Where(w => w.Address.AddressFamily == AddressFamily.InterNetworkV6).FirstOrDefault().Address.ToString()); } ////未获取到ipv4 //if (ip.UnicastAddresses.Count > 0) //{ // //ipv6 地址优先 // return ip.UnicastAddresses[0].Address.ToString();//IP地址 //} //if (ip.GatewayAddresses.Count > 0) //{ // txtGateWay.Text = ip.GatewayAddresses[0].Address.ToString();//默认网关 //} //int DnsCount = ip.DnsAddresses.Count; //Console.WriteLine("DNS服务器地址:"); //if (DnsCount > 0) //{ // try // { // txtDNS1.Text = ip.DnsAddresses[0].ToString(); //主DNS // txtDNS2.Text = ip.DnsAddresses[1].ToString(); //备用DNS地址 // } // catch (Exception er) // { // throw er; // } //} } } return("127.0.0.1"); }
public static bool IsMyNodeAddress(String addr) { try { InetAddress nodeaddr = new InetAddress(addr); if (nodeaddr.IsAnyLocalAddress()) { return(true); } System.Net.NetworkInformation.NetworkInterface[] nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); if (nics != null && nics.Length > 0) { foreach (System.Net.NetworkInformation.NetworkInterface adapter in nics) { System.Net.NetworkInformation.IPInterfaceProperties properties = adapter.GetIPProperties(); System.Net.NetworkInformation.UnicastIPAddressInformationCollection uniCast = properties.UnicastAddresses; if (uniCast == null) { continue; } foreach (System.Net.NetworkInformation.UnicastIPAddressInformation uni in uniCast) { if (uni.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) //IPV4 { if (nodeaddr.Equals(uni.Address)) { return(true); } } } } } return(false); } catch { return(false); } }
private void SearchNetworkForWebServers(Dictionary <string, string> WebServiceURLs) { Cursor.Current = Cursors.WaitCursor; string origMessage = ux_textboxLoginMessage.Text; ux_textboxLoginMessage.Text = "Scanning..."; ux_progressbarScanning.Step = 1; ux_progressbarScanning.Minimum = 0; ux_progressbarScanning.Maximum = 255; ux_progressbarScanning.Value = 1; ux_progressbarScanning.Show(); System.Web.Services.Discovery.DiscoveryClientProtocol dcp = new System.Web.Services.Discovery.DiscoveryClientProtocol(); dcp.Timeout = 1000; // Search for active servers hosting the GRIN-Global web services... // Try the localhost first... try { ux_textboxLoginMessage.Text = "Scanning localhost..."; ux_textboxLoginMessage.Update(); dcp.Discover("http://localhost/GRINGlobal/GUI.asmx"); WebServiceURLs.Add("localhost", "http://localhost/GRINGlobal/GUI.asmx"); } catch { // Silently fail... } // Now scan the class D subnet for all available ethernet adapters... System.Net.NetworkInformation.NetworkInterface[] adapters = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); foreach (System.Net.NetworkInformation.NetworkInterface adapter in adapters) { if (adapter.NetworkInterfaceType == System.Net.NetworkInformation.NetworkInterfaceType.Ethernet && adapter.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up) { System.Net.NetworkInformation.IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); System.Net.NetworkInformation.UnicastIPAddressInformationCollection adapterAddresses = adapterProperties.UnicastAddresses; foreach (System.Net.NetworkInformation.IPAddressInformation addressInfo in adapterAddresses) { DateTime dtStart = DateTime.Now; string addrPrefix = addressInfo.Address.ToString().Substring(0, addressInfo.Address.ToString().LastIndexOf('.')); string ipAddress = addrPrefix + ".1"; string webServiceURL = "http://" + ipAddress + "/GRINGlobal/GUI.asmx"; string serverName = System.Net.Dns.GetHostEntry(ipAddress).HostName; System.Web.Services.Discovery.DiscoveryDocument dd = new System.Web.Services.Discovery.DiscoveryDocument(); for (int addrSuffix = 1; addrSuffix < 254; addrSuffix++) { try { // Now see if we can find a GG server... ipAddress = addrPrefix + "." + addrSuffix; // Display what IP address is being scanned... ux_textboxLoginMessage.Text = "Scanning " + ipAddress + "..."; ux_textboxLoginMessage.Update(); // Attempt to discover the GG specific web services using the IP address... dd = dcp.Discover("http://" + ipAddress + "/GRINGlobal/GUI.asmx"); // If we made it here, we found a webservice so now attempt to resolve the ipAddress to a friendlier host name // Why do this now? Because DNS lookup can be expensive so only do it when really neccessary // (BTW... unresolved DNS lookups will return the ipAddress)... serverName = System.Net.Dns.GetHostEntry(ipAddress).HostName; webServiceURL = "http://" + serverName + "/GRINGlobal/GUI.asmx"; // Attempt to discover the GG specific web services (again - this time with a DNS resolved computer name) // Why do this? Because there is a slight possiblity the DNS lookup returned bogus data... dd = dcp.Discover(webServiceURL); for (int i = 0; i < dd.References.Count; i++) { // There are many different references in a discovery document - we only want the SOAP Bindings... if (dd.References[i].GetType() == typeof(System.Web.Services.Discovery.SoapBinding)) { System.Web.Services.Discovery.SoapBinding wsb = (System.Web.Services.Discovery.SoapBinding)dd.References[i]; // The bad news is that the references have duplicates bindings (one for each protocol), but the good // news is that since the WebServiceURLs object is a dictionary... it will create and execption if the same Key entry is // attempted to be added twice (net result is that it will silently fail in the catch block)... WebServiceURLs.Add(serverName, wsb.Address); } } } catch { // Silently fail... } ux_progressbarScanning.PerformStep(); ux_progressbarScanning.Update(); // Check to see if we should bail out (at user request)... Application.DoEvents(); } } } } ux_progressbarScanning.Hide(); ux_textboxLoginMessage.Text = origMessage; }
public void Open() { if (!opened) { //// For udp receiver sockets it's important to set the "ReuseAddress" socket option //// before we call bind. Otherwise we will have a conflict with other applications //// listening on the same port. udpSocket = new UdpClient(); //udpSocket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1); string IpAddress = "0.0.0.0"; // We need to bind to a specific interface so we can get an IP address to publish to udp senders if (this.localInterface.Equals("0.0.0.0")) { System.Net.NetworkInformation.IPGlobalProperties gp = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties(); System.Net.NetworkInformation.UnicastIPAddressInformationCollection x = gp.GetUnicastAddresses(); for (int i = 0; i < x.Count; i++) { if (x[i].Address.AddressFamily == AddressFamily.InterNetwork) //IPV4 { IpAddress = x[i].Address.ToString(); break; } } } else { IpAddress = this.localInterface; } // If this.port == 0, the system will assign us a port. We fetch the used port below. IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IpAddress), this.port); udpSocket.Client.Bind(ep); // Fetch actualy used ip and port that we listen to this.IP = ((IPEndPoint)udpSocket.Client.LocalEndPoint).Address.ToString(); this.Port = ((IPEndPoint)udpSocket.Client.LocalEndPoint).Port; if (this.receiveBufferSize > 0) { udpSocket.Client.ReceiveBufferSize = this.receiveBufferSize; } this.opened = true; } }
public void Open() { if (!opened) { //// For udp receiver sockets it's important to set the "ReuseAddress" socket option //// before we call bind. Otherwise we will have a conflict with other applications //// listening on the same port. udpSocket = new UdpClient(); //udpSocket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1); string IpAddress = "0.0.0.0"; // We need to bind to a specific interface so we can get an IP address to publish to udp senders if (this.localInterface.Equals("0.0.0.0")) { /* This does not work on mono (tested with version 4.2.3) * System.Net.NetworkInformation.IPGlobalProperties gp = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties(); * System.Net.NetworkInformation.UnicastIPAddressInformationCollection x = gp.GetUnicastAddresses(); * for (int i = 0; i < x.Count; i++) * { * if (x[i].Address.AddressFamily == AddressFamily.InterNetwork) //IPV4 * { * IpAddress = x[i].Address.ToString(); * break; * } * } */ // Alternative implementation to enable use on mono System.Net.NetworkInformation.NetworkInterface[] nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); if (nics != null) { foreach (System.Net.NetworkInformation.NetworkInterface adapter in nics) { System.Net.NetworkInformation.IPInterfaceProperties properties = adapter.GetIPProperties(); System.Net.NetworkInformation.UnicastIPAddressInformationCollection uniCast = properties.UnicastAddresses; if (uniCast != null) { foreach (System.Net.NetworkInformation.UnicastIPAddressInformation uni in uniCast) { if (uni.Address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork) { continue; //IPV4 } IpAddress = uni.Address.ToString(); break; } } if (!IpAddress.Equals("0.0.0.0")) { break; } } } } else { IpAddress = this.localInterface; } // If this.port == 0, the system will assign us a port. We fetch the used port below. IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IpAddress), this.port); udpSocket.Client.Bind(ep); // Fetch actualy used ip and port that we listen to this.IP = ((IPEndPoint)udpSocket.Client.LocalEndPoint).Address.ToString(); this.Port = ((IPEndPoint)udpSocket.Client.LocalEndPoint).Port; if (this.receiveBufferSize > 0) { udpSocket.Client.ReceiveBufferSize = this.receiveBufferSize; } this.opened = true; } }
public void ShowIPAddresses(System.Net.NetworkInformation.IPInterfaceProperties adapterProperties) { //System.Net.NetworkInformation.IPAddressCollection dnsServers = adapterProperties.DnsAddresses; //if (dnsServers != null) //{ // foreach (System.Net.IPAddress dns in dnsServers) // { // Log(" DNS Servers ............................. : " + dns.ToString() // ); // } //} //System.Net.NetworkInformation.IPAddressInformationCollection anyCast = adapterProperties.AnycastAddresses; //if (anyCast != null) //{ // foreach (System.Net.NetworkInformation.IPAddressInformation any in anyCast) // { // if (any.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) //IPV4 // Log(" Anycast Address .......................... : " + any.Address + " " + (any.IsTransient ? "Transient" : "") + " " + (any.IsDnsEligible ? "DNS Eligible" : "")); // } // Console.WriteLine(); //} //System.Net.NetworkInformation.MulticastIPAddressInformationCollection multiCast = adapterProperties.MulticastAddresses; //if (multiCast != null) //{ // foreach (System.Net.NetworkInformation.IPAddressInformation multi in multiCast) // { // if (multi.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) //IPV4 // Log(" Multicast Address ....................... : " + // multi.Address + " " + // (multi.IsTransient ? "Transient" : "") + " " + // (multi.IsDnsEligible ? "DNS Eligible" : "") // ); // } // Console.WriteLine(); //} System.Net.NetworkInformation.UnicastIPAddressInformationCollection uniCast = adapterProperties.UnicastAddresses; if (uniCast != null) { //string lifeTimeFormat = "dddd, MMMM dd, yyyy hh:mm:ss tt"; foreach (System.Net.NetworkInformation.UnicastIPAddressInformation uni in uniCast) { //DateTime when; if (uni.Address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork) { continue; //IPV4 } Log(" Unicast Address ......................... : " + uni.Address); //Log(" Prefix Origin ........................ : " + uni.PrefixOrigin); //Log(" Suffix Origin ........................ : " + uni.SuffixOrigin); //Log(" Duplicate Address Detection .......... : " + uni.DuplicateAddressDetectionState); // Format the lifetimes as Sunday, February 16, 2003 11:33:44 PM // if en-us is the current culture. //// Calculate the date and time at the end of the lifetimes. //when = DateTime.UtcNow + TimeSpan.FromSeconds(uni.AddressValidLifetime); //when = when.ToLocalTime(); //Console.WriteLine(" Valid Life Time ...................... : {0}", // when.ToString(lifeTimeFormat, System.Globalization.CultureInfo.CurrentCulture) //); //when = DateTime.UtcNow + TimeSpan.FromSeconds(uni.AddressPreferredLifetime); //when = when.ToLocalTime(); //Console.WriteLine(" Preferred life time .................. : {0}", // when.ToString(lifeTimeFormat, System.Globalization.CultureInfo.CurrentCulture) //); //when = DateTime.UtcNow + TimeSpan.FromSeconds(uni.DhcpLeaseLifetime); //when = when.ToLocalTime(); //Console.WriteLine(" DHCP Leased Life Time ................ : {0}", // when.ToString(lifeTimeFormat, System.Globalization.CultureInfo.CurrentCulture) //); } } }