Package java.net
Class DatagramSocket
- java.lang.Object
-
- java.net.DatagramSocket
-
- All Implemented Interfaces:
Closeable,AutoCloseable
- Direct Known Subclasses:
MulticastSocket
public class DatagramSocket extends Object implements Closeable
This class implements a UDP socket for sending and receivingDatagramPacket. ADatagramSocketobject can be used for both endpoints of a connection for a packet delivery service.- See Also:
DatagramPacket,DatagramSocketImplFactory
-
-
Constructor Summary
Constructors Modifier Constructor Description DatagramSocket()Constructs a UDP datagram socket which is bound to any available port on the local host using a wildcard address.DatagramSocket(int aPort)Constructs a UDP datagram socket which is bound to the specific portaPorton the local host using a wildcard address.DatagramSocket(int aPort, InetAddress addr)Constructs a UDP datagram socket which is bound to the specific local addressaddron portaPort.protectedDatagramSocket(DatagramSocketImpl socketImpl)Constructs a newDatagramSocketusing the specific datagram socket implementationsocketImpl.DatagramSocket(SocketAddress localAddr)Constructs a newDatagramSocketbound to the host/port specified by theSocketAddresslocalAddror an unboundDatagramSocketif theSocketAddressisnull.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description voidbind(SocketAddress localAddr)Binds this socket to the local address and port specified bylocalAddr.voidclose()Closes this UDP datagram socket and all possibly associated channels.voidconnect(InetAddress address, int port)Connects this datagram socket to the specificaddressandport.voidconnect(SocketAddress peer)Connects this datagram socket to the address and port specified bypeer.voiddisconnect()Disconnects this UDP datagram socket from the remote host.booleangetBroadcast()Gets the state of the socket optionSocketOptions.SO_BROADCAST.DatagramChannelgetChannel()Returns this socket'sDatagramChannel, if one exists.FileDescriptorgetFileDescriptor$()InetAddressgetInetAddress()Gets theInetAddressinstance representing the remote address to which this UDP datagram socket is connected.InetAddressgetLocalAddress()Returns the local address to which this socket is bound, a wildcard address if this socket is not yet bound, ornullif this socket is closed.intgetLocalPort()Gets the local port which this socket is bound to.SocketAddressgetLocalSocketAddress()Returns theSocketAddressthis socket is bound to, ornullfor an unbound or closed socket.intgetPort()Gets the remote port which this socket is connected to.intgetReceiveBufferSize()Returns this socket'sreceive buffer size.SocketAddressgetRemoteSocketAddress()Returns theSocketAddressthis socket is connected to, or null for an unconnected socket.booleangetReuseAddress()Gets the state of the socket optionSocketOptions.SO_REUSEADDR.booleangetReusePort()Gets the state of the socket optionSocketOptions.SO_REUSEPORT.intgetSendBufferSize()Returns this socket'ssend buffer size.intgetSoTimeout()Gets the socketreceive timeout.intgetTrafficClass()Returns this socket's {@see SocketOptions#IP_TOS} setting.booleanisBound()Returns true if this socket is bound to a local address.booleanisClosed()Gets the state of this socket.booleanisConnected()Returns true if this datagram socket is connected to a remote address.voidonBind(InetAddress localAddress, int localPort)Sets the DatagramSocket and its related DatagramSocketImpl state as if a successful bind() took place, without actually performing an OS bind().voidonClose()Sets the DatagramSocket and its related DatagramSocketImpl state as if a successful close() took place, without actually performing an OS close().voidonConnect(InetAddress remoteAddress, int remotePort)Sets the DatagramSocket and its related DatagramSocketImpl state as if a successful connect() took place, without actually performing an OS connect().voidonDisconnect()Sets the DatagramSocket and its related DatagramSocketImpl state as if a successful disconnect() took place, without actually performing a disconnect().voidreceive(DatagramPacket pack)Receives a packet from this socket and stores it in the argumentpack.voidsend(DatagramPacket pack)Sends a packet over this socket.voidsetBroadcast(boolean broadcast)Sets the socket optionSocketOptions.SO_BROADCAST.static voidsetDatagramSocketImplFactory(DatagramSocketImplFactory fac)Sets the socket implementation factory.voidsetNetworkInterface(NetworkInterface netInterface)Sets the network interface used by this socket.voidsetReceiveBufferSize(int size)Sets this socket'sreceive buffer size.voidsetReuseAddress(boolean reuse)Sets the socket optionSocketOptions.SO_REUSEADDR.voidsetReusePort(boolean reuse)Sets the socket optionSocketOptions.SO_REUSEPORT.voidsetSendBufferSize(int size)Sets this socket'ssend buffer size.voidsetSoTimeout(int timeout)Sets theread timeoutin milliseconds for this socket.voidsetTrafficClass(int value)Sets the {@see SocketOptions#IP_TOS} value for every packet sent by this socket.
-
-
-
Constructor Detail
-
DatagramSocket
public DatagramSocket() throws SocketExceptionConstructs a UDP datagram socket which is bound to any available port on the local host using a wildcard address.- Throws:
SocketException- if an error occurs while creating or binding the socket.
-
DatagramSocket
public DatagramSocket(int aPort) throws SocketExceptionConstructs a UDP datagram socket which is bound to the specific portaPorton the local host using a wildcard address. Valid values foraPortare between 0 and 65535 inclusive.- Parameters:
aPort- the port to bind on the local host.- Throws:
SocketException- if an error occurs while creating or binding the socket.
-
DatagramSocket
public DatagramSocket(int aPort, InetAddress addr) throws SocketExceptionConstructs a UDP datagram socket which is bound to the specific local addressaddron portaPort. Valid values foraPortare between 0 and 65535 inclusive. Ifaddrisnullthe socket will be bound to a wildcard address.- Parameters:
aPort- the port to bind on the local host.addr- the address to bind on the local host.- Throws:
SocketException- if an error occurs while creating or binding the socket.
-
DatagramSocket
protected DatagramSocket(DatagramSocketImpl socketImpl)
Constructs a newDatagramSocketusing the specific datagram socket implementationsocketImpl. The createdDatagramSocketwill not be bound.- Parameters:
socketImpl- the DatagramSocketImpl to use.
-
DatagramSocket
public DatagramSocket(SocketAddress localAddr) throws SocketException
Constructs a newDatagramSocketbound to the host/port specified by theSocketAddresslocalAddror an unboundDatagramSocketif theSocketAddressisnull.- Parameters:
localAddr- the local machine address and port to bind to.- Throws:
IllegalArgumentException- if the SocketAddress is not supportedSocketException- if a problem occurs creating or binding the socket.
-
-
Method Detail
-
close
public void close()
Closes this UDP datagram socket and all possibly associated channels.- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable
-
onClose
public void onClose()
Sets the DatagramSocket and its related DatagramSocketImpl state as if a successful close() took place, without actually performing an OS close().
-
disconnect
public void disconnect()
Disconnects this UDP datagram socket from the remote host. This method called on an unconnected socket does nothing.
-
onDisconnect
public void onDisconnect()
Sets the DatagramSocket and its related DatagramSocketImpl state as if a successful disconnect() took place, without actually performing a disconnect().
-
getInetAddress
public InetAddress getInetAddress()
Gets theInetAddressinstance representing the remote address to which this UDP datagram socket is connected.- Returns:
- the remote address this socket is connected to or
nullif this socket is not connected.
-
getLocalAddress
public InetAddress getLocalAddress()
Returns the local address to which this socket is bound, a wildcard address if this socket is not yet bound, ornullif this socket is closed.
-
getLocalPort
public int getLocalPort()
Gets the local port which this socket is bound to.- Returns:
- the local port of this socket or
-1if this socket is closed and0if it is unbound.
-
getPort
public int getPort()
Gets the remote port which this socket is connected to.- Returns:
- the remote port of this socket. The return value
-1indicates that this socket is not connected.
-
getReceiveBufferSize
public int getReceiveBufferSize() throws SocketExceptionReturns this socket'sreceive buffer size.- Throws:
SocketException
-
getSendBufferSize
public int getSendBufferSize() throws SocketExceptionReturns this socket'ssend buffer size.- Throws:
SocketException
-
getSoTimeout
public int getSoTimeout() throws SocketExceptionGets the socketreceive timeout.- Throws:
SocketException- if an error occurs while getting the option value.
-
receive
public void receive(DatagramPacket pack) throws IOException
Receives a packet from this socket and stores it in the argumentpack. All fields ofpackmust be set according to the data received. If the received data is longer than the packet buffer size it is truncated. This method blocks until a packet is received or a timeout has expired.- Parameters:
pack- theDatagramPacketto store the received data.- Throws:
IOException- if an error occurs while receiving the packet.
-
send
public void send(DatagramPacket pack) throws IOException
Sends a packet over this socket.- Parameters:
pack- theDatagramPacketwhich has to be sent.- Throws:
IOException- if an error occurs while sending the packet.
-
setNetworkInterface
public void setNetworkInterface(NetworkInterface netInterface) throws SocketException
Sets the network interface used by this socket. Any packets sent via this socket are transmitted via the specified interface. Any packets received by this socket will come from the specified interface. Broadcast datagrams received on this interface will be processed by this socket. This corresponds to Linux's SO_BINDTODEVICE.- Throws:
SocketException
-
setSendBufferSize
public void setSendBufferSize(int size) throws SocketExceptionSets this socket'ssend buffer size.- Throws:
SocketException
-
setReceiveBufferSize
public void setReceiveBufferSize(int size) throws SocketExceptionSets this socket'sreceive buffer size.- Throws:
SocketException
-
setSoTimeout
public void setSoTimeout(int timeout) throws SocketExceptionSets theread timeoutin milliseconds for this socket. This receive timeout defines the period the socket will block waiting to receive data before throwing anInterruptedIOException. The value0(default) is used to set an infinite timeout. To have effect this option must be set before the blocking method was called.- Parameters:
timeout- the timeout in milliseconds or 0 for no timeout.- Throws:
SocketException- if an error occurs while setting the option.
-
setDatagramSocketImplFactory
public static void setDatagramSocketImplFactory(DatagramSocketImplFactory fac) throws IOException
Sets the socket implementation factory. This may only be invoked once over the lifetime of the application. This factory is used to create a new datagram socket implementation.- Parameters:
fac- the socket factory to use.- Throws:
IOException- if the factory has already been set.- See Also:
DatagramSocketImplFactory
-
bind
public void bind(SocketAddress localAddr) throws SocketException
Binds this socket to the local address and port specified bylocalAddr. If this value isnullany free port on a valid local address is used.- Parameters:
localAddr- the local machine address and port to bind on.- Throws:
IllegalArgumentException- if the SocketAddress is not supportedSocketException- if the socket is already bound or a problem occurs during binding.
-
onBind
public void onBind(InetAddress localAddress, int localPort)
Sets the DatagramSocket and its related DatagramSocketImpl state as if a successful bind() took place, without actually performing an OS bind().
-
connect
public void connect(SocketAddress peer) throws SocketException
Connects this datagram socket to the address and port specified bypeer. Future calls tosend(java.net.DatagramPacket)will use this as the default target, andreceive(java.net.DatagramPacket)will only accept packets from this source.- Throws:
SocketException- if an error occurs.
-
onConnect
public void onConnect(InetAddress remoteAddress, int remotePort)
Sets the DatagramSocket and its related DatagramSocketImpl state as if a successful connect() took place, without actually performing an OS connect().
-
connect
public void connect(InetAddress address, int port)
Connects this datagram socket to the specificaddressandport. Future calls tosend(java.net.DatagramPacket)will use this as the default target, andreceive(java.net.DatagramPacket)will only accept packets from this source.Beware: because it can't throw, this method silently ignores failures. Use
connect(SocketAddress)instead.
-
isBound
public boolean isBound()
Returns true if this socket is bound to a local address. Seebind(java.net.SocketAddress).
-
isConnected
public boolean isConnected()
Returns true if this datagram socket is connected to a remote address. Seeconnect(java.net.SocketAddress).
-
getRemoteSocketAddress
public SocketAddress getRemoteSocketAddress()
Returns theSocketAddressthis socket is connected to, or null for an unconnected socket.
-
getLocalSocketAddress
public SocketAddress getLocalSocketAddress()
Returns theSocketAddressthis socket is bound to, ornullfor an unbound or closed socket.
-
setReuseAddress
public void setReuseAddress(boolean reuse) throws SocketExceptionSets the socket optionSocketOptions.SO_REUSEADDR. This option has to be enabled if more than one UDP socket wants to be bound to the same address. That could be needed for receiving multicast packets.There is an undefined behavior if this option is set after the socket is already bound.
- Parameters:
reuse- the socket option value to enable or disable this option.- Throws:
SocketException- if the socket is closed or the option could not be set.
-
getReuseAddress
public boolean getReuseAddress() throws SocketExceptionGets the state of the socket optionSocketOptions.SO_REUSEADDR.- Returns:
trueif the option is enabled,falseotherwise.- Throws:
SocketException- if the socket is closed or the option is invalid.
-
setReusePort
public void setReusePort(boolean reuse) throws SocketExceptionSets the socket optionSocketOptions.SO_REUSEPORT. This option has to be enabled if more than one UDP socket wants to be bound to the same address. That could be needed for receiving multicast packets.There is an undefined behavior if this option is set after the socket is already bound.
- Parameters:
reuse- the socket option value to enable or disable this option.- Throws:
SocketException- if the socket is closed or the option could not be set.
-
getReusePort
public boolean getReusePort() throws SocketExceptionGets the state of the socket optionSocketOptions.SO_REUSEPORT.- Returns:
trueif the option is enabled,falseotherwise.- Throws:
SocketException- if the socket is closed or the option is invalid.
-
setBroadcast
public void setBroadcast(boolean broadcast) throws SocketExceptionSets the socket optionSocketOptions.SO_BROADCAST. This option must be enabled to send broadcast messages.- Parameters:
broadcast- the socket option value to enable or disable this option.- Throws:
SocketException- if the socket is closed or the option could not be set.
-
getBroadcast
public boolean getBroadcast() throws SocketExceptionGets the state of the socket optionSocketOptions.SO_BROADCAST.- Returns:
trueif the option is enabled,falseotherwise.- Throws:
SocketException- if the socket is closed or the option is invalid.
-
setTrafficClass
public void setTrafficClass(int value) throws SocketExceptionSets the {@see SocketOptions#IP_TOS} value for every packet sent by this socket.- Throws:
SocketException- if the socket is closed or the option could not be set.
-
getTrafficClass
public int getTrafficClass() throws SocketExceptionReturns this socket's {@see SocketOptions#IP_TOS} setting.- Throws:
SocketException- if the socket is closed or the option is invalid.
-
isClosed
public boolean isClosed()
Gets the state of this socket.- Returns:
trueif the socket is closed,falseotherwise.
-
getChannel
public DatagramChannel getChannel()
Returns this socket'sDatagramChannel, if one exists. A channel is available only if this socket wraps a channel. (That is, you can go from a channel to a socket and back again, but you can't go from an arbitrary socket to a channel.) In practice, this means that the socket must have been created byDatagramChannel.open().
-
getFileDescriptor$
public final FileDescriptor getFileDescriptor$()
-
-