Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix C socket server not accepting connections

Here's the deal, I'm writing a simple tcp socket server in C (with unix system calls) that I'm not able to get to accept connections.

From what I can tell, I get through the server initialization just fine, but when I try to connect to the port that I print out (see code below) it refuses as if nothing is there.

More to the point, when I netstat that port isn't even in use. I'm not throwing any errors with my current set up, I'm all dried up for ideas.

int main(){

    int sock_fd;
    int conn_fd;
    struct sockaddr_in serv_addr;
    struct sockaddr_in cli_addr;
    socklen_t* serlen;
    socklen_t* clilen;
    clilen  = malloc(sizeof(socklen_t));
    serlen  = malloc(sizeof(socklen_t));
    *serlen = sizeof(serv_addr);
    *clilen = sizeof(cli_addr);

    /*=============================Create Socket=============================*/


        //Create Socket
        sock_fd = socket(AF_INET, SOCK_STREAM, 0);
            if(sock_fd<0){
                fprintf(stderr,"error creating socket\n");
                exit(1);}

        //Initialize Server Address Struct
        bzero((char *) &serv_addr, *serlen);
        serv_addr.sin_family = AF_INET;
        serv_addr.sin_addr.s_addr = INADDR_ANY;
        serv_addr.sin_port = 0;

    /*=============================Bind Address==============================*/

        //Bind socket to an address
        if(bind(sock_fd,(struct sockaddr*)&serv_addr,*serlen)<0){
            fprintf(stderr,"error binding\n");
            exit(1);}

        //Get socket data
        if(getsockname(sock_fd,(struct sockaddr*)&serv_addr, serlen)<0){
            fprintf(stderr,"error with socket name");
            exit(1);}

    /*=============================Server Started============================*/

        //Listen for connections
        listen(sock_fd,32);

        //Print port
        printf("%i", serv_addr.sin_port);

        conn_fd = accept(sock_fd,(struct sockaddr*)&cli_addr,clilen);

        /**Do something exciting with my new connection**/

}
like image 566
darkpbj Avatar asked Dec 20 '25 05:12

darkpbj


1 Answers

Are you really trying to listen on port zero? Try a high port number, preferably > 1024. /etc/services will give a hint about free ports - but it only a set of comments, those port numbers are not enforced.

Edit: another hint. The port number should be in network order, so the assignment should use htons(). It could be that the "random numbers" you are getting are simple numbers that appear garbled because you might be on a little-endian machine (like Intel). When you print them, convert them back using ntohs().

like image 184
cdarke Avatar answered Dec 22 '25 19:12

cdarke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!