Inheritance: java.net.SocketAddress
コード例 #1
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: @Override protected void connect(SocketAddress endpoint, int timeout) throws java.io.IOException
        protected internal override void Connect(SocketAddress endpoint, int timeout)
        {
            if (endpoint == null || !(endpoint is InetSocketAddress))
            {
                throw new IllegalArgumentException("Unsupported address type");
            }
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final InetSocketAddress epoint = (InetSocketAddress)endpoint;
            InetSocketAddress epoint = (InetSocketAddress)endpoint;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final String destHost = epoint.isUnresolved() ? epoint.getHostName() : epoint.getAddress().getHostAddress();
            String destHost = epoint.Unresolved ? epoint.HostName : epoint.Address.HostAddress;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int destPort = epoint.getPort();
            int destPort = epoint.Port;

            SecurityManager security = System.SecurityManager;

            if (security != null)
            {
                security.CheckConnect(destHost, destPort);
            }

            // Connect to the HTTP proxy server
            String urlString  = "http://" + destHost + ":" + destPort;
            Socket httpSocket = PrivilegedDoTunnel(urlString, timeout);

            // Success!
            External_address = epoint;

            // close the original socket impl and release its descriptor
            Close();

            // update the Sockets impl to the impl from the http Socket
            AbstractPlainSocketImpl psi = (AbstractPlainSocketImpl)httpSocket.Impl_Renamed;

            this.Socket.Impl_Renamed = psi;

            // best effort is made to try and reset options previously set
//JAVA TO C# CONVERTER TODO TASK: There is no .NET Dictionary equivalent to the Java 'entrySet' method:
            Set <java.util.Map_Entry <Integer, Object> > options = OptionsMap.entrySet();

            try
            {
                foreach (java.util.Map_Entry <Integer, Object> entry in options)
                {
                    psi.SetOption(entry.Key, entry.Value);
                }
            }             // gulp!
            catch (IOException)
            {
            }
        }
コード例 #2
0
        ///
        /// <summary>
        /// Binds the {@code ServerSocket} to a specific address
        /// (IP address and port number).
        /// <para>
        /// If the address is {@code null}, then the system will pick up
        /// an ephemeral port and a valid local address to bind the socket.
        /// <P>
        /// The {@code backlog} argument is the requested maximum number of
        /// pending connections on the socket. Its exact semantics are implementation
        /// specific. In particular, an implementation may impose a maximum length
        /// or may choose to ignore the parameter altogther. The value provided
        /// should be greater than {@code 0}. If it is less than or equal to
        /// {@code 0}, then an implementation specific default will be used.
        /// </para>
        /// </summary>
        /// <param name="endpoint">        The IP address and port number to bind to. </param>
        /// <param name="backlog">         requested maximum length of the queue of
        ///                          incoming connections. </param>
        /// <exception cref="IOException"> if the bind operation fails, or if the socket
        ///                     is already bound. </exception>
        /// <exception cref="SecurityException">       if a {@code SecurityManager} is present and
        /// its {@code checkListen} method doesn't allow the operation. </exception>
        /// <exception cref="IllegalArgumentException"> if endpoint is a
        ///          SocketAddress subclass not supported by this socket
        /// @since 1.4 </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void bind(SocketAddress endpoint, int backlog) throws java.io.IOException
        public virtual void Bind(SocketAddress endpoint, int backlog)
        {
            if (Closed)
            {
                throw new SocketException("Socket is closed");
            }
            if (!OldImpl && Bound)
            {
                throw new SocketException("Already bound");
            }
            if (endpoint == null)
            {
                endpoint = new InetSocketAddress(0);
            }
            if (!(endpoint is InetSocketAddress))
            {
                throw new IllegalArgumentException("Unsupported address type");
            }
            InetSocketAddress epoint = (InetSocketAddress)endpoint;

            if (epoint.Unresolved)
            {
                throw new SocketException("Unresolved address");
            }
            if (backlog < 1)
            {
                backlog = 50;
            }
            try
            {
                SecurityManager security = System.SecurityManager;
                if (security != null)
                {
                    security.CheckListen(epoint.Port);
                }
                Impl.Bind(epoint.Address, epoint.Port);
                Impl.Listen(backlog);
                Bound_Renamed = true;
            }
            catch (SecurityException e)
            {
                Bound_Renamed = false;
                throw e;
            }
            catch (IOException e)
            {
                Bound_Renamed = false;
                throw e;
            }
        }
