Search code examples
cip-addressprintf

How should I print server address


    int server_sockfd, client_sockfd; //server and client filedescriptors
    socklen_t server_len, client_len; 
    struct sockaddr_in server_address; //server address
    struct sockaddr_in client_address; //client address
    int server_port = 10000;
    char *def_server_address ="127.0.0.1";

    server_len = sizeof(server_address);
    memset(&server_address, 0, server_len );
    server_address.sin_family = AF_INET;

    if (x == 1) {
        server_address.sin_addr.s_addr = INADDR_ANY;}
    else {
        server_address.sin_addr.s_addr = inet_addr(def_server_address);
    }
    server_address.sin_port = htons(server_port);

How should I print the address of the server from server_address? Using printf.


Solution

  • Use inet_ntop() to convert it to a string

    This function converts the network address structure src in the af address family into a character string. The resulting string is copied to the buffer pointed to by dst, which must be a non-null pointer. The caller specifies the number of bytes available in this buffer in the argument size.

    inet_ntop() extends the inet_ntoa(3) function to support multiple address families, inet_ntoa(3) is now considered to be deprecated in favor of inet_ntop().