LinuxQuestions.org
Register a domain and help support LQ
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices

Reply
 
LinkBack Search this Thread
Old 10-21-2006, 11:45 PM   #1
naihe2010
Member
 
Registered: Oct 2005
Location: China
Distribution: ArchLinux
Posts: 103

Rep: Reputation: 15
how to check if a socket is valid in C ?


Hi, guys.

I am writing a program in Linux C.

It connect a server and send some things to it.

But, the server often closed my socket after some time. And, my wirte () thread will get a SIGPIPE signal.

How to check the socket? and, when the server closed it, I can connect
again.

Thanks!
 
Old 10-22-2006, 02:01 AM   #2
demon_vox
Member
 
Registered: May 2006
Location: Argentina
Distribution: SuSE 10
Posts: 173

Rep: Reputation: 30
Hi,
you will know that your socket is close when you get SIGPIPE when you try to write (as you have discovered yourself ) or you will have a return value of 0 when you try to read from it. You should also know that when the socket is closed by the other side (or broken) there will be "data" to read, which will be the end of "file" (or connection in this case).

CHeers!
 
Old 10-22-2006, 11:59 PM   #3
Wim Sturkenboom
Senior Member
 
Registered: Jan 2005
Location: Roodepoort, South Africa
Distribution: Slackware 10.1/10.2/12, Ubuntu 12.04, Crunchbang Statler
Posts: 3,786

Rep: Reputation: 282Reputation: 282Reputation: 282
You can use a signal handler to catch the SIGPIPE signal.

The handler that you write for it will set a global flag to indicate that the socket is no longer valid.
Before writing to the socket, check this global flag. If an error is indicated, cleanup your client socket and reconnect.

As you now handle the SIGPIPE, your program will not 'crash'.

Below a modified client example (original is taken from http://www.cs.utah.edu/~swalton/list...kets/programs/)
Code:
/* simple-client.c
 *
 * Copyright (c) 2000 Sean Walton and Macmillan Publishers.  Use may be in
 * whole or in part in accordance to the General Public License (GPL).
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
*/

/*****************************************************************************/
/*** simple-client.c                                                       ***/
/***                                                                       ***/
/*****************************************************************************/

/**************************************************************************
*   This is a simple client socket reader.  It opens a socket, connects
*   to a server, reads the message, and closes.
**************************************************************************/
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>

#include <resolv.h>

#define PORT_TIME       13              /* "time" (not available on RedHat) */
#define PORT_FTP        21              /* FTP connection port */
#define PORT_TEST       9999            /* connection port */
#define SERVER_ADDR     "127.0.0.1"     /* localhost */
#define MAXBUF          1024


int socket_OK=0;



void sigpipe_handler()
{
    printf("SIGPIPE caught\n");
    socket_OK=0;
}

int main()
{
    int sockfd;
    struct sockaddr_in dest;
    char buffer[MAXBUF];

    int counter=0;


    /*---Open socket for streaming---*/
    if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
    {
        perror("Socket");
        exit(errno);
    }

    /*---Initialize server address/port struct---*/
    bzero(&dest, sizeof(dest));
    dest.sin_family = AF_INET;
    dest.sin_port = htons(PORT_TEST);
    if ( inet_aton(SERVER_ADDR, &dest.sin_addr.s_addr) == 0 )
    {
        perror(SERVER_ADDR);
        exit(errno);
    }


    // instal sigpipe handler
    signal(SIGPIPE,sigpipe_handler);

    /*---Connect to server---*/
    if ( connect(sockfd, (struct sockaddr*)&dest, sizeof(dest)) != 0 )
    {
        perror("Connect ");
        exit(errno);
    }

    // indicate that socket is OK
    socket_OK=1;


    while(1)
    {
        if(!socket_OK)
            break;
        send(sockfd, "test\n", 5, 0);
        printf("message sent\n");
        /*---Get "Hello?"---*/
        bzero(buffer, MAXBUF);
        recv(sockfd, buffer, sizeof(buffer), 0);
        printf("[%6d]:%s", ++counter,buffer);
        sleep(1);
    }

    /*---Clean up---*/
    close(sockfd);
    return 0;
}
It compiles with some warnings, but I did not feel like looking into that now.
 
Old 10-29-2006, 06:56 PM   #4
naihe2010
Member
 
Registered: Oct 2005
Location: China
Distribution: ArchLinux
Posts: 103

Original Poster
Rep: Reputation: 15
Thank you very much!
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Check if an int value is within valid range of enum? mic Programming 6 02-21-2006 11:02 AM
fseek on a socket descriptor to discard socket buffer? Thinking Programming 1 12-06-2005 09:15 PM
cannot read data at server socket, though client socket sends it jacques83 Linux - Networking 0 11-15-2005 01:58 PM
Unable to connect to UNIX socket /tmp/.esd/socket error while using grip dr_zayus69 Linux - Software 4 08-23-2005 07:28 PM
Boot disk; check. CD in drive; check. Doesn't work; check. Hal DamnSmallLinux 7 02-04-2004 02:10 AM


All times are GMT -5. The time now is 08:10 AM.

Main Menu
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration