socket设置基本listen

大耗子 2020年02月24日 212次浏览
#define PORT 6666
#define IP "127.0.0.1"
int SRV_create_listen_fd()
{
    //创建socket
    int listenfd = socket(AF_INET, SOCK_STREAM, 0);
    if(listenfd == -1)
    {
        ERR_PRINT("socket fail, listenfd:%d\n",listenfd);
        return false;
    }
        
    //设置端口复用
    int on = 1;
    if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
    {
        ERR_PRINT("setsockopt fail\n");
        return false;
    }

    struct sockaddr_in servaddr;
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(PORT);
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    //inet_pton(AF_INET, IP, &servaddr.sin_addr);
    
    //bind端口
    if(bind(listenfd, (struct sockaddr*)&servaddr, sizeof servaddr) < 0)
    {
        ERR_PRINT("bind fail\n"); 
        return false;
    }

    //listen端口
    if(listen(listenfd, LISTSIZE) < 0)
        ERR_PRINT("listen fail\n");

    return listenfd;
}