getservbyport_r - Linux


Overview

getservbyport_r is a Linux command used to retrieve service information for a given port number. It’s primarily used in network programming to associate port numbers with their corresponding service names.

Syntax

#include <netdb.h>

int getservbyport_r(int port, const struct protoent *protocol,
                    struct servent *result_buf, char *buf, size_t buflen,
                    struct servent **result);

Options/Flags

  • port: The port number to retrieve information for.
  • protocol: The transport layer protocol (e.g., TCP, UDP) to use for the lookup.
  • result_buf: A pointer to a struct servent to store the retrieved service information.
  • buf: A buffer to store the service name in.
  • buflen: The size of the buf buffer in bytes.
  • result: A pointer to a struct servent ** that will be set to the result_buf if the lookup succeeds.

Examples

Get service information for TCP port 80:

#include <netdb.h>

struct servent *serv_info;
int status;

status = getservbyport_r(htons(80), getprotobyname("tcp"),
                       serv_info, buf, buflen, &serv_info);
if (status == 0) {
    printf("Service: %s\n", serv_info->s_name);
} else {
    perror("getservbyport_r");
}

Common Issues

  • Ensure that the protocol argument is a valid transport layer protocol name (e.g., TCP, UDP).
  • Make sure the buflen is large enough to hold the service name.

Integration

getservbyport_r can be used in conjunction with other network programming functions such as socket, connect, and send. It’s particularly useful when working with various network services and handling inbound connections on specific ports.

Related Commands

  • getservbyname_r: Retrieves service information by service name.
  • getprotobynumber_r: Retrieves protocol information by protocol number.