socklib.c:创建一个socket服务端

/**
 * @file socklib.c
 * @author your name (you@domain.com)
 * @brief make_socket_server 创建一个socket服务端
 * @version 0.1
 * @date 2022-04-15
 *
 * @copyright Copyright (c) 2022
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <strings.h>
#include <netinet/in.h>
#include <unistd.h>
#include <netdb.h>
#define ERROR_CODE -1
#define BACKLOG 1
#define oops(m)             \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    }
#define exit_on_error(msg)   \
    {                        \
        printf("%s\n", msg); \
        exit(EXIT_FAILURE);  \
    }
/**
 * @brief int portnum 端口
 *
 * @return int -1 error,or socket fd
 */
int make_socket_server(int);

int make_socket_server(int portnum) {
    int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (sock_fd == ERROR_CODE)
    {
        return ERROR_CODE;
    }
    struct sockaddr_in sock_addr;
    char hostname[BUFSIZ];
    bzero(&sock_addr, sizeof(sock_addr));
    sock_addr.sin_family = AF_INET;
    sock_addr.sin_port = htons(portnum);
    if (gethostname(hostname, BUFSIZ) == ERROR_CODE)
    {
        close(sock_fd);
        return ERROR_CODE;
    }
    struct hostent *host_addr = gethostbyname(hostname);
    if (host_addr == NULL)
    {
        close(sock_fd);
        return ERROR_CODE;
    }
    bcopy(host_addr->h_addr_list[0], &sock_addr.sin_addr, host_addr->h_length);
    if (bind(sock_fd, (struct sockaddr *)&sock_addr, sizeof(sock_addr)) == ERROR_CODE)
    {
        close(sock_fd);
        return ERROR_CODE;
    }
    if (listen(sock_fd, BACKLOG) == ERROR_CODE)
    {
        close(sock_fd);
        return ERROR_CODE;
    }
    return sock_fd;
}

 

posted @ 2022-04-15 14:14  风的低吟  阅读(67)  评论(0编辑  收藏  举报