简体   繁体   中英

Socket: get socket() in the server code

I trying to return a result of socket() in the following server code:

#include "sys/socket.h"
#include "sys/types.h"
int main(void)
{   
    int listenfd = 0,connfd = 0;
    struct sockaddr_in serv_addr;
    char sendBuff[1025];  
    int numrv;  
    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    printf("socket retrieve success\n");
    return(listenfd);
}

I do the gcc to this code and it worked well,but when I execute it,it return nothing.

If successful socket() returns an integer file descriptor for the new socket. If there was an error, -1 is returned. You can inspect the error code in errno , and can print out a text version of it using perror() .

Note that you need to #include <netinet/in.h> for the definition of struct sockaddr_in .

This might aid your understanding:

#include <stdio.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>

int main(void)
{
    int listenfd = 0,connfd = 0;
    struct sockaddr_in serv_addr;
    char sendBuff[1025];
    int numrv;
    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    if (listenfd == -1) {
        printf("Failed to create socket: errno = %d\n", errno);
        perror("Failed to create socket");
    }
    else
        printf("socket created, fd = %d\n", listenfd);
    return(listenfd);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM