public static string[] GetAvailableIps() { List <string> ips = new List <string>(); System.Net.NetworkInformation.NetworkInterface[] interfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); Console.WriteLine("Available IPS:" + interfaces.Length); foreach (System.Net.NetworkInformation.NetworkInterface inf in interfaces) { Console.WriteLine(inf.Name); if (!inf.IsReceiveOnly && inf.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up && inf.SupportsMulticast && inf.NetworkInterfaceType != System.Net.NetworkInformation.NetworkInterfaceType.Loopback) { System.Net.NetworkInformation.IPInterfaceProperties ipinfo = inf.GetIPProperties(); //if (ipinfo.GatewayAddresses == null || ipinfo.GatewayAddresses.Count == 0 || (ipinfo.GatewayAddresses.Count == 1 && ipinfo.GatewayAddresses[0].Address.ToString() == "0.0.0.0")) continue; foreach (System.Net.NetworkInformation.UnicastIPAddressInformation addr in ipinfo.UnicastAddresses) { Console.WriteLine(addr.Address); if ((addr.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)) // || // ((addr.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) && Yabe.Properties.Settings.Default.IPv6_Support)) //for now, no IPv6... { ips.Add(addr.Address.ToString()); } } } } return(ips.ToArray()); }
public static System.Net.IPAddress GetFirstMulticastIPAddress(System.Net.NetworkInformation.NetworkInterface networkInterface, System.Net.Sockets.AddressFamily addressFamily) { //Filter interfaces which are not usable. if (networkInterface == null || false == networkInterface.SupportsMulticast || networkInterface.OperationalStatus != System.Net.NetworkInformation.OperationalStatus.Up)// The interface is not up (should probably ignore...?) { return(System.Net.IPAddress.None); } //Get the IPInterfaceProperties for the NetworkInterface System.Net.NetworkInformation.IPInterfaceProperties interfaceProperties = networkInterface.GetIPProperties(); //If there are no IPInterfaceProperties then try the next interface if (interfaceProperties == null) { return(null); } //Iterate for each Multicast IP bound to the interface foreach (System.Net.NetworkInformation.MulticastIPAddressInformation multicastIpInfo in interfaceProperties.MulticastAddresses) { //If the IP AddresFamily is the same as required then return it. (Maybe Broadcast...) if (multicastIpInfo.Address.AddressFamily == addressFamily) { return(multicastIpInfo.Address); } } //Indicate no multicast IPAddress was found return(System.Net.IPAddress.None); }
{ //得到网关地址 public static string GetGateway() { //网关地址 string strGateway = ""; //获取所有网卡 System.Net.NetworkInformation.NetworkInterface[] nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); //遍历数组 foreach (var netWork in nics) { //单个网卡的IP对象 System.Net.NetworkInformation.IPInterfaceProperties ip = netWork.GetIPProperties(); //获取该IP对象的网关 System.Net.NetworkInformation.GatewayIPAddressInformationCollection gateways = ip.GatewayAddresses; foreach (var gateWay in gateways) { //如果能够Ping通网关 if (IsPingIP(gateWay.Address.ToString())) { //得到网关地址 strGateway = gateWay.Address.ToString(); //跳出循环 break; } } //如果已经得到网关地址 if (strGateway.Length > 0) { //跳出循环 break; } } //返回网关地址 return(strGateway); }/// <summary>
public static string[] GetAvailableIps() { List <string> ips = new List <string>(); System.Net.NetworkInformation.NetworkInterface[] interfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); foreach (System.Net.NetworkInformation.NetworkInterface inf in interfaces) { if (!inf.IsReceiveOnly && inf.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up && inf.SupportsMulticast && inf.NetworkInterfaceType != System.Net.NetworkInformation.NetworkInterfaceType.Loopback) { if (!(inf.Description.Contains("VirtualBox") || inf.Description.Contains("VMware"))) // remove interfaces with virtual machines { System.Net.NetworkInformation.IPInterfaceProperties ipinfo = inf.GetIPProperties(); foreach (System.Net.NetworkInformation.UnicastIPAddressInformation addr in ipinfo.UnicastAddresses) { if ((addr.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) || ((addr.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) && Properties.Settings.Default.IPv6_Support)) { ips.Add(addr.Address.ToString()); } } } } } return(ips.ToArray()); }
/// <summary> /// 获取本地IPv4地址 /// </summary> public static string GetHostIPv4(string[] NetNames) { System.Net.NetworkInformation.NetworkInterface[] interfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); int len = interfaces.Length; for (int i = 0; i < len; i++) { System.Net.NetworkInformation.NetworkInterface ni = interfaces[i]; if (ni.NetworkInterfaceType == System.Net.NetworkInformation.NetworkInterfaceType.Ethernet) { if (NetNames.Contains(ni.Name)) { System.Net.NetworkInformation.IPInterfaceProperties property = ni.GetIPProperties(); foreach (System.Net.NetworkInformation.UnicastIPAddressInformation ip in property.UnicastAddresses) { if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { return(ip.Address.ToString()); } } } } } return(string.Empty); }
/// <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 string GetMACAddress() { System.Net.NetworkInformation.NetworkInterface[] nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); String sMacAddress = string.Empty; foreach (System.Net.NetworkInformation.NetworkInterface adapter in nics) { if (sMacAddress == String.Empty)// only return MAC Address from first card { System.Net.NetworkInformation.IPInterfaceProperties properties = adapter.GetIPProperties(); sMacAddress = adapter.GetPhysicalAddress().ToString(); } } return(sMacAddress); }
private List <IPAddress> getLocalIps() { if (_localAddresses == null) { _localAddresses = new List <IPAddress>(); foreach (System.Net.NetworkInformation.NetworkInterface iface in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()) { System.Net.NetworkInformation.IPInterfaceProperties iprop = iface.GetIPProperties(); foreach (System.Net.NetworkInformation.UnicastIPAddressInformation info in iprop.UnicastAddresses) { _localAddresses.Add(IPAddress.Parse(info.Address.ToString())); } } } return(_localAddresses); }
public bool IsIpAddressLocal(System.Net.IPAddress address) { if (_localAddresses == null) { _localAddresses = new List <System.Net.IPAddress>(); foreach (System.Net.NetworkInformation.NetworkInterface iface in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()) { System.Net.NetworkInformation.IPInterfaceProperties iprop = iface.GetIPProperties(); foreach (System.Net.NetworkInformation.UnicastIPAddressInformation info in iprop.UnicastAddresses) { _localAddresses.Add(info.Address); } } } return(_localAddresses.Contains(address)); }
public static System.Net.IPAddress GetFirstUnicastIPAddress(System.Net.NetworkInformation.NetworkInterface networkInterface, System.Net.Sockets.AddressFamily addressFamily) { //Filter interfaces which are not usable. if (networkInterface == null || networkInterface.OperationalStatus != System.Net.NetworkInformation.OperationalStatus.Up)// The interface is not up { return(System.Net.IPAddress.None); } //Get the IPInterfaceProperties for the NetworkInterface System.Net.NetworkInformation.IPInterfaceProperties interfaceProperties = networkInterface.GetIPProperties(); //If there are no IPInterfaceProperties then try the next interface if (interfaceProperties == null) { return(null); } //Iterate for each Unicast IP bound to the interface foreach (System.Net.NetworkInformation.UnicastIPAddressInformation unicastIpInfo in interfaceProperties.UnicastAddresses) { //Get the address System.Net.IPAddress address = unicastIpInfo.Address; //If the IP AddressFamily is not the same as required then return it. if (address.AddressFamily != addressFamily) { continue; } //Don't use Any and don't use Broadcast. if (address.Equals(System.Net.IPAddress.Broadcast) || (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6 ? address.Equals(System.Net.IPAddress.IPv6Any) : address.Equals(System.Net.IPAddress.Any))) { continue; } //Return the compatible address. return(address); } //Indicate no unicast IPAddress was found return(System.Net.IPAddress.None); }
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 string[] _GetAvailableIps() { List <string> ips = new List <string>(); System.Net.NetworkInformation.NetworkInterface[] interfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); foreach (System.Net.NetworkInformation.NetworkInterface inf in interfaces) { if (!inf.IsReceiveOnly && inf.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up && inf.SupportsMulticast && (inf.NetworkInterfaceType != System.Net.NetworkInformation.NetworkInterfaceType.Loopback || this._SParams.ListLoopback)) { System.Net.NetworkInformation.IPInterfaceProperties ipinfo = inf.GetIPProperties(); foreach (System.Net.NetworkInformation.UnicastIPAddressInformation addr in ipinfo.UnicastAddresses) { if (addr.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { ips.Add(addr.Address.ToString()); } } } } return(ips.ToArray()); }
/// <summary> /// 获取当前活动着的网络链接的名称。 /// 默认通过百度的ip进行测试。也可以指定IP /// </summary> /// <returns></returns> public static string GetActiveConnectionID(String testAddress = "123.125.115.110") { System.Net.Sockets.UdpClient udp = new System.Net.Sockets.UdpClient(testAddress, 1); System.Net.IPAddress localAddr = ((System.Net.IPEndPoint)udp.Client.LocalEndPoint).Address; foreach (System.Net.NetworkInformation.NetworkInterface nic in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()) { System.Net.NetworkInformation.IPInterfaceProperties ipProps = nic.GetIPProperties(); foreach (var ip in ipProps.UnicastAddresses) { if (localAddr.Equals(ip.Address)) { return(nic.Name); } } } return(String.Empty); // 20180719:通过IPEnable,不能准确测出来是哪个网卡能上网。多网卡情况下,可能多个网卡的IPEnable都是True //List<Win32Provider.Win32_NetworkAdapterConfiguration> list = Win32Provider.ProviderHelper<Win32Provider.Win32_NetworkAdapterConfiguration>.GetAll(); //if(list == null || list.Count == 0) // return string.Empty; //Win32Provider.Win32_NetworkAdapterConfiguration obj = list.FirstOrDefault(o => o.IPEnabled == true); //if(obj == null) // return string.Empty; //// 根据MAC地址,找到连接的名称 //List<Win32Provider.Win32_NetworkAdapter> listAdapters = Win32Provider.ProviderHelper<Win32Provider.Win32_NetworkAdapter>.GetAll(); //if(listAdapters == null || listAdapters.Count == 0) // return string.Empty; //Win32Provider.Win32_NetworkAdapter objAdapter = listAdapters.FirstOrDefault(o => o.MACAddress == obj.MACAddress); //if(obj == null) // return string.Empty; //return objAdapter.NetConnectionID; }
/// <summary> /// Get the subnet mask associated with an IPv4 address. /// </summary> /// <param name="localAddress">IPv4 address for which you will find the subnet mask.</param> /// <returns>The subnet mask associated with the IPv4 address.</returns> /// <exception cref="ArgumentException">Argument Exception if localAddress is not an IPv4 address.</exception> public static IPAddress GetSubnetMask(IPAddress localAddress) { if (localAddress == null || localAddress.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork) { throw new ArgumentException("'localAddress' must be an IPv4 address."); } try { foreach (System.Net.NetworkInformation.NetworkInterface nic in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()) { System.Net.NetworkInformation.IPInterfaceProperties ipProps = nic.GetIPProperties(); foreach (System.Net.NetworkInformation.UnicastIPAddressInformation unicastAddress in ipProps.UnicastAddresses) { if (unicastAddress.Address.Equals(localAddress)) { return(unicastAddress.IPv4Mask); } } } } catch (Exception) { } return(null); }
// 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; }
public List <IPAddress> DetectedVehicles(string remoteHostConfig, int maxVehicles = -1) { if (!remoteHostConfig.StartsWith(AutoIp, StringComparison.OrdinalIgnoreCase)) { return(null); } // ReSharper disable once UseObjectOrCollectionInitializer UdpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); #if !WindowsCE UdpSocket.EnableBroadcast = true; #endif IPEndPoint ipUdp = new IPEndPoint(IPAddress.Any, 0); UdpSocket.Bind(ipUdp); lock (UdpRecListLock) { UdpRecIpListList = new List <IPAddress>(); } UdpMaxResponses = maxVehicles; StartUdpListen(); bool broadcastSend = false; #if !WindowsCE string configData = remoteHostConfig.Remove(0, AutoIp.Length); if ((configData.Length > 0) && (configData[0] == ':')) { string adapterName = configData.StartsWith(":all", StringComparison.OrdinalIgnoreCase) ? string.Empty : configData.Remove(0, 1); System.Net.NetworkInformation.NetworkInterface[] adapters = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); foreach (System.Net.NetworkInformation.NetworkInterface adapter in adapters) { if (adapter.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up) { System.Net.NetworkInformation.IPInterfaceProperties properties = adapter.GetIPProperties(); if (properties.UnicastAddresses != null) { foreach (System.Net.NetworkInformation.UnicastIPAddressInformation ipAddressInfo in properties.UnicastAddresses) { if (ipAddressInfo.Address.AddressFamily == AddressFamily.InterNetwork) { if ((adapterName.Length == 0) || (adapter.Name.StartsWith(adapterName, StringComparison.OrdinalIgnoreCase))) { try { byte[] ipBytes = ipAddressInfo.Address.GetAddressBytes(); byte[] maskBytes = ipAddressInfo.IPv4Mask.GetAddressBytes(); for (int i = 0; i < ipBytes.Length; i++) { ipBytes[i] |= (byte)(~maskBytes[i]); } IPAddress broadcastAddress = new IPAddress(ipBytes); EdiabasProtected?.LogString(EdiabasNet.EdLogLevel.Ifh, string.Format("Sending: '{0}': Ip={1} Mask={2} Broadcast={3}", adapter.Name, ipAddressInfo.Address, ipAddressInfo.IPv4Mask, broadcastAddress)); IPEndPoint ipUdpIdent = new IPEndPoint(broadcastAddress, ControlPort); UdpSocket.SendTo(UdpIdentReq, ipUdpIdent); broadcastSend = true; } catch (Exception) { EdiabasProtected?.LogString(EdiabasNet.EdLogLevel.Ifh, "Broadcast failed"); } } } } } } } } else #endif { try { #if Android || WindowsCE IPEndPoint ipUdpIdent = new IPEndPoint(IPAddress.Broadcast, ControlPort); #else IPEndPoint ipUdpIdent = new IPEndPoint(IPAddress.Parse("169.254.255.255"), ControlPort); #endif EdiabasProtected?.LogString(EdiabasNet.EdLogLevel.Ifh, string.Format("Sending to: {0}", ipUdpIdent.Address)); UdpSocket.SendTo(UdpIdentReq, ipUdpIdent); broadcastSend = true; } catch (Exception) { EdiabasProtected?.LogString(EdiabasNet.EdLogLevel.Ifh, "Broadcast failed"); } } if (!broadcastSend) { EdiabasProtected?.LogString(EdiabasNet.EdLogLevel.Ifh, "No broadcast send"); InterfaceDisconnect(); return(null); } UdpEvent.WaitOne(1000, false); if (UdpRecIpListList.Count == 0) { EdiabasProtected?.LogString(EdiabasNet.EdLogLevel.Ifh, "No answer received"); InterfaceDisconnect(); return(null); } UdpSocket.Close(); List <IPAddress> ipList; lock (UdpRecListLock) { ipList = UdpRecIpListList; UdpRecIpListList = null; } return(ipList); }
public static string GuessLocalIpAddress(System.Net.NetworkInformation.NetworkInterfaceType?ofType) { System.Net.NetworkInformation.UnicastIPAddressInformation mostSuitableIp = null; System.Net.NetworkInformation.NetworkInterface[] networkInterfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); foreach (System.Net.NetworkInformation.NetworkInterface network in networkInterfaces) { if (ofType.HasValue && network.NetworkInterfaceType != ofType) { continue; } if (network.OperationalStatus != System.Net.NetworkInformation.OperationalStatus.Up) { continue; } if (network.Description.ToLower().Contains("virtual") || network.Description.ToLower().Contains("pseudo") ) { continue; } System.Net.NetworkInformation.IPInterfaceProperties properties = network.GetIPProperties(); if (properties.GatewayAddresses.Count == 0) { continue; } foreach (System.Net.NetworkInformation.UnicastIPAddressInformation address in properties.UnicastAddresses) { if (address.Address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork) { continue; } if (System.Net.IPAddress.IsLoopback(address.Address)) { continue; } if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows) && !address.IsDnsEligible) { if (mostSuitableIp == null) { mostSuitableIp = address; } continue; } // The best IP is the IP got from DHCP server if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows) && address.PrefixOrigin != System.Net.NetworkInformation.PrefixOrigin.Dhcp) { if (mostSuitableIp == null || !mostSuitableIp.IsDnsEligible) { mostSuitableIp = address; } continue; } // System.Console.WriteLine(address.IPv4Mask); // Subnet Mask return(address.Address.ToString()); } } return(mostSuitableIp != null ? mostSuitableIp.Address.ToString() : ""); }
private void ConnectionReceived(object sender, NewConnectionEventArgs e) { if (engine.ConnectionManager.ShouldBanPeer(e.Peer)) { e.Connection.Dispose(); return; } PeerId id = new PeerId(e.Peer, e.TorrentManager); id.Connection = e.Connection; Logger.Log(id.Connection, "ListenManager - ConnectionReceived"); if (id.Connection.IsIncoming) { if (!_hasAcceptedConnections) { var ep = ((System.Net.IPEndPoint)id.Connection.EndPoint); System.Net.NetworkInformation.NetworkInterface[] networkInterfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); var found = false; foreach (System.Net.NetworkInformation.NetworkInterface network in networkInterfaces) { System.Net.NetworkInformation.IPInterfaceProperties properties = network.GetIPProperties(); foreach (System.Net.NetworkInformation.IPAddressInformation address in properties.UnicastAddresses) { if (address.Address.AddressFamily != AddressFamily.InterNetwork && address.Address.AddressFamily != AddressFamily.InterNetworkV6) { continue; } if (System.Net.IPAddress.IsLoopback(address.Address)) { continue; } if (address.Address.ToString() == ep.Address.ToString()) { found = true; } } } if (!found) { _hasAcceptedConnections = true; } } List <InfoHash> skeys = new List <InfoHash>(); ClientEngine.MainLoop.QueueWait((MainLoopTask) delegate { for (int i = 0; i < engine.Torrents.Count; i++) { skeys.Add(engine.Torrents[i].InfoHash); } }); EncryptorFactory.BeginCheckEncryption(id, HandshakeMessage.HandshakeLength, endCheckEncryptionCallback, id, skeys.ToArray()); } else { ClientEngine.MainLoop.Queue(delegate { engine.ConnectionManager.ProcessFreshConnection(id); }); } }
// 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; }
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")) { /* 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; } }
private void button1_Click(object sender, EventArgs e) { //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.Count(); j++) addr[j] = (byte)((int)addr[j] & (int)mask[j]); // System.Net.IPAddress Subnet = new System.Net.IPAddress(addr); // Log("IPV4 Address: " + x[i].Address.ToString() + // ", Mask: " + x[i].IPv4Mask.ToString() + // ", Subnet: " + Subnet.ToString() // ); // } // else if (x[i].Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) //IPV6 // { // //Log("IPV6 Address: " + x[i].Address.ToString()); // } // else // { // //Log("OTHER Address: " + x[i].Address.ToString()); // } //} test("0.0.0.0"); test("127.0.0.1"); test("192.168.0.0/255.255.255.0"); test("192.168.0.34"); System.Net.NetworkInformation.IPGlobalProperties computerProperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties(); System.Net.NetworkInformation.NetworkInterface[] nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); Log("Interface information for " + computerProperties.HostName + " . " + computerProperties.DomainName); if (nics == null || nics.Length < 1) { Log(" No network interfaces found."); return; } Log(" Number of interfaces .................... : " + nics.Length); foreach (System.Net.NetworkInformation.NetworkInterface adapter in nics) { System.Net.NetworkInformation.IPInterfaceProperties properties = adapter.GetIPProperties(); Log(adapter.Description); Log(String.Empty.PadLeft(adapter.Description.Length, '=')); Log(" Interface type .......................... : " + adapter.NetworkInterfaceType); //Log(" Physical Address ........................ : " + adapter.GetPhysicalAddress().ToString()); //Log(" Operational status ...................... : " + adapter.OperationalStatus); //string versions = ""; // Create a display string for the supported IP versions. //if (adapter.Supports(System.Net.NetworkInformation.NetworkInterfaceComponent.IPv4)) //{ // versions = "IPv4"; //} //if (adapter.Supports(System.Net.NetworkInformation.NetworkInterfaceComponent.IPv6)) //{ // if (versions.Length > 0) // { // versions += " "; // } // versions += "IPv6"; //} //Log(" IP version .............................. : " + versions); ShowIPAddresses(properties); // The following information is not useful for loopback adapters. //if (adapter.NetworkInterfaceType == System.Net.NetworkInformation.NetworkInterfaceType.Loopback) //{ // continue; //} //Log(" DNS suffix .............................. : " + properties.DnsSuffix); //if (adapter.Supports(System.Net.NetworkInformation.NetworkInterfaceComponent.IPv4)) //{ // System.Net.NetworkInformation.IPv4InterfaceProperties ipv4 = properties.GetIPv4Properties(); // Log(" MTU...................................... : " + ipv4.Mtu); //} } }
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) //); } } }