0

I am learning socket programming in linux and I have a problem.

I am trying to set up a really simple client-server socket connection with TCP sockets. However, I think I am unable to close the server socket because, when I restarted the server, it cannot bind to the same IP address and port number.

I also don't know how to debug issue. I have read that errno would be set when an error ocurs in man pages of bind. I don't know how to look at that errno.

Here is my all code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main(int argc, char* argv[]) {

    int serverSocket, clientSocket, portno;
    socklen_t clientLength;
    struct sockaddr_in serverAddress, clientAddress;
    int n;
    char buffer[256];

    if (argc < 2) {
        fprintf(stderr, "ERROR too few arguments.\n");
        exit(-1);
    }

    serverSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (serverSocket < 0) {
        fprintf(stderr, "ERROR creating socket!\n");
        exit(1);
    }

    bzero((char*) &serverAddress, sizeof(serverAddress));
    portno = atoi(argv[1]);

    serverAddress.sin_family = AF_INET;
    serverAddress.sin_addr.s_addr = INADDR_ANY;
    serverAddress.sin_port = htons(portno);

    if (bind(serverSocket, (struct sockaddr*) &serverAddress, sizeof(serverAddress)) < 0) { //This bind will fail, after re-run.
        fprintf(stderr, "ERROR binding socket\n");
        exit(2);
    }

    listen(serverSocket, 5);
    clientLength = sizeof(clientAddress);

    clientSocket = accept(serverSocket, (struct sockaddr*) &clientSocket, &clientLength);
    if (clientSocket < 0) {
        fprintf(stderr, "ERROR on accept\n");
        exit(3);
    }

    bzero(buffer, 256);
    n = read(clientSocket, buffer, 256);
    char* ack = "I got your message";
    fprintf(stdout, "Here is the message %s\n", buffer);

    n = write(clientSocket, ack, strlen(ack));

    close(clientSocket);
    close(serverSocket);
    return 0;
}

As far as I understand, the socket, which is a file descriptor, cannot get closed immediately. So when the program terminates and I run again within 30 seconds, it cannot bind to the address. But if I wait for, like, a minute, it has no problem binding to address.

What causes this issue?

Bora
  • 1,778
  • 4
  • 17
  • 28

1 Answers1

0

You can use perror() to view the readable error message, and set serverSocket reusable. The snippet is listed here:

serverAddress.sin_port = htons(portno);
int opt = 1;
setsockopt(serverSocket,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
if (bind(serverSocket, (struct sockaddr*) &serverAddress, sizeof(serverAddress)) < 0) {
    //This bind will fail, after re-run.
    perror("bind ");
    fprintf(stderr, "ERROR binding socket\n");
    exit(2);
}
Mathieu
  • 8,840
  • 7
  • 32
  • 45
wen
  • 114
  • 1
  • 3