コード例 #3
0
        internal HttpConnectSocketImpl(Proxy proxy)
        {
            SocketAddress a = proxy.Address();

            if (!(a is InetSocketAddress))
            {
                throw new IllegalArgumentException("Unsupported address type");
            }

            InetSocketAddress ad = (InetSocketAddress)a;

            Server       = ad.HostString;
            Port_Renamed = ad.Port;
        }
コード例 #4
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: void socketAccept(SocketImpl s) throws java.io.IOException
        internal override void SocketAccept(SocketImpl s)
        {
            int nativefd = CheckAndReturnNativeFD();

            if (s == null)
            {
                throw new NullPointerException("socket is null");
            }

            int newfd = -1;

            InetSocketAddress[] isaa = new InetSocketAddress[1];
            if (Timeout_Renamed <= 0)
            {
                newfd = accept0(nativefd, isaa);
            }
            else
            {
                configureBlocking(nativefd, false);
                try
                {
                    waitForNewConnection(nativefd, Timeout_Renamed);
                    newfd = accept0(nativefd, isaa);
                    if (newfd != -1)
                    {
                        configureBlocking(newfd, true);
                    }
                }
                finally
                {
                    configureBlocking(nativefd, true);
                }
            }
            /* Update (SocketImpl)s' fd */
            FdAccess.set(s.Fd, newfd);
            /* Update socketImpls remote port, address and localport */
            InetSocketAddress isa = isaa[0];

            s.Port_Renamed = isa.Port;
            s.Address      = isa.Address;
            s.Localport    = Localport;
        }
コード例 #5
0
        /// <summary>
        /// Creates a socket and connects it to the specified address on
        /// the specified port. </summary>
        /// <param name="address"> the address </param>
        /// <param name="timeout"> the timeout value in milliseconds, or zero for no timeout. </param>
        /// <exception cref="IOException"> if connection fails </exception>
        /// <exception cref="IllegalArgumentException"> if address is null or is a
        ///          SocketAddress subclass not supported by this socket
        /// @since 1.4 </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: protected void connect(SocketAddress address, int timeout) throws java.io.IOException
        protected internal override void Connect(SocketAddress address, int timeout)
        {
            bool connected = false;

            try
            {
                if (address == null || !(address is InetSocketAddress))
                {
                    throw new IllegalArgumentException("unsupported address type");
                }
                InetSocketAddress addr = (InetSocketAddress)address;
                if (addr.Unresolved)
                {
                    throw new UnknownHostException(addr.HostName);
                }
                this.Port_Renamed = addr.Port;
                this.Address      = addr.Address;

                ConnectToAddress(this.Address, Port_Renamed, timeout);
                connected = true;
            }
            finally
            {
                if (!connected)
                {
                    try
                    {
                        Close();
                    }
                    catch (IOException)
                    {
                        /* Do nothing. If connect threw an exception then
                         * it will be passed up the call stack */
                    }
                }
            }
        }
コード例 #6
0
ファイル: sun.nio.ch.cs プロジェクト: gongfuPanada/ikvm-fork
    public static int send0(object obj, bool preferIPv6, FileDescriptor fd, byte[] buf, int pos, int len, object sa)
    {
#if FIRST_PASS
        return(0);
#else
        java.net.InetSocketAddress addr = (java.net.InetSocketAddress)sa;
        try
        {
            return(fd.getSocket().SendTo(buf, pos, len, System.Net.Sockets.SocketFlags.None, new System.Net.IPEndPoint(java.net.SocketUtil.getAddressFromInetAddress(addr.getAddress(), preferIPv6), addr.getPort())));
        }
        catch (System.Net.Sockets.SocketException x)
        {
            if (x.ErrorCode == java.net.SocketUtil.WSAEWOULDBLOCK)
            {
                return(sun.nio.ch.IOStatus.UNAVAILABLE);
            }
            throw java.net.SocketUtil.convertSocketExceptionToIOException(x);
        }
        catch (ObjectDisposedException)
        {
            throw new java.net.SocketException("Socket is closed");
        }
#endif
    }
