Socket reuse
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: Socket reuse

  1. #1
    Join Date
    Dec 2001
    Location
    Dallas, Tx, USA (originally fromIndia)
    Posts
    154

    Socket reuse

    I use connect() to connect to a particular server.
    If i want to reuse the socket and connect to another server, what should i do..
    What i am doing currently is:
    //Create a socket and bind to a port
    //then
    tcnt = 0;
    while(1)
    {
    servAddr.sin_family = AF_INET;
    inet_pton(AF_INET, ip_addr[tcnt], &servAddr.sin_addr);
    servAddr.sin_port = htons(SERVPORT);
    bytes = connect(sdServerLoad, (struct sockaddr *) &servAddr, sizeof(servAddr));
    if(bytes < 0)
    {
    perror("connect");
    continue;
    }
    .
    .
    .
    .
    tcnt++;
    }
    The first loop executes fine, but during the second round of execution of the loop..it throws me an error "connect: Transport endpoint is already connected"
    Why is this n how can i solve it..

    Regards,
    Preetham.
    "All you touch and all you see is all you'll ever be"

  2. #2
    Join Date
    Feb 2002
    Location
    Somewhere in the United States.
    Posts
    58

    Re: Socket reuse

    I think you're going to have to release the previous socket connection before you try to open the socket again to another server. See, a socket is a two end deal, it's not something that you can just re-direct you have to first disconnect it and then re-connect it. A socket is defined by both ends of the connection, not by one and this is an important thing to remember.

    Try disconnecting your socket again before re-connecting.


  3. #3
    Join Date
    Dec 2001
    Location
    Dallas, Tx, USA (originally fromIndia)
    Posts
    154

    Re: Socket reuse

    I have even tried using the code below..
    tcnt = 0;
    while(1)
    {
    //Create a socket and bind to a port
    //then
    servAddr.sin_family = AF_INET;
    inet_pton(AF_INET, ip_addr[tcnt], &servAddr.sin_addr);
    servAddr.sin_port = htons(SERVPORT);
    bytes = connect(sdServerLoad, (struct sockaddr *) &servAddr, sizeof(servAddr));
    if(bytes < 0)
    {
    perror("connect");
    continue;
    }
    .
    .
    .
    .
    tcnt++;
    shutdown(sdServerLoad, SHUT_WR);
    close(sdServerLoad);
    }
    But, now its givin me an error:
    "cannot bind port : Address already in use", during
    the second loop of execution...
    How do i release the address and the port...


    Regards,
    Preetham.
    "All you touch and all you see is all you'll ever be"

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center