P
P
Pavel2015-11-05 15:59:15
linux
Pavel, 2015-11-05 15:59:15

How to get the domain name of your computer using the Linux API?

There is a function in which a socket is bound to a port and starts listening to it:

bool ListenPort(int sock, int port)
{
    addrinfo hints, *results, *res = NULL;

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;

    int status = getaddrinfo(NULL, std::to_string(port).c_str(), &hints, &results);
    if (status != 0) {
      //error
      return false;
    }
    int yes = 1;
    if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
        return false;
    }
    for(res = results; res != NULL; res = res->ai_next) {
        int bind_res = bind(sock, res->ai_addr, res->ai_addrlen);
        if (bind_res != -1) break;
    }
    if (res == NULL)  {
        return false;
    }

    int backlog = 10;
    int listen_res = listen(sock, backlog);
    if (listen_res < 0)
        return false;
    return true;
}

I want to use this function to organize the work of a simple server. Need: get the domain name of the computer on which this program will run in order to use it to connect to the running server from the client program.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ruslan Fedoseev, 2015-11-05
@martin74ua

hostname

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question