#include
int getsockname(int sockfd,struct sockaddr * localaddr,socklen_t * addrlen);
int getpeername(int connfd,struct sockaddr * peeraddr,socklen_t * addrlen);
两者均返回 : 0--成功 , -1--出错.
注意:
函数在使用时,第三个参数addrlen要指定地址结构长度。
socklen_t addrlen;
addrlen = sizeof(struct sockaddr_in);
程序代码:
#include
#include
#include
#include
#include
#include
#include
int main()
{
int sockfd,connfd;
char buff[100];
struct sockaddr_in serv,local,cli,peer;
socklen_t len,addrlen;
sockfd = socket(AF_INET,SOCK_STREAM,0);
memset(&serv,0,sizeof(serv));
memset(&local,0,sizeof(local));
memset(&peer,0,sizeof(peer));
serv.sin_family = AF_INET;
inet_pton(AF_INET,"127.0.0.1",&serv.sin_addr);
//serv.sin_addr.s_addr = INADDR_ANY;
serv.sin_port = htons(5000);
bind(sockfd,(struct sockaddr *)&serv,sizeof(serv));
inet_ntop(AF_INET,&serv.sin_addr,buff,sizeof(buff));
printf("serv.addr = %s,port=%d \n",buff,ntohs(serv.sin_port));
memset(&buff,0,sizeof(buff));
len = sizeof(struct sockaddr_in);
getsockname(sockfd,(struct sockaddr *)&local,&len);
if((inet_ntop(AF_INET,&local.sin_addr,buff,sizeof(buff)))==NULL)
printf("inet_ntop\n");
printf("local.addr = %s ,port=%d \n",buff,ntohs(local.sin_port));
listen(sockfd,14);
for(;;)
{
connfd = accept(sockfd, (struct sockaddr *)&cli,&addrlen);
printf("peer connect ...\n");
memset(buff,0,sizeof(buff));
if((getpeername(connfd,(struct sockaddr *)&peer,&len))!=0)
printf("getpeername \n");
printf("peer.addr = %s, port = %d\n",inet_ntop(AF_INET,&peer.sin_addr,buff,sizeof(buff)),ntohs(peer.sin_port));
}
return 0;
}
阅读(1115) | 评论(0) | 转发(0) |