1

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.

Horse SMith
  • 1,003
  • 2
  • 12
  • 25

2 Answers2

5

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

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
0

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);
helloV
  • 50,176
  • 7
  • 137
  • 145
  • Still POSIX, 1+ however. – alk Nov 15 '14 at 17:40
  • @alk Do notice I never say in the question it needs to be from the standard C library. In fact, I mention getaddrinfo, which isn't in the standard C library. When I in the comment said some standard C function for this, I meant more as in a commonly used C function/library that is pretty much the standard to use, but I get the confusion. – Horse SMith Nov 15 '14 at 17:41
  • 3
    This is outdated/deprecated and non-thread-safe. The correct way is `getaddrinfo`. – R.. GitHub STOP HELPING ICE Nov 15 '14 at 17:45