In C you can use a service name to get the port number when using getaddrinfo, like this:
getaddrinfo("stackoverflow.com", "http", &hints, &results);
This will assign 80 (big endian) to the first two bytes (uint16_t) of results->ai_addr.
Is there some easy way to get the port number from ?only? giving the service name? I need this for the server side, where I want to allow the user to specify either port number or service name for the port to bind and listen to.
Using getaddrinfo
with a null pointer for the hostname and AI_PASSIVE
in the flags will give you a sockaddr
you can bind on for running a server. See the documentation for getaddrinfo
:
http://pubs.opengroup.org/onlinepubs/9699919799/functions/getaddrinfo.html
man getservbyname
#include \netdb.h>
struct servent *getservent(void);
struct servent *getservbyname(const char *name, const char *proto);
struct servent *getservbyport(int port, const char *proto);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.