コード例 #7
0
        protected override void onCreate(Bundle savedInstanceState)
        {
            base.onCreate(savedInstanceState);

            var sv = new ScrollView(this);
            var b2 = new Button(this);
            {
                var ll = new LinearLayout(this);
                //ll.setOrientation(LinearLayout.VERTICAL);
                sv.addView(ll);

                var b1 = new Button(this).AttachTo(ll);



                b1.WithText("LANBroadcastListener createMulticastLock");


                var c = 0;

                b1.AtClick(
                    v =>
                    {
                        //                 server error { Message = , StackTrace = android.os.NetworkOnMainThreadException
                        //at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
                        //at libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:175)
                        //at libcore.io.IoBridge.sendto(IoBridge.java:473)
                        //at java.net.PlainDatagramSocketImpl.send(PlainDatagramSocketImpl.java:182)
                        //at java.net.DatagramSocket.send(DatagramSocket.java:284)

                        new Thread(
                            delegate()
                            {

                                try
                                {
                                    var socket = new DatagramSocket(); //construct a datagram socket and binds it to the available port and the localhos

                                    c++;

                                    var b = Encoding.UTF8.GetBytes(c + " hi from jvm!");    //creates a variable b of type byte
                                    var dgram = new DatagramPacket((sbyte[])(object)b, b.Length, InetAddress.getByName("239.1.2.3"), 40404);//sends the packet details, length of the packet,destination address and the port number as parameters to the DatagramPacket  
                                    //dgram.setData(b);
                                    //System.Console.WriteLine(
                                    //    "Sending " + b.Length + " bytes to " + dgram.getAddress() + ":" + dgram.getPort());//standard error output stream
                                    socket.send(dgram); //send the datagram packet from this port
                                }
                                catch (Exception ex)
                                {
                                    System.Console.WriteLine("server error " + new { ex.Message, ex.StackTrace });
                                }

                            }
                                )
                               {

                                   Name = "sender"
                               }.Start();
                    }
                );

                b2.setText("The other button!");
                ll.addView(b2);

                this.setContentView(sv);
            }


            // http://www.zzzxo.com/q/answers-android-device-not-receiving-multicast-package-13221736.html



            new Thread(
                delegate()
                {
                    // http://stackoverflow.com/questions/12610415/multicast-receiver-malfunction
                    // http://answers.unity3d.com/questions/250732/android-build-is-not-receiving-udp-broadcasts.html

                    // Acquire multicast lock
                    wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
                    multicastLock = wifi.createMulticastLock("multicastLock");
                    //multicastLock.setReferenceCounted(true);
                    multicastLock.acquire();

                    System.Console.WriteLine("LANBroadcastListener ready...");
                    try
                    {
                        byte[] b = new byte[0x100];

                        // https://code.google.com/p/android/issues/detail?id=40003

                        var port = 40404;

                        MulticastSocket socket = new MulticastSocket(port); // must bind receive side
                        socket.setBroadcast(true);
                        socket.setReuseAddress(true);
                        socket.setTimeToLive(30);
                        socket.setReceiveBufferSize(0x100);
                        
                        // https://code.google.com/p/android/issues/detail?id=40003
                        // http://stackoverflow.com/questions/6550618/multicast-support-on-android-in-hotspot-tethering-mode
                        // http://www.massapi.com/class/java/net/InetSocketAddress.java.html
                        // http://www.javadocexamples.com/java/net/MulticastSocket/joinGroup(SocketAddress%20mcastaddr,NetworkInterface%20netIf).html
                        // http://grokbase.com/t/hadoop/common-issues/117jsjk8d7/jira-created-hadoop-7472-rpc-client-should-deal-with-the-ip-address-changes

                        var group = InetAddress.getByName("239.1.2.3");
                        var groupSockAddr = new InetSocketAddress(group, port);

                        // what lan interfaces do we have?
                        socket.joinGroup(groupSockAddr,
                            NetworkInterface.getByName("wlan0")
                        );

                        System.Console.WriteLine("LANBroadcastListener joinGroup...");
                        while (true)
                        {
                            DatagramPacket dgram = new DatagramPacket((sbyte[])(object)b, b.Length);
                            socket.receive(dgram); // blocks until a datagram is received

                            var bytes = new MemoryStream((byte[])(object)dgram.getData(), 0, dgram.getLength());


                            var listen = Encoding.UTF8.GetString(bytes.ToArray());

                            System.Console.WriteLine("Received "
                                + dgram.getLength()
                                + " bytes from " + dgram.getAddress());
                            //dgram.setLength(b.Length); // must reset length field!s



                        }
                    }
                    catch
                    {
                        System.Console.WriteLine("client error");
                    }
                }
            )
            {

                Name = "client"
            }.Start();

        }
