Question

I am doing a program about client server communication using sockets. I saw examples of client server program on internet, but I have a question. How to get host name? I saw a client program example on the webpage int the link below. The program gets the host name from the user in command line arguments,but how can I know the host name? and I tried using my username on it but its says host does not found. I am running both on same machine. Thank you very much for your time.

client: http://www.tutorialspoint.com/unix_sockets/socket_client_example.htm

server: http://www.tutorialspoint.com/unix_sockets/socket_server_example.htm

Was it helpful?

Solution

Host name is different from the username to get the host name use the command "hostname" and use this host name in command line

commands:

hostname -->gethostname

hostname < name > -->sethostname with name

OTHER TIPS

If your client and server are on the same host, the hostname is localhost, or you could use the name of the machine, or you could use 127.0.0.1

Assuming you mean the host you are currently running on you use gethostname

int main(int argc, char *argv[])
{
    int ret;
    char buffer[100];

    if ((ret = gethostname(buffer, sizeof(buffer))) == -1)
    {
        perror("gethostname");
        exit(1);
    }    

    printf("hostname is: %s\n", buffer);

    return(0);
}

For a client server program , the client must know the hostname or the ip address of the machine it wants to communicate with.

Think of it like you are driving to a particular shop, you need to know the address of the shop to reach there. Similarly clients need the address of the host it needs to communicate with.

If you are running your own client and server, then type hostname in the machine and it will give you the host name. Usually you would need host name and port but in simple example programs the value may be hard coded.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top