Socket Socket(String, int, InetAddress, int) in Java

Socket(String, int, InetAddress, int): This method is available in the java.net.Socket class of Java.

Syntax:

java.net.Socket.Socket(String host, int port, InetAddress localAddr, int localPort) throws IOException

This method takes four arguments. This method creates a socket and connects it to the specified remote host on the specified remote port. The Socket will also bind() to the local address and port supplied.

A local port number of zero will let the system pick up a free port in the bind operation.

Parameters: Four parameters are required for this method.

host: the name of the remote host, or null for the loopback address.

port: the remote port.

localAddr: the local address the socket is bound to, or null for any local address.

localPort: the local port the socket is bound to, or zero for a system-selected free port.

Throws:

1. IOException - if an I/O error occurs when creating the socket.

2. SecurityException - if a security manager exists and its checkConnect method doesn't allow the connection to the destination, or if its checkListen method doesn't allow the bind to the local port.

3. IllegalArgumentException - if the port parameter or localPort parameter is outside the specified range of valid port values, which is between 0 and 65535, inclusive.

Approach

Java

package com.Socket;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class Socket6 {
    public static void main(String[] args) throws UnknownHostException, IOException {

        String host = "java.sun.com";
        int port = 80;
        InetAddress localAddress = InetAddress.getLocalHost();
        int localPort = 8080;
        Socket socket = new Socket(host, port, localAddress, localPort);

        System.out.println(socket);
    }
}

Output:

Exception in thread "main" java.net.SocketException: Network is unreachable: connect at java.base/sun.nio.ch.Net.connect0(Native Method) at java.base/sun.nio.ch.Net.connect(Net.java:574) at java.base/sun.nio.ch.Net.connect(Net.java:563) at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:588) at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:333) at java.base/java.net.Socket.connect(Socket.java:648) at java.base/java.net.Socket.connect(Socket.java:597) at java.base/java.net.Socket.<init>(Socket.java:520) at java.base/java.net.Socket.<init>(Socket.java:370) at com.Socket.Socket6.main(Socket6.java:15)


Approach 2: IllegalArgumentException 

Java

package com.Socket;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class Socket6 {
    public static void main(String[] args) throws UnknownHostException, IOException {

        String host = "java.sun.com";
        int port = 80;
        InetAddress localAddress = InetAddress.getLocalHost();
        int localPort = 809980;
        Socket socket = new Socket(host, port, localAddress, localPort);

        System.out.println(socket);
    }
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: port out of range:809980 at java.base/java.net.InetSocketAddress.checkPort(InetSocketAddress.java:153) at java.base/java.net.InetSocketAddress.<init>(InetSocketAddress.java:198) at java.base/java.net.Socket.<init>(Socket.java:371) at com.Socket.Socket6.main(Socket6.java:15)


Some other methods of Socket class

Socket(): This method creates an unconnected Socket.

Socket(Proxy): This method creates an unconnected socket, specifying the type of proxy, if any, that should be used regardless of other settings.

Socket(InetAddress, int): This method creates a stream socket and connects it to the specified port number at the specified IP address.

Socket(String, int): This method creates a stream socket and connects it to the specified port number on the named host.

Socket(InetAddress, int, InetAddress, int): This method creates a socket and connects it to the specified remote address on the specified remote port. The Socket will bind() to the local address and port supplied.

Socket(String, int, InetAddress, int): This method creates a socket and connects it to the specified remote host on the specified remote port. The Socket will bind() to the local address and port supplied.

bind(SocketAddress):  This method binds the socket to a local address.

close(): This method closes this socket.

connect(SocketAddress): This method connects this socket to the server.

connect(SocketAddress, int): This method connects this socket to the server with a specified timeout value. A timeout of zero is interpreted as an infinite timeout.

getChannel(): This method returns the unique SocketChannelobject associated with this socket, if any.

getInetAddress(): This method returns the address to which the socket is connected.

getInputStream(): This method returns an input stream for this socket.

getKeepAlive(): This method tests if SO_KEEPALIVE is enabled.

getLocalAddress(): This method gets the local address to which the socket is bound.

getLocalPort(): This method returns the local port number to which this socket is bound.

getLocalSocketAddress(): This method returns the address of the endpoint this socket is bound to.

getOOBInline(): This method tests if SO_OOBINLINE is enabled.

getOption(SocketOption): This method returns the value of a socket option.

getOutputStream(): This method returns an output stream for this socket.

getPort(): This method returns the remote port number to which this socket is connected.

getReceiveBufferSize(): This method gets the value of the SO_RCVBUF option for this Socket, which is the buffer size used by the platform for input on this Socket.

getRemoteSocketAddress(): This method returns the address of the endpoint this socket is connected to, or null if it is unconnected.

getReuseAddress(): This method tests if SO_REUSEADDR is enabled.

getSendBufferSize(): This method gets the value of the SO_SNDBUF option for this Socket, which is the buffer size used by the platform for output on this Socket.

getSoLinger(): This method returns the setting for SO_LINGER.-1 returns implies that the option is disabled. The setting only affects socket closing.

getSoTimeout(): This method returns setting for SO_TIMEOUT.0 returns implies that the option is disabled (i.e., timeout of infinity).

getTcpNoDelay(): This method tests if TCP_NODELAY is enabled.

getTrafficClass(): This method gets the traffic class or type of service in the IP header for packets sent from this Socket.

isBound(): This method returns the binding state of the socket.

isClosed(): This method returns the closed state of the socket.

isConnected(): This method returns the connection state of the socket.

isInputShutdown(): This method returns whether the read-half of the socket connection is closed.

isOutputShutdown(): This method returns whether the write-half of the socket connection is closed.

sendUrgentData(int): This method sends one byte of urgent data to the socket. The byte to be sent is the lowest eight bits of the data parameter.

setKeepAlive(boolean): This method enables/disables SO_KEEPALIVE.

setOOBInline(boolean):  This method enables/disables SO_OOBINLINE By default, this option is disabled, and TCP urgent data received on a socket is silently discarded.

setOption(SocketOption, Object): This method sets the value of a socket option.

setPerformancePreferences(int, int, int): This method sets performance preferences for this socket.

setReceiveBufferSize(int): This method sets the SO_RCVBUF option to the specified value for this Socket. The SO_RCVBUF option is used by the platform's networking code as a hint for the size to set the underlying network I/O buffers.

setReuseAddress(boolean): This method enables/disables the SO_REUSEADDR socket option.

setSendBufferSize(int): This method sets the SO_SNDBUF option to the specified value for this Socket. 

Socket.setSocketImplFactory(SocketImplFactory):  This method sets the client socket implementation factory for the application. The factory can be specified only once.

setSoLinger(boolean, int): This method enables/disables SO_LINGER with the specified linger time in seconds.

setSoTimeout(int): This method enables/disables SO_TIMEOUT with the specified timeout, in milliseconds.

setTcpNoDelay(boolean): This method enables/disables TCP_NODELAY (disable/enable Nagle's algorithm).

setTrafficClass(int): This method sets the traffic class or type-of-service octet in the IP header for packets sent from this Socket.

shutdownInput(): This method places the input stream for this socket at the "end of stream".

shutdownOutput(): This method disables the output stream for this socket.

supportedOptions(): This method returns a set of the socket options supported by this socket. This method will continue to return the set of options even after the socket has been closed.

toString(): This method converts this socket to a String.

No comments:

Post a Comment