Sponsored Content
Top Forums Programming can-not detect TCP disconnects well Post 302311049 by captwiggum on Monday 27th of April 2009 06:54:06 PM
Old 04-27-2009
Code:
"""
tcp_disconnect.py
Echo network data test program in python. This program easily translates to C & Java.

By TCP rules, the only way for a server program to know if a client has disconnected,
is to try to read from the socket. Specifically, if select() says there is data, but
recv() returns 0 bytes of data, then this implies the client has disconnected.

But a server program might want to confirm that a tcp client is still connected without
reading data. For example, before it performs some task or sends data to the client.
This program will demonstrate how to detect a TCP client disconnect without reading data.

The method to do this:
1) select on socket as poll (no wait)
2) if no recv data waiting, then client still connected
3) if recv data waiting, the read one char using PEEK flag 
4) if PEEK data len=0, then client has disconnected, otherwise its connected.
Note, the peek flag will read data without removing it from tcp queue.

To see it in action: 0) run this program on one computer 1) from another computer, 
connect via telnet port 12345, 2) type a line of data 3) wait to see it echo, 
4) type another line, 5) disconnect quickly, 6) watch the program will detect the 
disconnect and exit.

I hope this is helpful to someone. John Masinter, 17-Dec-2008.
"""

import socket
import time
import select

HOST = ''       # all local interfaces
PORT = 12345    # port to listen

# listen for new TCP connections
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(1)
# accept new conneciton
conn, addr = s.accept()
print 'Connected by', addr
# loop reading/echoing, until client disconnects
try:
    conn.send("Send me data, and I will echo it back after a short delay.\n")
    while 1:
        data = conn.recv(1024)                          # recv all data queued
        if not data: break                              # client disconnected
        time.sleep(3)                                   # simulate time consuming work
        # below will detect if client disconnects during sleep
        r, w, e = select.select([conn], [], [], 0)      # more data waiting?
        print "select: r=%s w=%s e=%s" % (r,w,e)        # debug output to command line
        if r:                                           # yes, data avail to read.
            t = conn.recv(1024, socket.MSG_PEEK)        # read without remove from queue
            print "peek: len=%d, data=%s" % (len(t),t)  # debug output
            if len(t)==0:                               # length of data peeked 0?
                print "Client disconnected."            # client disconnected
                break                                   # quit program
        conn.send("-->"+data)                           # echo only if still connected
finally:
    conn.close()

 

10 More Discussions You Might Find Interesting

1. AIX

aix telnet disconnects

We're having problems getting disconnected from AIX with our telnet sessions. I can't ping the server when this happens, either. Other serves can be pinged at the same time. This happens both at unix and within the database. Database locks remain when editing files. unix logins remain after... (0 Replies)
Discussion started by: e1lyons
0 Replies

2. AIX

Telnet disconnects on handheld device AIX

I have intermec handheld device which is connecting to AIX Server on port 12431 or whatever. ( oracle application ) The handheld device connects for few seconds and then disconnects from the AIX server. Once it disconnects the handheld device automatically switches off. Are there any... (2 Replies)
Discussion started by: filosophizer
2 Replies

3. Windows & DOS: Issues & Discussions

Putty disconnects after sometime

i am using Putty to do ssh to all the unix nodes that we have in our work environment. it is very strange that all my network connections will timeout quickly in 10 mins, it can either be a putty connection, sqlplus or toad. is there some setting that can help to prevent this. please let me know... (3 Replies)
Discussion started by: sudhiroracle
3 Replies

4. Programming

How detect TCP/IP socket shutdown when ethernet cable is disconnected

Hi, I want to code TCP/IP client/server in linux application capable to fastly detect ethernet cable disconnection in any condition. So I have activate SO_KEEPALIVE options and set TCP_KEEPCNT, TCP_KEEPIDLE and TCP_KEEPINTVL to 1. When I disconnect ethernet cable I have the following... (5 Replies)
Discussion started by: jeje_clb
5 Replies

5. Programming

Socket endpoints disconnects

Hello, I am able to establish a connection, and transfer data. Occasionally the receiving client will block in read(2) and stay that way until it is killed. initial: server: netstat -aveeopT tcp 0 0 *:17398 *:* LISTEN server-user... (8 Replies)
Discussion started by: eoa
8 Replies

6. Programming

[C++] [Unix] TCP non-blocking. Detect server disconnection procedure over, from client.

Hello! I searched forum for similar topic, with no luck, if you know one, delete this topic, and send me private message with link please. Little background: I have a lot of clients and one serwer. Client can make multiple connections on different ports and ips, but only one can be acctive... (2 Replies)
Discussion started by: ikeban
2 Replies

7. Red Hat

Network disconnects often

Hi , My redhat 5 frequently disconnects from network. Once rebooted , network is working for one day or two. After that the NIC suddently stops working. Even if i give "#service network restart" or ifup eth0 commands it won't come up. I even tried reconfigure the network card. but no use. Only... (6 Replies)
Discussion started by: dknattukal
6 Replies

