Search code examples
javaslf4jsystemtime

Get system time from a remote pc


Is there a way to get the system time from a remote PC in java? The remote PC is in the same network as the client pc.

There are some clients with a java gui. The guis should log in the same file on the remote PC. For this I use the RollingFileAppender of the slf4j api. But I want, that the log time is the server time. The clients can have different times and they have no rights to change the clock.
So my idea was to get the remote pc server time, get the time difference and log with the server time.
But I can't find something similar.
The clients and the server does not have a internet connection. And I doesn't want to change someting at the server. Only if there is no other way.
The gui runs with java 1.6.

I know there are some ways with TCP connections. But for this I have to write and execute a server programm or install a NTP server.

Do you have any suggestions or ideas to solve my issue?


Solution

  • I found a solution for my problem.
    I activated the ntp server on windows.
    On gui startup I get the time difference from the remote pc to the client.

    NTPUDPClient client = new NTPUDPClient();
    client.setDefaultTimeout(5000);
    client.open();
    InetAddress hostAddr = InetAddress.getByName(confFile.getIpAddresse());
    TimeInfo info = client.getTime(hostAddr, 8110);
    info.computeDetails(); // compute offset/delay if not already done
    Long offsetValue = info.getOffset();
    Long delayValue = info.getDelay();
    String delay = (delayValue == null) ? "0" : delayValue.toString();
    String offset = (offsetValue == null) ? "0" : offsetValue.toString();
    System.out.println(" Roundtrip delay(ms)=" + delay + ", clock offset(ms)=" + offset); 
    // offset in ms
    client.close();
    StaticVariables.timeDifference = Long.parseLong(offset);  
    

    To modify the timestamp of the log4j logging, I created a custom RollingFileAppender:

    public class CustomRollingFileAppender extends RollingFileAppender
    {
        @Override
        protected void subAppend(LoggingEvent event)
        {
            LoggingEvent modifiedEvent = new LoggingEvent(event.getFQNOfLoggerClass(), event.getLogger(),
                    event.getTimeStamp() + StaticVariables.timeDifference, event.getLevel(), event.getMessage(), event.getThreadName(),
                    event.getThrowableInformation(), event.getNDC(), event.getLocationInformation(), event.getProperties());
    
            super.subAppend(modifiedEvent);
        }
    }
    

    In this appender I added the time difference event.getTimeStamp() + StaticVariables.timeDifference.