Simple C Port Scanner
After creating a socket make it non-blocking. Then call connect(). If connect returns 0 then the connection has been established and you can use it already. If it retuned -1 and errno is equal to EINPROGRESS then you need to wait until it becomes write-ready using select() or poll(). When it becomes write-ready use getsockopt(sock, SOL_SOCKET, SO_ERROR, ...) to tell if the connection has failed or succeeded. The example code for using non-blocking connect is here:

http://developerweb.net/viewtopic.php?id=3196

But this sample shows waiting on single socket only. You need to wait on a bunch of them at the same time. So have a table of socket connections with some fixed size, e.g. 32:

#define MAX_CONNECT 32

struct socket_info {
    int sock;    /* the socket */
    int ready;   /* initialize to 0 when filling the table, set to 1 when the connection has established or failed */
    int error;   /* set to errno got with getsockopt() for failed connections, set to 0 if connection succeeded */
    sockaddr_in addr;
};

struct socket_info pending_connect[MAX_CONNECT];


First fill this table in a loop calling socket/connect. Then wait in another loop with select until all of the sockets become ready. Set appropriate flags in the table as the sockets become ready.

After the select loop you have info about 32 ports. Print it. Close the sockets. Then proceed with a next bunch of 32 ports.

This approach could be further optimised. You could close a socket as soon as you get info about it, print that info, and immediately open another socket in its place in the table. This will be faster but perhaps this also requires more careful coding.