Search code examples
javatcpftpnetwork-protocolsapplication-layer

How to access information about network from TCP?


I am writing an application layer protocol in Java. It basically just transfers files. I would like it generate error messages if the transfer is unable to be completed or if the connection between the client and the server is interrupted.

Is there a way to get the information about the connection or status of the transfer from TCP? Or do I need to rely on what I'm working with at the application layer? If I can access information from TCP, how?


Solution

  • TCP is not aware of the "status" of a transfer. That is an application protocol concern, not a transport layer concern.

    As for the status of the TCP connection, there is no way to inquire directly. Instead, you find out the status when you attempt to read or write data. The outcome of the read(...) or `write(...) to gives some information about the connection status..

    • If read or write call indicates that it has read or written a non-zero number of bytes, then the connection is probably alive.

    • If a read that returns zero bytes indicates that the other end has closed their write side of the connection. However, we cannot tell if the remote application did that, the remote OS did that, or something in the network initiated the close.

    • If a read or write throws an exception, then we can infer that a problem occurred AND the connection is no longer viable. Exceptions that are possible in this context include:

      • SocketException - Typical messages "connection reset" or "pipe broken" which typically mean that the remote did something unexpected, or "socket closed" which means that the application has attempted to read or write on a connection that it has close.
      • SocketTimeoutException - Typically, this happens if a read has taken longer than the read timeout configured for the socket. Unfortunately, it cannot tell you anything about the underlying cause for the timeout.
      • ProtocolException - This is possible in theory for a socket i/o operation, but this exception is usually thrown by application protocol code.

    Unfortunately, this means that providing clear and accurate information to your application's user about why a transfer has failed is difficult. But this is inherent to network connections. The real problem is that simple / clear diagnostic information is not directly available anywhere.