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



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

Answer / 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

More Unix Socket Programming Interview Questions

What is active unix domain sockets?

0 Answers  


How can my client work through a firewall/proxy server?

1 Answers  


How would I put my socket in non-blocking mode?

1 Answers  


If bind() fails, what should I do with the socket descriptor?

1 Answers  


How is a socket created?

0 Answers  






How can I put a timeout on connect()?

1 Answers  


What is socket address?

0 Answers  


How come I get address already in use from bind()?

1 Answers  


Why do I get connection refused when the server is not running?

1 Answers  


Where is the socket located?

0 Answers  


Can multiple clients connect to same socket?

0 Answers  


What are Sockets?

1 Answers  


Categories