public virtual void TestAvoidLoopbackTcpSockets() { Configuration conf = new Configuration(); Socket socket = NetUtils.GetDefaultSocketFactory(conf).CreateSocket(); socket.Bind2(new IPEndPoint("127.0.0.1", 0)); System.Console.Error.WriteLine("local address: " + socket.GetLocalAddress()); System.Console.Error.WriteLine("local port: " + socket.GetLocalPort()); try { NetUtils.Connect(socket, new IPEndPoint(socket.GetLocalAddress(), socket.GetLocalPort ()), 20000); socket.Close(); NUnit.Framework.Assert.Fail("Should not have connected"); } catch (ConnectException ce) { System.Console.Error.WriteLine("Got exception: " + ce); Assert.True(ce.Message.Contains("resulted in a loopback")); } catch (SocketException se) { // Some TCP stacks will actually throw their own Invalid argument exception // here. This is also OK. Assert.True(se.Message.Contains("Invalid argument")); } }
/// <exception cref="System.IO.IOException"/> private void DoSocketReadTimeoutTest(bool withChannel) { // Binding a ServerSocket is enough to accept connections. // Rely on the backlog to accept for us. Socket ss = Extensions.CreateServerSocket(0); Socket s; if (withChannel) { s = NetUtils.GetDefaultSocketFactory(new Configuration()).CreateSocket(); Assume.AssumeNotNull(s.GetChannel()); } else { s = new Socket(); NUnit.Framework.Assert.IsNull(s.GetChannel()); } SocketInputWrapper stm = null; try { NetUtils.Connect(s, ss.LocalEndPoint, 1000); stm = NetUtils.GetInputStream(s, 1000); AssertReadTimeout(stm, 1000); // Change timeout, make sure it applies. stm.SetTimeout(1); AssertReadTimeout(stm, 1); // If there is a channel, then setting the socket timeout // should not matter. If there is not a channel, it will // take effect. s.ReceiveTimeout = 1000; if (withChannel) { AssertReadTimeout(stm, 1); } else { AssertReadTimeout(stm, 1000); } } finally { IOUtils.CloseStream(stm); IOUtils.CloseSocket(s); ss.Close(); } }