getpeername函数用于获取与某个套接字关联的外地地址,accept函数在接收连接的时候也会获取对端的地址。getsockname用于获取本端的地址。看代码。
服务端:
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <malloc.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <stdarg.h>
#include <fcntl.h>
int main()
{
int sockSrv = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addrSrv;
addrSrv.sin_family = AF_INET;
addrSrv.sin_addr.s_addr =htonl(INADDR_ANY);
addrSrv.sin_port = htons(8888);
bind(sockSrv, (const struct sockaddr *)&addrSrv, sizeof(struct sockaddr_in));
listen(sockSrv, 5);
struct sockaddr_in addrClient;
socklen_t len = sizeof(struct sockaddr_in);
int sockConn = accept(sockSrv, (struct sockaddr *)&addrClient, &len);
printf("ip=%s\n",inet_ntoa(addrClient.sin_addr));
printf("port=%d\n",ntohs(addrClient.sin_port));
getchar();
close(sockConn);
close(sockSrv);
return 0;
}
客户端:
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <malloc.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <stdarg.h>
#include <fcntl.h>
#include <error.h>
int main()
{
int ret=0;
int sockClient = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addrSrv;
addrSrv.sin_addr.s_addr=inet_addr("127.0.0.1");
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons(8888);
ret=connect(sockClient, ( const struct sockaddr *)&addrSrv, sizeof(struct sockaddr_in));
struct sockaddr_in addrClient;
socklen_t len=sizeof(addrClient);
getsockname(sockClient,(struct sockaddr *)&addrClient,&len);
printf("ip=%s\n",inet_ntoa(addrClient.sin_addr));
printf("port=%d\n",ntohs(addrClient.sin_port));
getchar();
close(sockClient);
return 0;
}
编译运行。
服务端:
[mapan@localhost TCP]$ ./server
ip=127.0.0.1
port=39914
客户端:
[mapan@localhost TCP]$ ./client
ip=127.0.0.1
port=39914
再用netstat命令查看:
[mapan@localhost ~]$ netstat -na | grep 8888
tcp 0 0 0.0.0.0:8888 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:39914 127.0.0.1:8888 ESTABLISHED
tcp 0 0 127.0.0.1:8888 127.0.0.1:39914 ESTABLISHED
结果一目了然。