Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

Open C Sockets: getpeername method

From Wiki
Jump to: navigation, search
Article Metadata
Created: polaka_sr (17 Jun 2008)
Last edited: hamishwillee (08 Feb 2012)

The getpeername method gets name of connected peer socket.

int getpeername (int s, struct sockaddr * restrict name, socklen_t * restrict namelen);

The getpeername system call returns the name of the peer connected to socket s. The namelen argument should be initialized to indicate the amount of space pointed to by name. On return it contains the actual size of the name returned (in bytes). The name is truncated if the buffer provided is too small.

Following code snippet shows the usage of getpeername method:

#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
void GetSockName()
int sock_fd;
int newsock_fd;
struct sockaddr_in addr;
struct sockaddr_in ss;
struct sockaddr_in new_socket;
unsigned int len;
unsigned int addr_len;
sock_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(5000);
bind(sock_fd,(struct sockaddr*)&addr,sizeof(addr));
newsock_fd = accept(sock_fd,(struct sockaddr*)&new_socket,&addr_len); // Code blocks here
// Assuming client has connected to the server.
len = sizeof(ss);
getpeername(sock_fd,(struct sockaddr*)&ss,&len);

Wiki Links

Open C Sockets Overview

This page was last modified on 8 February 2012, at 02:42.
71 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.


Thank you!

We appreciate your feedback.