public IpBits(IpVersion ver, Vt_to_string cp, Vt_to_string ucp, uint bits, uint part_bits, uint dns_bits, String rev_domain, BigInteger part_mod, BigInteger host_ofs) { this.version = ver; this.vt_as_compressed_string = cp; this.vt_as_uncompressed_string = ucp; this.bits = bits; this.part_bits = part_bits; this.dns_bits = dns_bits; this.rev_domain = rev_domain; this.part_mod = part_mod; this.host_ofs = host_ofs; }
/// <summary> /// Generate a random packet of a specific ip version /// </summary> /// <param name="version"> /// A <see cref="IpVersion" /> /// </param> /// <returns> /// A <see cref="IpPacket" /> /// </returns> public static IpPacket RandomPacket(IpVersion version) { Log.DebugFormat("version {0}", version); if (version == IpVersion.IPv4) { return(IPv4Packet.RandomPacket()); } if (version == IpVersion.IPv6) { return(IPv6Packet.RandomPacket()); } throw new InvalidOperationException("Unknown version of " + version); }
/// <summary> /// Generate a random packet of a specific ip version /// </summary> /// <param name="version"> /// A <see cref="IpVersion"/> /// </param> /// <returns> /// A <see cref="IpPacket"/> /// </returns> public static IpPacket RandomPacket(IpVersion version) { if (version == IpVersion.IPv4) { return(IPv4Packet.RandomPacket()); } else if (version == IpVersion.IPv6) { return(IPv6Packet.RandomPacket()); } else { throw new System.InvalidOperationException("Unknown version of " + version); } }
/// <summary> /// Generate a random ip address /// </summary> /// <param name="version"> /// A <see cref="IpVersion"/> /// </param> /// <returns> /// A <see cref="System.Net.IPAddress"/> /// </returns> public static System.Net.IPAddress GetIPAddress(IpVersion version) { var rnd = new Random(); byte[] randomAddressBytes; if (version == IpVersion.IPv4) { randomAddressBytes = new byte[IPv4Fields.AddressLength]; rnd.NextBytes(randomAddressBytes); } else if (version == IpVersion.IPv6) { randomAddressBytes = new byte[IPv6Fields.AddressLength]; rnd.NextBytes(randomAddressBytes); } else { throw new System.InvalidOperationException("Unknown version of " + version); } return new System.Net.IPAddress(randomAddressBytes); }
public static bool IsIp(string input, IpVersion version) { IPAddress address; if (IPAddress.TryParse(input, out address)) { if (address.AddressFamily == AddressFamily.InterNetwork && version == IpVersion.Four) { return(true); } if (address.AddressFamily == AddressFamily.InterNetworkV6 && version == IpVersion.Six) { return(true); } } return(false); }
/// <summary> /// Determine whether input is a valid IPv4 or IPv6 address. /// </summary> /// <param name="input"></param> /// <param name="version">Valid values are: IpVersion.Four and IpVersion.Six</param> /// <returns></returns> public static bool IsIp(string input, IpVersion version) { const string ipv4MaybePattern = @"^(\d?\d?\d)\.(\d?\d?\d)\.(\d?\d?\d)\.(\d?\d?\d)$"; const string ipv6Pattern = @"^::|^::1|^([a-fA-F0-9]{1,4}::?){1,7}([a-fA-F0-9]{1,4})$"; if (version == IpVersion.Four) { if (!Validator.Matches(input, ipv4MaybePattern)) { return(false); } var parts = input.Split('.').Select(p => Convert.ToInt32(p)); return(parts.Max() <= 255); } return(Validator.Matches(input, ipv6Pattern)); }
/// <summary> /// Use TestInitialize to run code before running the test in the class. /// </summary> protected override void TestInitialize() { base.TestInitialize(); this.ISMBAdapterInstance = Site.GetAdapter <ISmbAdapter>(); this.IServerSetupAdapterInstance = Site.GetAdapter <IServerSetupAdapter>(); smbClientStack = new SmbClient(); serverName = Site.Properties["SutMachineName"]; serverPort = int.Parse(Site.Properties["SutPort"]); string ip = Site.Properties["SmbTransportIpVersion"]; switch (ip.ToLower()) { case "ipv4": ipVersion = IpVersion.Ipv4; break; case "ipv6": ipVersion = IpVersion.Ipv6; break; default: ipVersion = IpVersion.Any; break; } bufferSize = int.Parse(Site.Properties["SmbTransportBufferSize"]); domainName = Site.Properties["SutLoginDomain"]; userName = Site.Properties["SutLoginAdminUserName"]; password = Site.Properties["SutLoginAdminPwd"]; string ptfSutOs = Site.Properties["SutPlatformOS"].ToString(); if (Enum.Parse(typeof(Platform), ptfSutOs, true) != null) { sutOsVersion = (Platform)Enum.Parse(typeof(Platform), ptfSutOs, true); } else { sutOsVersion = Platform.NonWindows; } }
public static string GetIP(IpVersion ipVersion) { if (ipVersion == IpVersion.IPv6 && !Socket.OSSupportsIPv6) { ipVersion = IpVersion.IPv4; // Fallback to IPv4 if OS does not support IPv6. } if (ipVersion == IpVersion.IPv4 && !Socket.OSSupportsIPv4) { return(null); } string output = string.Empty; foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces()) { #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN NetworkInterfaceType _type1 = NetworkInterfaceType.Wireless80211; NetworkInterfaceType _type2 = NetworkInterfaceType.Ethernet; if ((item.NetworkInterfaceType == _type1 || item.NetworkInterfaceType == _type2) && item.OperationalStatus == OperationalStatus.Up) #endif { foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses) { if (ipVersion == IpVersion.IPv4) { if (ip.Address.AddressFamily == AddressFamily.InterNetwork) { output = ip.Address.ToString(); } } else if (ipVersion == IpVersion.IPv6) { if (ip.Address.AddressFamily == AddressFamily.InterNetworkV6) { output = ip.Address.ToString(); } } } } } return(output); }
/// <summary> /// Creates a string representation of the IpPacket object. /// </summary> public override string ToString() { var s = new StringBuilder(); s.Append("IP version: "); s.AppendLine(IpVersion.ToString()); s.Append("Internet Header Length "); s.AppendLine(InternetHeaderLength.ToString()); s.Append("DSCP value "); s.AppendLine(DscpValue.ToString()); s.Append("ECN value "); s.AppendLine(ExplicitCongestionNotice.ToString()); s.Append("IP packet length "); s.AppendLine(IpPacketLength.ToString()); s.Append("ID/Fragment Group "); s.AppendLine(FragmentGroupId.ToString()); s.Append("IP header flags "); s.AppendLine(IpHeaderFlags.ToString()); s.Append("Fragment offset "); s.AppendLine(FragmentOffset.ToString()); s.Append("TTL "); s.AppendLine(TimeToLive.ToString()); s.Append("Protocol Number "); s.AppendLine(ProtocolNumber.ToString()); s.Append("Header Checksum "); s.AppendLine(PacketHeaderChecksum.ToString()); s.Append("Source IP "); s.AppendLine(SourceIpAddress.ToString()); s.Append("Destination IP "); s.AppendLine(DestinationIpAddress.ToString()); if (IpOptions != null) { s.Append("Length of IP options "); s.AppendLine(IpOptions.Length.ToString()); } s.Append("Packet Data Length "); s.AppendLine(PacketData.Length.ToString()); s.Append("Size of data buffer processed "); s.AppendLine(DataBuffer.Length.ToString()); return(s.ToString()); }
/// <summary> /// Gets the TCP row by local port number. /// </summary> /// <returns><see cref="TcpRow"/>.</returns> internal static TcpRow GetTcpRowByLocalPort(IpVersion ipVersion, int localPort) { var tcpTable = IntPtr.Zero; int tcpTableLength = 0; int ipVersionValue = ipVersion == IpVersion.Ipv4 ? NativeMethods.AfInet : NativeMethods.AfInet6; int allPid = (int)NativeMethods.TcpTableType.OwnerPidAll; if (NativeMethods.GetExtendedTcpTable(tcpTable, ref tcpTableLength, false, ipVersionValue, allPid, 0) != 0) { try { tcpTable = Marshal.AllocHGlobal(tcpTableLength); if (NativeMethods.GetExtendedTcpTable(tcpTable, ref tcpTableLength, true, ipVersionValue, allPid, 0) == 0) { var table = (NativeMethods.TcpTable)Marshal.PtrToStructure(tcpTable, typeof(NativeMethods.TcpTable)); var rowPtr = (IntPtr)((long)tcpTable + Marshal.SizeOf(table.length)); for (int i = 0; i < table.length; ++i) { var tcpRow = (NativeMethods.TcpRow)Marshal.PtrToStructure(rowPtr, typeof(NativeMethods.TcpRow)); if (tcpRow.GetLocalPort() == localPort) { return(new TcpRow(tcpRow)); } rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(typeof(NativeMethods.TcpRow))); } } } finally { if (tcpTable != IntPtr.Zero) { Marshal.FreeHGlobal(tcpTable); } } } return(null); }
private static T[] GetTcpConnections <T>(IpVersion ipVersion) { T[] tTable; int buffSize = 0; // how much memory do we need? GetExtendedTcpTable(IntPtr.Zero, ref buffSize, false, ipVersion, TcpTableClass.TcpTableOwnerPidAll, 0); IntPtr buffer = Marshal.AllocHGlobal(buffSize); try { uint retVal = GetExtendedTcpTable(buffer, ref buffSize, false, ipVersion, TcpTableClass.TcpTableOwnerPidAll, 0); while (retVal == ErrorInsufficientBuffer) //buffer should be greater? { buffer = Marshal.ReAllocHGlobal(buffer, new IntPtr(buffSize)); retVal = GetExtendedTcpTable(buffer, ref buffSize, false, ipVersion, TcpTableClass.TcpTableOwnerPidAll, 0); } if (retVal != Successfully) { return(null); } ReadData(buffer, out tTable); } catch (Exception) { return(null); } finally { // Free the Memory Marshal.FreeHGlobal(buffer); } return(tTable); }
public static IPAddress GetIPAddress(IpVersion version) { byte[] buffer; Random random = new Random(); if (version == IpVersion.IPv4) { buffer = new byte[IPv4Fields.AddressLength]; random.NextBytes(buffer); } else { if (version != IpVersion.IPv6) { throw new InvalidOperationException("Unknown version of " + version); } buffer = new byte[IPv6Fields.AddressLength]; random.NextBytes(buffer); } return(new IPAddress(buffer)); }
/// <summary> /// Gets the extended TCP table. /// </summary> /// <returns>Collection of <see cref="TcpRow"/>.</returns> internal static TcpTable GetExtendedTcpTable(IpVersion ipVersion) { var tcpRows = new List <TcpRow>(); var tcpTable = IntPtr.Zero; int tcpTableLength = 0; int ipVersionValue = ipVersion == IpVersion.Ipv4 ? NativeMethods.AfInet : NativeMethods.AfInet6; if (NativeMethods.GetExtendedTcpTable(tcpTable, ref tcpTableLength, false, ipVersionValue, (int)NativeMethods.TcpTableType.OwnerPidAll, 0) != 0) { try { tcpTable = Marshal.AllocHGlobal(tcpTableLength); if (NativeMethods.GetExtendedTcpTable(tcpTable, ref tcpTableLength, true, ipVersionValue, (int)NativeMethods.TcpTableType.OwnerPidAll, 0) == 0) { var table = (NativeMethods.TcpTable)Marshal.PtrToStructure(tcpTable, typeof(NativeMethods.TcpTable)); var rowPtr = (IntPtr)((long)tcpTable + Marshal.SizeOf(table.length)); for (int i = 0; i < table.length; ++i) { tcpRows.Add(new TcpRow((NativeMethods.TcpRow)Marshal.PtrToStructure(rowPtr, typeof(NativeMethods.TcpRow)))); rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(typeof(NativeMethods.TcpRow))); } } } finally { if (tcpTable != IntPtr.Zero) { Marshal.FreeHGlobal(tcpTable); } } } return(new TcpTable(tcpRows)); }
/// <summary> /// Generate a random ip address /// </summary> /// <param name="version"> /// A <see cref="IpVersion"/> /// </param> /// <returns> /// A <see cref="System.Net.IPAddress"/> /// </returns> public static System.Net.IPAddress GetIPAddress(IpVersion version) { var rnd = new Random(); byte[] randomAddressBytes; if (version == IpVersion.IPv4) { randomAddressBytes = new byte[IPv4Fields.AddressLength]; rnd.NextBytes(randomAddressBytes); } else if (version == IpVersion.IPv6) { randomAddressBytes = new byte[IPv6Fields.AddressLength]; rnd.NextBytes(randomAddressBytes); } else { throw new System.InvalidOperationException("Unknown version of " + version); } return(new System.Net.IPAddress(randomAddressBytes)); }
public static string GetRandomIpAddress(IpVersion version = IpVersion.Ipv4) { var rnd = new Random(Guid.NewGuid().GetHashCode()); switch (version) { case IpVersion.Ipv4: var address = new List <string>(); for (var i = 0; i < 4; i++) { var segmentInt = 0; do { segmentInt = rnd.Next(1, 255); } while (segmentInt == 127); var segment = segmentInt.ToString(); address.Add(segment); } return(string.Join(".", address)); case IpVersion.Ipv6: var segments = new List <string>(); for (int i = 0; i < 8; i++) { var segment = rnd.Next(0, 65536).ToString("X"); segments.Add(segment); } return(string.Join(":", segments)); default: throw new RegoException("Unrecognized IP version"); } }
public async Task <IPEndPoint> ResolveAsync(string endpoint, int port, IpVersion ipVersion = IpVersion.IpV4) { string cacheKey = string.Join(":", endpoint, port, ipVersion); if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort) { throw new ArgumentOutOfRangeException(nameof(port)); } if (cache.HasKey(cacheKey)) { return(cache.Get <IPEndPoint>(cacheKey)); } var addressFamily = ipVersion == IpVersion.IpV4 ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6; IPEndPoint ipEndpoint; var ipAddress = TryGetIpAddress(endpoint); if (ipAddress != null) { ipEndpoint = new IPEndPoint(ipAddress, port); cache.Add(cacheKey, ipEndpoint, TimeSpan.FromMinutes(60)); return(ipEndpoint); } try { var allAddresses = await Dns.GetHostAddressesAsync(endpoint); var firstAddressInFamily = allAddresses.FirstOrDefault(x => x.AddressFamily == addressFamily); if (firstAddressInFamily != null) { ipEndpoint = new IPEndPoint(firstAddressInFamily, port); cache.Add(cacheKey, ipEndpoint, TimeSpan.FromMinutes(60)); return(ipEndpoint); } var firstAddress = allAddresses.FirstOrDefault(); if (firstAddress == null) { return(null); } switch (firstAddress.AddressFamily) { case AddressFamily.InterNetwork: ipEndpoint = new IPEndPoint(firstAddress.MapToIPv6(), port); break; case AddressFamily.InterNetworkV6: ipEndpoint = new IPEndPoint(firstAddress.MapToIPv4(), port); break; default: return(null); } cache.Add(cacheKey, ipEndpoint, TimeSpan.FromMinutes(60)); return(ipEndpoint); } catch (Exception) { return(null); } }
/// <summary> /// The process record method. /// </summary> protected override void ProcessRecord() { ResponseType response = null; base.ProcessRecord(); try { RulePlacementType rulePlacement = new RulePlacementType { position = Position }; if (Position == RulePositionType.AFTER || Position == RulePositionType.BEFORE) { if (RelativeToRule == null) { ThrowTerminatingError( new ErrorRecord( new ArgumentException("For relative rule placement, please provide the RelativeRule"), "-3", ErrorCategory.InvalidArgument, Connection)); return; } rulePlacement.relativeToRule = RelativeToRule.name; } var firewall = new CreateFirewallRuleType { networkDomainId = NetworkDomain.id, name = FirewallRuleName, ipVersion = IpVersion.ToString(), protocol = Protocol.ToString(), action = FirewallAction, source = Source, destination = Destination, placement = rulePlacement, enabled = Enabled }; response = Connection.ApiClient.Networking.FirewallRule.CreateFirewallRule(firewall).Result; } catch (AggregateException ae) { ae.Handle( e => { if (e is ComputeApiException) { WriteError(new ErrorRecord(e, "-2", ErrorCategory.InvalidOperation, Connection)); } else { // if (e is HttpRequestException) ThrowTerminatingError(new ErrorRecord(e, "-1", ErrorCategory.ConnectionError, Connection)); } return(true); }); } WriteObject(response); }
/// <summary> /// Connect to a share indicated by shareName in server /// This will use smb over tcp as transport. Only one server /// can be connected at one time /// </summary> /// <param name="serverName">The server Name</param> /// <param name="port">The server port</param> /// <param name="ipVersion">The ip version</param> /// <param name="domain">The domain name</param> /// <param name="userName">The user name</param> /// <param name="password">The password</param> /// <param name="shareName">The share name</param> /// <exception cref="System.InvalidOperationException">Thrown if there is any error occurred</exception> public abstract void ConnectShare(string serverName, int port, IpVersion ipVersion, string domain, string userName, string password, string shareName);
protected RemoteServerTestBase(GcChannelType channelType, Func <MarshalByRefObject> serviceInstanceCreatorFunction, IpVersion ipVersion = IpVersion.IPv4) { _channelType = channelType; _ipVersion = ipVersion; if (serviceInstanceCreatorFunction == null) { throw new ArgumentNullException(nameof(serviceInstanceCreatorFunction)); } _serviceInstanceCreatorFunction = serviceInstanceCreatorFunction; }
public void IsIp(string input, IpVersion version, bool expected) { var actual = Validator.IsIp(input, version); Assert.Equal(actual, expected); }
/// <summary> /// Connect to a share indicated by shareName in server /// This will use smb over tcp as transport. Only one server /// can be connected at one time /// </summary> /// <param name="serverName">The server Name</param> /// <param name="port">The server port</param> /// <param name="ipVersion">The ip version</param> /// <param name="domain">The domain name</param> /// <param name="userName">The user name</param> /// <param name="password">The password</param> /// <param name="shareName">The share name</param> /// <exception cref="System.InvalidOperationException">Thrown if there is any error occurred</exception> public override void ConnectShare(string serverName, int port, IpVersion ipVersion, string domain, string userName, string password, string shareName) { ConnectShare(serverName, port, ipVersion, domain, userName, password, shareName, SecurityPackageType.Ntlm, false); }
public static int ToIpVersion(IpVersion ipVersion) { switch (ipVersion) { case IpVersion.v4: return Converter.IpVersion4; case IpVersion.v6: return Converter.IpVersion6; default: throw new InvalidCastException(); } }
/// <summary> /// Connect to a share indicated by shareName in server /// This will use smb over tcp as transport. Only one server /// can be connected at one time /// </summary> /// <param name="serverName">The server Name</param> /// <param name="port">The server port</param> /// <param name="ipVersion">The ip version</param> /// <param name="domain">The domain name</param> /// <param name="userName">The user name</param> /// <param name="password">The password</param> /// <param name="shareName">The share name</param> /// <param name="securityPackage">The security package</param> /// <param name="useServerToken">Whether to use token from server</param> /// <exception cref="System.InvalidOperationException">Thrown if there is any error occurred</exception> public override void ConnectShare(string serverName, int port, IpVersion ipVersion, string domain, string userName, string password, string shareName, SecurityPackageType securityPackage, bool useServerToken) { throw new NotImplementedException(); }
/// <summary> /// Connect to a share indicated by shareName in server /// This will use smb over tcp as transport. Only one server /// can be connected at one time /// </summary> /// <param name="serverName">The server Name</param> /// <param name="port">The server port</param> /// <param name="ipVersion">The ip version</param> /// <param name="domain">The domain name</param> /// <param name="userName">The user name</param> /// <param name="password">The password</param> /// <param name="shareName">The share name</param> /// <exception cref="System.InvalidOperationException">Thrown if there is any error occurred</exception> public override void ConnectShare(string serverName, int port, IpVersion ipVersion, string domain, string userName, string password, string shareName) { throw new NotImplementedException(); }
/// <summary> /// Connect to a share indicated by shareName in server /// This will use smb over tcp as transport. Only one server /// can be connected at one time /// </summary> /// <param name="serverName">The server Name</param> /// <param name="port">The server port</param> /// <param name="ipVersion">The ip version</param> /// <param name="domain">The domain name</param> /// <param name="userName">The user name</param> /// <param name="password">The password</param> /// <param name="shareName">The share name</param> /// <param name="securityPackage">The security package</param> /// <param name="useServerToken">Whether to use token from server</param> /// <exception cref="System.InvalidOperationException">Thrown if there is any error occurred</exception> public abstract void ConnectShare(string serverName, int port, IpVersion ipVersion, string domain, string userName, string password, string shareName, SecurityPackageType securityPackage, bool useServerToken);
/// <summary> /// Use TestInitialize to run code before running the test in the class. /// </summary> protected override void TestInitialize() { base.TestInitialize(); this.ISMBAdapterInstance = Site.GetAdapter<ISmbAdapter>(); this.IServerSetupAdapterInstance = Site.GetAdapter<IServerSetupAdapter>(); smbClientStack = new SmbClient(); serverName = Site.Properties["SutMachineName"]; serverPort = int.Parse(Site.Properties["SutPort"]); string ip = Site.Properties["SmbTransportIpVersion"]; switch (ip.ToLower()) { case "ipv4": ipVersion = IpVersion.Ipv4; break; case "ipv6": ipVersion = IpVersion.Ipv6; break; default: ipVersion = IpVersion.Any; break; } bufferSize = int.Parse(Site.Properties["SmbTransportBufferSize"]); domainName = Site.Properties["SutLoginDomain"]; userName = Site.Properties["SutLoginAdminUserName"]; password = Site.Properties["SutLoginAdminPwd"]; string ptfSutOs = Site.Properties["SutPlatformOS"].ToString(); if (Enum.Parse(typeof(Platform), ptfSutOs, true) != null) { sutOsVersion = (Platform)Enum.Parse(typeof(Platform), ptfSutOs, true); } else { sutOsVersion = Platform.NonWindows; } }
public async Task Should_return_ip_endpoint_when_given_hostname(string hostname, string expectedIpAddress, IpVersion ipVersion, AddressFamily addressFamily) { var sut = new DnsResolver(); var endpoint = await sut.ResolveAsync(hostname, 21, ipVersion); endpoint.Should().BeOfType <IPEndPoint>(); var ipEndpoint = endpoint; ipEndpoint.Address.ToString().Should().Be(expectedIpAddress); ipEndpoint.AddressFamily.Should().Be(addressFamily); }
/// <summary> /// Private constructor used for deserialization. /// </summary> private IpPacket(IpVersion version, byte ihl, byte dscp, ushort totalLength, ushort identification, IpFlag flags, ushort fragmentOffset, byte ttl, IpProtocol protocol, ushort checksum, IpAddress source, IpAddress destination) { destination.ThrowIfNull("destination"); source.ThrowIfNull("source"); if (ihl > 0x0F) throw new ArgumentException("The Internet Header Length field must " + "be in the range from 0 to 15.", nameof(ihl)); if (fragmentOffset > 0x1FFF) throw new ArgumentException("The Fragment Offset field must be in " + "the range from 0 to 8191.", nameof(fragmentOffset)); Version = version; Ihl = ihl; Dscp = dscp; TotalLength = totalLength; Identification = identification; Flags = flags; FragmentOffset = fragmentOffset; TimeToLive = ttl; Protocol = protocol; Checksum = checksum; Source = source; Destination = destination; Data = new byte[0]; }
/// <summary> /// Connect to a share indicated by shareName in server /// This will use smb over tcp as transport. Only one server /// can be connected at one time /// </summary> /// <param name="serverName">The server Name</param> /// <param name="port">The server port</param> /// <param name="ipVersion">The ip version</param> /// <param name="domain">The domain name</param> /// <param name="userName">The user name</param> /// <param name="password">The password</param> /// <param name="shareName">The share name</param> /// <param name="securityPackage">The security package</param> /// <param name="useServerToken">Whether to use token from server</param> /// <exception cref="System.InvalidOperationException">Thrown if there is any error occurred</exception> public override void ConnectShare(string serverName, int port, IpVersion ipVersion, string domain, string userName, string password, string shareName, SecurityPackageType securityPackage, bool useServerToken) { smbClient.Connect(serverName, port, ipVersion, defaultBufferSize); InternalConnectShare(serverName, domain, userName, password, shareName, securityPackage); }
/// <summary> /// Connect to a share indicated by shareName in server /// This will use smb over tcp as transport. Only one server /// can be connected at one time /// </summary> /// <param name="serverName">The server Name</param> /// <param name="port">The server port</param> /// <param name="ipVersion">The ip version</param> /// <param name="domain">The domain name</param> /// <param name="userName">The user name</param> /// <param name="password">The password</param> /// <param name="shareName">The share name</param> /// <param name="securityPackage">The security package</param> /// <param name="useServerToken">Whether to use token from server</param> /// <exception cref="System.InvalidOperationException">Thrown if there is any error occurred</exception> public override void ConnectShare(string serverName, int port, IpVersion ipVersion, string domain, string userName, string password, string shareName, SecurityPackageType securityPackage, bool useServerToken) { IPHostEntry hostEntry = Dns.GetHostEntry(serverName); serverPrincipleName = Smb2Utility.GetPrincipleName(hostEntry.HostName); if (ipVersion == IpVersion.Ipv4) { foreach (var ip in hostEntry.AddressList) { if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { client.ConnectOverTCP(ip); break; } } } else if (ipVersion == IpVersion.Ipv6) { foreach (var ip in hostEntry.AddressList) { if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) { client.ConnectOverTCP(ip); break; } } } else { // if specified the IpVersion.Any, try ipv4 first, if failed, try ipv6 try { foreach (var ip in hostEntry.AddressList) { if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { client.ConnectOverTCP(ip); break; } } } catch (InvalidOperationException) { foreach (var ip in hostEntry.AddressList) { if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) { client.ConnectOverTCP(ip); break; } } } } if (!client.IsConnected) { throw new InvalidOperationException("No valid IP address can be used to connect to the server."); } InternalConnectShare(domain, userName, password, shareName, internalTimeout, securityPackage, useServerToken); }
public static bool IsIp(this string input, IpVersion version) => Validator.IsIp(input, version);
private static int FindProcessIdFromLocalPort(int port, IpVersion ipVersion) { var tcpRow = TcpHelper.GetTcpRowByLocalPort(ipVersion, port); return(tcpRow?.ProcessId ?? 0); }
/// <summary> /// Determine whether input is a valid IPv4 or IPv6 address. /// </summary> /// <param name="input"></param> /// <param name="version">Valid values are: IpVersion.Four and IpVersion.Six</param> /// <returns></returns> public static bool IsIp(string input, IpVersion version) { const string ipv4MaybePattern = @"^(\d?\d?\d)\.(\d?\d?\d)\.(\d?\d?\d)\.(\d?\d?\d)$"; const string ipv6Pattern = @"^::|^::1|^([a-fA-F0-9]{1,4}::?){1,7}([a-fA-F0-9]{1,4})$"; if (version == IpVersion.Four) { if (!Validator.Matches(input, ipv4MaybePattern)) { return false; } var parts = input.Split('.').Select(p => Convert.ToInt32(p)); return parts.Max() <= 255; } else { return Validator.Matches(input, ipv6Pattern); } }
/// <summary> /// to set up the tcp connection, and add the connection into context. Exception will be thrown if failed to /// set up connection with server. /// </summary> /// <param name = "serverName">the server name or server ip address to connect to </param> /// <param name = "serverPort">the port of server to connect to </param> /// <param name = "ipVersion">the ipversion to connect to server </param> /// <param name = "bufferSize">the buffer size of transport </param> /// <exception cref="InvalidOperationException"> /// Failed to get the IP address of SMB server in SmbClient(). /// </exception> public virtual void Connect(string serverName, int serverPort, IpVersion ipVersion, int bufferSize) { // initialize the config for transport SocketTransportConfig config = new SocketTransportConfig(); config.Role = Role.Client; config.Type = StackTransportType.Tcp; config.BufferSize = bufferSize; // init remote address of config #region Lookup the ip address from server name. IPHostEntry ipHostEntry = Dns.GetHostEntry(serverName); if (ipHostEntry != null) { foreach (IPAddress address in ipHostEntry.AddressList) { if (ipVersion != IpVersion.Ipv4 && address.AddressFamily == AddressFamily.InterNetworkV6) { config.LocalIpAddress = IPAddress.IPv6Any; config.RemoteIpAddress = address; break; } else if (ipVersion != IpVersion.Ipv6 && address.AddressFamily == AddressFamily.InterNetwork) { config.LocalIpAddress = IPAddress.Any; config.RemoteIpAddress = address; break; } else { continue; } } } if (config.RemoteIpAddress == null) { throw new InvalidOperationException("Failed to get the IP address of SMB server in SmbClient()."); } #endregion // init remote port config.RemoteIpPort = serverPort; // init local address of config config.LocalIpAddress = IPAddress.Any; config.LocalIpPort = 0; // init transport this.transport = new TransportStack(config, new SmbClientDecodePacket(this).DecodePacket); // connect to server. object endPointIdentity = this.transport.Connect(); // initialize the connection SmbClientConnection connection = new SmbClientConnection(); connection.ConnectionId = this.Context.GetConnectionID(endPointIdentity as IPEndPoint); connection.ConnectionState = StackTransportState.ConnectionEstablished; connection.MaxBufferSize = (uint)bufferSize; // update the context this.cifsClient.Context.AddOrUpdateConnection(connection); // update the connection id, to identity the connection instance. this.ConnectionId = connection.ConnectionId; // set the transport type this.capability.TransportType = TransportType.TCP; }
private static extern uint GetExtendedUdpTable(IntPtr pTcpTable, ref int dwOutBufLen, bool sort, IpVersion ipVersion, UdpTableClass tblClass, int reserved);
public async Task <IPEndPoint> ResolveAsync(string endpoint, int port, IpVersion ipVersion = IpVersion.IpV4, CancellationToken token = default(CancellationToken)) { string cacheKey = $"{endpoint}:{port}:{ipVersion}"; if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort) { throw new ArgumentOutOfRangeException(nameof(port)); } if (cache.HasKey(cacheKey)) { return(cache.Get <IPEndPoint>(cacheKey)); } var addressFamily = ipVersion.HasFlag(IpVersion.IpV4) ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6; token.ThrowIfCancellationRequested(); IPEndPoint ipEndpoint; var ipAddress = TryGetIpAddress(endpoint); if (ipAddress != null) { ipEndpoint = new IPEndPoint(ipAddress, port); cache.Add(cacheKey, ipEndpoint, TimeSpan.FromMinutes(60)); return(ipEndpoint); } try { #if NET40 var allAddresses = Dns.GetHostAddresses(endpoint); #else var allAddresses = await Dns.GetHostAddressesAsync(endpoint); #endif var firstAddressInFamily = allAddresses.FirstOrDefault(x => x.AddressFamily == addressFamily); if (firstAddressInFamily != null) { ipEndpoint = new IPEndPoint(firstAddressInFamily, port); cache.Add(cacheKey, ipEndpoint, TimeSpan.FromMinutes(60)); return(ipEndpoint); } if (addressFamily == AddressFamily.InterNetwork && ipVersion.HasFlag(IpVersion.IpV6)) { ipEndpoint = await ResolveAsync(endpoint, port, IpVersion.IpV6, token); if (ipEndpoint != null) { cache.Add(cacheKey, ipEndpoint, TimeSpan.FromMinutes(60)); return(ipEndpoint); } } var firstAddress = allAddresses.FirstOrDefault(); if (firstAddress == null) { return(null); } switch (firstAddress.AddressFamily) { case AddressFamily.InterNetwork: #if NET40 ipEndpoint = new IPEndPoint(firstAddress, port); #else ipEndpoint = new IPEndPoint(firstAddress.MapToIPv6(), port); #endif break; case AddressFamily.InterNetworkV6: #if NET40 ipEndpoint = new IPEndPoint(firstAddress, port); #else ipEndpoint = new IPEndPoint(firstAddress.MapToIPv4(), port); #endif break; default: return(null); } cache.Add(cacheKey, ipEndpoint, TimeSpan.FromMinutes(60)); return(ipEndpoint); } catch { return(null); } }