コード例 #8
0
ファイル: sun.nio.ch.cs プロジェクト: cDoru/ikvm-fork
    public static int receive0(object obj, FileDescriptor fd, byte[] buf, int pos, int len, bool connected)
    {
#if FIRST_PASS
        return(0);
#else
        sun.nio.ch.DatagramChannelImpl impl          = (sun.nio.ch.DatagramChannelImpl)obj;
        java.net.SocketAddress         remoteAddress = impl.remoteAddress();
        System.Net.EndPoint            remoteEP;
        if (fd.getSocket().AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
        {
            remoteEP = new System.Net.IPEndPoint(System.Net.IPAddress.IPv6Any, 0);
        }
        else
        {
            remoteEP = new System.Net.IPEndPoint(0, 0);
        }
        java.net.InetSocketAddress addr;
        int length;
        do
        {
            for (; ;)
            {
                try
                {
                    length = fd.getSocket().ReceiveFrom(buf, pos, len, System.Net.Sockets.SocketFlags.None, ref remoteEP);
                    break;
                }
                catch (System.Net.Sockets.SocketException x)
                {
                    if (x.ErrorCode == java.net.SocketUtil.WSAECONNRESET)
                    {
                        // A previous send failed (i.e. the remote host responded with a ICMP that the port is closed) and
                        // the winsock stack helpfully lets us know this, but we only care about this when we're connected,
                        // otherwise we'll simply retry the receive (note that we use SIO_UDP_CONNRESET to prevent these
                        // WSAECONNRESET exceptions, but when switching from connected to disconnected, some can slip through).
                        if (connected)
                        {
                            throw new java.net.PortUnreachableException();
                        }
                        continue;
                    }
                    if (x.ErrorCode == java.net.SocketUtil.WSAEMSGSIZE)
                    {
                        // The buffer size was too small for the packet, ReceiveFrom receives the part of the packet
                        // that fits in the buffer and then throws an exception, so we have to ignore the exception in this case.
                        length = len;
                        break;
                    }
                    if (x.ErrorCode == java.net.SocketUtil.WSAEWOULDBLOCK)
                    {
                        return(sun.nio.ch.IOStatus.UNAVAILABLE);
                    }
                    throw java.net.SocketUtil.convertSocketExceptionToIOException(x);
                }
                catch (ObjectDisposedException)
                {
                    throw new java.net.SocketException("Socket is closed");
                }
            }
            System.Net.IPEndPoint ep = (System.Net.IPEndPoint)remoteEP;
            addr = new java.net.InetSocketAddress(java.net.SocketUtil.getInetAddressFromIPEndPoint(ep), ep.Port);
        } while (remoteAddress != null && !addr.equals(remoteAddress));
        impl.sender = addr;
        return(length);
#endif
    }