8. Solaris

Too much TCP retransmitted and TCP duplicate on server Oracle Solaris 10

I have problem with oracle solaris 10 running on oracle sparc T4-2 server. Os information: 5.10 Generic_150400-03 sun4v sparc sun4v Output from tcpstat.d script TCP bytes: out outRetrans in inDup inUnorder 6833763 7300 98884 0... (2 Replies)
Discussion started by: insatiable1610
2 Replies

9. UNIX for Dummies Questions & Answers

Persistent terminal windows across viewer disconnects

Is there a way to have persistent terminal windows to redhat server across viewer disconnects? I can do that with the help of an extra MS Windows server and rdp, but is there a way of doing that without the Windows server? Here's the scenario. I have multiple redhat servers (VMs) which have no... (3 Replies)
Discussion started by: ad101
3 Replies

10. SCO

Telnet session disconnects abruptly

I have inherited and SCO OpenServer Release 6 server. The clients connect using telnet to get to a proprietary database application for Service tickets. The issue I am currently having is that the connection just stops abruptly and you can see "telnet session terminated" on the terminal emulation... (22 Replies)
Discussion started by: sean6605
22 Replies
ivykis(3)						    ivykis programmer's manual							 ivykis(3)

NAME
iv_examples - ivykis examples EXAMPLE
ivykis is initialised by calling iv_init(3). This function is the first function to call when dealing with ivykis -- it has to be called before registering file descriptors or timers. The ivykis main event loop is started by calling iv_main(3). This function generally does not return, except when iv_quit(3) is called somewhere during execution of the program. An application asks ivykis to monitor a certain file descriptor by filling out a structure of type 'struct iv_fd' with a file descriptor number and a callback function, and calling the function iv_fd_register. The first example program waits for data from standard input, and writes a message to standard out whenever something is received: #include <stdio.h> #include <stdlib.h> #include <iv.h> struct iv_fd fd_stdin; static void callback(void *dummy) { char buf[1024]; int len; len = read(fd_stdin.fd, buf, sizeof(buf)); if (len <= 0) { if (len < 0) { if (errno == EAGAIN) return; perror("read"); } exit(1); } printf("read %d bytes of data from stdin ", len); } int main() { iv_init(); IV_FD_INIT(&fd_stdin); fd_stdin.fd = 0; fd_stdin.handler_in = callback; iv_fd_register(&fd_stdin); iv_main(); iv_deinit(); return 0; } The application is responsible for memory management of 'struct iv_fd's passed to ivykis. For example, it should not free memory that con- tains such structures that are still registered with ivykis (i.e. haven't had iv_fd_unregister called on them). iv_fd_register transparently sets the passed file descriptor to nonblocking mode, in anticipation of its future usage. File descriptor callbacks are called in a level-triggered fashion. Therefore, the way of dealing with fd_stdin in the example callback function is safe. In case there arrives data between read and detecting EAGAIN, ivykis will re-call the callback function after it returns. Also, if there are more than 1024 bytes waiting in the input buffer, ivykis will re-call the callback function until all data from stdin have been drained. EXAMPLE 2 The second example accepts connections on TCP port 6667, and waits on each of the connections for data. When data is received on any con- nection, a message is printed to standard out. #include <stdio.h> #include <stdlib.h> #include <iv.h> #include <netinet/in.h> struct connection { struct iv_fd fd; /* other per-connection data goes here */ }; struct listening_socket { struct iv_fd fd; /* other per-listening socket data goes here */ }; static void connection_handler(void *_conn) { struct connection *conn = (struct connection *)_conn; char buf[1024]; int len; len = read(conn->fd.fd, buf, sizeof(buf)); if (len <= 0) { if (len < 0 && errno == EAGAIN) return; iv_fd_unregister(&conn->fd); close(conn->fd.fd); free(conn); return; } printf("got %d bytes of data from %p ", len, conn); } static void listening_socket_handler(void *_sock) { struct listening_socket *sock = (struct listening_socket *)_sock; struct sockaddr_in addr; socklen_t addrlen; struct connection *conn; int fd; addrlen = sizeof(addr); fd = accept(sock->fd.fd, (struct sockaddr *)&addr, &addrlen); if (fd < 0) { if (errno == EAGAIN) return; perror("accept"); exit(1); } conn = malloc(sizeof(*conn)); if (conn == NULL) { fprintf(stderr, "listening_socket_handler: memory allocation error, dropping connection"); close(fd); return; } IV_FD_INIT(&conn->fd); conn->fd.fd = fd; conn->fd.cookie = (void *)conn; conn->fd.handler_in = connection_handler; iv_fd_register(&conn->fd); } int main() { struct listening_socket s; struct sockaddr_in addr; int fd; fd = socket(AF_INET, SOCK_STREAM, 0); if (fd < 0) { perror("socket"); exit(1); } addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(6667); if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("bind"); exit(1); } if (listen(fd, 4) < 0) { perror("listen"); exit(1); } iv_init(); IV_FD_INIT(&s.fd); s.fd.fd = fd; s.fd.cookie = (void *)&s; s.fd.handler_in = listening_socket_handler; iv_fd_register(&s.fd); iv_main(); iv_deinit(); return 0; } As illustrated, it is possible to pass cookies into callback functions. This is useful for conveying information on which higher-level entity (such as 'connection' or 'listening socket') generated the event for which the callback was called. Note how it is possible to unregister and even free a 'struct iv_fd' in its own callback function. There is logic in ivykis to deal with this case. EXAMPLE 3 This example extends the previous example by a per-connection timer that disconnects the client after too long a period of inactivity. Lines not present in example 2 or different than in example 2 are indicated by '//XXXX' in the right-hand margin. #include <stdio.h> #include <stdlib.h> #include <iv.h> #include <netinet/in.h> #define CONNECTION_TIMEOUT(10) struct connection { struct iv_fd fd; struct iv_timer disconnect_timeout; //XXXX /* other per-connection data goes here */ }; struct listening_socket { struct iv_fd fd; /* other per-listening socket data goes here */ }; static void connection_handler(void *_conn) { struct connection *conn = (struct connection *)_conn; char buf[1024]; int len; len = read(conn->fd.fd, buf, sizeof(buf)); if (len <= 0) { if (len < 0 && errno == EAGAIN) return; iv_timer_unregister(&conn->disconnect_timeout); //XXXX iv_fd_unregister(&conn->fd); close(conn->fd.fd); free(conn); return; } printf("got %d bytes of data from %p ", len, conn); iv_timer_unregister(&conn->disconnect_timeout); //XXXX iv_validate_now(); //XXXX conn->disconnect_timeout.expires = iv_now; //XXXX conn->disconnect_timeout.expires.tv_sec += CONNECTION_TIMEOUT;//XXXX iv_timer_register(&conn->disconnect_timeout); //XXXX } static void disconnect_timeout_expired(void *_conn) //XXXX { //XXXX struct connection *conn = (struct connection *)_conn; //XXXX iv_fd_unregister(&conn->fd); //XXXX close(conn->fd.fd); //XXXX free(conn); //XXXX } //XXXX static void listening_socket_handler(void *_sock) { struct listening_socket *sock = (struct listening_socket *)_sock; struct sockaddr_in addr; socklen_t addrlen; struct connection *conn; int fd; addrlen = sizeof(addr); fd = accept(sock->fd.fd, (struct sockaddr *)&addr, &addrlen); if (fd < 0) { if (errno == EAGAIN) return; perror("accept"); exit(1); } conn = malloc(sizeof(*conn)); if (conn == NULL) { fprintf(stderr, "listening_socket_handler: memory allocation error, dropping connection"); close(fd); return; } IV_FD_INIT(&conn->fd); conn->fd.fd = fd; conn->fd.cookie = (void *)conn; conn->fd.handler_in = connection_handler; iv_fd_register(&conn->fd); IV_TIMER_INIT(&conn->disconnect_timeout); //XXXX iv_validate_now(); //XXXX conn->disconnect_timeout.cookie = (void *)conn; //XXXX conn->disconnect_timeout.handler = disconnect_timeout_expired;//XXXX conn->disconnect_timeout.expires = iv_now; //XXXX conn->disconnect_timeout.expires.tv_sec += CONNECTION_TIMEOUT;//XXXX iv_timer_register(&conn->disconnect_timeout); //XXXX } int main() { struct listening_socket s; struct sockaddr_in addr; int fd; fd = socket(AF_INET, SOCK_STREAM, 0); if (fd < 0) { perror("socket"); exit(1); } addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(6667); if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("bind"); exit(1); } if (listen(fd, 4) < 0) { perror("listen"); exit(1); } iv_init(); IV_FD_INIT(&s.fd); s.fd.fd = fd; s.fd.cookie = (void *)&s; s.fd.handler_in = listening_socket_handler; iv_fd_register(&s.fd); iv_main(); iv_deinit(); return 0; } The global variable 'iv_now' contains the current time-of-day. However, it is updated lazily, and its contents might be stale at any given time. Before using it, iv_validate_now(3) must be called. EXAMPLE 4 The fourth example demonstrates how to use a custom fatal error handler that does not write the message to syslog. #include <stdio.h> #include <iv.h> static void fatal_error(const char *msg) { fprintf(stderr, "ivykis: FATAL ERROR: %s ", msg); } int main() { iv_init(); iv_set_fatal_msg_handler(fatal_error); iv_fatal("Programmatically triggered fatal error %d.", 42); printf("This code is never reached. "); iv_deinit(); return 0; } This program will abort immediately, with the error message printed to the standard error stream. SEE ALSO
ivykis(3), iv_fatal(3), iv_fd(3), iv_timer(3), iv_task(3), iv_init(3), iv_time(3) ivykis 2003-03-29 ivykis(3)
All times are GMT -4. The time now is 06:21 AM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy