How do I get the port number for a given service?

Answer Posted / chaitanya

Use the getservbyname() routine. This will return a pointer to a servent structure. You are interested in the s_port field, which contains the port number, with correct byte ordering (so you don't need to call htons() on it). Here is a sample routine:

/* Take a service name, and a service type, and return a port number. If the service name is not found, it tries it as a decimal number. The number returned is byte ordered for the network. */

int atoport(char *service, char *proto)

{

int port;

long int lport;

struct servent *serv;

char *errpos;

/* First try to read it from /etc/services */

serv = getservbyname(service, proto);

if (serv != NULL)

port = serv->s_port;

else {

/* Not in services, maybe a number? */

lport = strtol(service,&errpos,0);

if ( (errpos[0] != 0) || (lport < 1)

|| (lport > 5000) )

return -1;

/* Invalid port address */

port = htons(lport);

}

return port;

}

Is This Answer Correct ?    0 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

How many sockets can a cpu have?

501


How to find other end of unix socket connection?

513


What is af_inet in socket?

475


What pieces of information make up a socket?

547


What is socket address?

570






What is a sae socket?

514


What is a socket address?

521


What is socket address with example?

495


How do unix sockets work?

492


How does unix socket work?

508


What's the difference between impact sockets and regular sockets?

476


Is tcp or unix socket faster?

494


Why do we need sockets?

485


What is a socket api?

533


Is socket a hardware or software?

505