0

Is there a way through bash/nc/xinetd/nginx clever trickery to run a TCP server that only output Unix time then disconnect?

A client connects to the TCP server, and server outputs the unix time in string form, e.g. "1456860938", then server disconnects client.

Server should continue running to serve many clients, but the length of time for each connection is very short.

garbagecollector
  • 3,731
  • 5
  • 32
  • 44

2 Answers2

0

A quick python script might do the trick. I referenced this socket programming tutorial. This is purely TCP, not an HTTP server

'''
TCP Time Server
'''

import socket
import sys
import time
import signal

HOST = ''   # blank for All interfaces
PORT = 8000 # Port to listen on

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Signal handler to close the socket on exit
def signal_handler(signal, frame):
    s.close()
    sys.exit(0)

# Bind to port
try:
    s.bind((HOST, PORT))
    signal.signal(signal.SIGINT, signal_handler)
except socket.error as msg:
    print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
    sys.exit()

# Listen for connections
s.listen(1)

print('Ready to serve')

# Except connections forever
while 1:
    #wait to accept a connection - blocking call
    conn, addr = s.accept()
    conn.sendall(str(int(time.time())))
    conn.close()

Sample output:

$ nc localhost 8000
1456868540
Thomas Zwaagstra
  • 397
  • 4
  • 11
0

Assuming you're running a standard inetd, you can simply add date to /etc/inetd.conf thus:

daytime            stream tcp      nowait  nobody  /bin/date date +%s

After reloading (sudo pkill -HUP inetd), you can verify the result:

$ netcat localhost daytime
1456915174

(Obviously, use a port other than daytime if you already run a daemon there).

Toby Speight
  • 27,591
  • 48
  • 66
  • 103