Search code examples
csocketsdatagram

C: how to create a socket?


I am trying to create a socket for a client and server to communicate with.

I am not very familiar with how socket() and bind() works. How do I create a datagram socket?

When I try compiling it, it says the address of the socket will never be NULL and sockfd is not used.

int create_dg_socket(in_port_t port) {

    int socket(int domain, int type, int protocol);

    int bind(int sockfd,
         const struct sockaddr *addr,
         socklen_t len);

    // Create the socket
    int sockfd;
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);

    if(socket==NULL) {
    fprintf(stderr, "create_dg_socket not implemented!\n");
    exit(-1);
    }
}

Solution

  • How do I create a datagram socket?

    Like this:

    int create_dg_socket(in_port_t port) {
    
        // Create the socket
    
        int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (sockfd == -1) {
            fprintf(stderr, "create_dg_socket cannot create socket! Error: %d\n", errno);
            return -1;
        }
    
        // Bind the socket port
    
        struct sockaddr_in addr;
        memset(&addr, 0, sizeof(addr));
    
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);
        addr.sin_addr.s_addr = INADDR_ANY;
    
        if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
            fprintf(stderr, "create_dg_socket cannot bind socket! Error: %d\n", errno);
            close(sockfd);
            return -1;
        }
    
        return sockfd;
    }
    

    int sockfd = create_dg_socket(port);
    if (sockfd == -1) {
        //...
        exit(-1);
    }