Golgappa.net | Golgappa.org | BagIndia.net | BodyIndia.Com | CabIndia.net | CarsBikes.net | CarsBikes.org | CashIndia.net | ConsumerIndia.net | CookingIndia.net | DataIndia.net | DealIndia.net | EmailIndia.net | FirstTablet.com | FirstTourist.com | ForsaleIndia.net | IndiaBody.Com | IndiaCab.net | IndiaCash.net | IndiaModel.net | KidForum.net | OfficeIndia.net | PaysIndia.com | RestaurantIndia.net | RestaurantsIndia.net | SaleForum.net | SellForum.net | SoldIndia.com | StarIndia.net | TomatoCab.com | TomatoCabs.com | TownIndia.com
Interested to Buy Any Domain ? << Click Here >> for more details...

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

What is difference between socket and websocket?

893


What is the purpose of socket?

912


How does a socket work?

856


How is a socket created?

904


What is a socket file?

883


Can a single socket port be used for multiple applications?

880


Can multiple sockets use the same port?

860


What is af_inet in socket?

823


Is there any advantage to handling the signal, rather than just ignoring it and checking for the EPIPE error? Are there any useful parameters passed to the signal catching function?

1411


What is socket programming in java?

839


How do I convert a string into an internet address?

1373


How many sockets can a cpu have?

838


What's better 6pt or 12pt sockets?

814


What is the function of socket?

905


What is a socket set used for?

940