×
Namespaces

Variants
Actions

Open C 套接字: getpeername 方法

From Nokia Developer Wiki
Jump to: navigation, search
Article Metadata

文章
dougcn 在 24 Jun 2008 创建
最后由 hamishwillee 在 15 Dec 2011 编辑

Open C 套接字: getpeername 方法

getpeername方法获取所连接的对等方套接字的名称。

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

getpeername系统调用返回已连接到套接字s的对等方的名称。namelen参数应被初始化以指出由name所指空间的总额。返回时它含

有所返回的name的实际大小(按字节)。若提供的buffer太小,那么名字将被截取。

下面的代码片段演示了getpeername方法的用法:

#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));
listen(sock_fd,1);
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);
close(newsock_fd);
close(sock_fd);
}

内部链接

Internal Links

This page was last modified on 15 December 2011, at 05:40.
92 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.

×