Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I know how to test it experimentally by running the program, but ideally I would like to test each function I write as I write it. Usually I can't test my functions until I write a whole bunch of them, and it makes it hard to find out what went wrong.

Does Posix have some way of testing the socket's options, flags, settings, etc, so I can write a test case for a function such as this?

What is the best way to test a function such as this?

 /**
 * Creates a listening socket, sets it up with setsockopt, bind, and listen.
 * @param port the port of the listening socket.
 * @return the file descriptor of the listening socket.
 */
int SetUpListeningSocket(int port)
{
    //Variables:
    struct sockaddr_in server;
    int s;

    // setup socket address structure
    memset(&server, 0, sizeof (server));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = INADDR_ANY;

    // create socket
    s = socket(PF_INET, SOCK_STREAM, 0);
    if (!s)
    {
    perror("socket");
    exit(-1);
    }

    // set socket to immediately reuse port when the application closes
    int opt = 1;
    if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof (opt)) < 0)
    {
    perror("setsockopt");
    exit(-1);
    }

    // call bind to associate the socket with our local address and
    // port
    if (bind(s, (const struct sockaddr *) &server, sizeof (server)) < 0)
    {
    perror("bind");
    exit(-1);
    }

    // convert the socket to listen for incoming connections
    if (listen(s, SOMAXCONN) < 0)
    {
    perror("listen");
    exit(-1);
    }
    return s;
}
share|improve this question

closed as off topic by Mat, Ulrich Dangel, Renan, ire_and_curses, jasonwryan Dec 23 '12 at 19:43

Questions on Unix & Linux Stack Exchange are expected to relate to Unix or Linux within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here.If this question can be reworded to fit the rules in the help center, please edit the question.