getsockname和getpeername
#include <sys/socket.h>
int getsockname(int sockfd, struct sockaddr *localaddr, socklen_t *addrlen);
int getpeername(int sockfd, struct sockaddr *peeraddr, socklen_t *addrlen);
返回:0—OK,-1—出错。
getsockname函数返回与套接口关联的本地协议地址。
getpeername函数返回与套接口关联的远程协议地址。
addrlen是值-结果参数。
使用场合:
- 在不调用bind的TCP客户,当connect成功返回后,getsockname返回分配给此连接的本地IP地址和本地端口号;
- 在以端口号为0调用bind后,使用getsockname返回内核分配的本地端口号;
- getsockname可用来获取某套接口的地址族;
- 在捆绑了通配IP地址的TCP服务器上,当连接建立后,可以使用getsockname获得分配给此连接的本地IP地址;
- 当一个服务器调用exec启动后,他获得客户身份的唯一途径是调用getpeername函数。
服务器端源码:
#include "unp.h" int main(int argc, char ** argv) { int listenfd,connfd; struct sockaddr_in servaddr; pid_t pid; char temp[20]; listenfd = Socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(10010); Bind(listenfd, (SA *)&servaddr, sizeof(servaddr)); Listen(listenfd, LISTENQ); for( ; ; ) { struct sockaddr_in local; connfd = Accept(listenfd, (SA *)NULL, NULL); if((pid = fork()) == 0) { Close(listenfd);struct sockaddr_in serv, guest; char serv_ip[20]; char guest_ip[20]; socklen_t serv_len = sizeof(serv); socklen_t guest_len = sizeof(guest); getsockname(connfd, (struct sockaddr *)&serv, &serv_len); getpeername(connfd, (struct sockaddr *)&guest, &guest_len); Inet_ntop(AF_INET, &serv.sin_addr, serv_ip, sizeof(serv_ip)); Inet_ntop(AF_INET, &guest.sin_addr, guest_ip, sizeof(guest_ip)); printf("host %s:%d guest %s:%d ", serv_ip, ntohs(serv.sin_port), guest_ip, ntohs(guest.sin_port)); char buf[] = "hello world"; Write(connfd, buf, strlen(buf)); Close(connfd); exit(0); } Close(connfd); } }
客户端源码:
1 #include "unp.h" 2 #define DEST_IP "127.0.0.1" 3 4 int 5 main(int argc, char ** argv) 6 { 7 int sockfd, n; 8 char buf[100]; 9 char serv_ip[20], guest_ip[20]; 10 struct sockaddr_in servaddr; 11 12 sockfd = Socket(AF_INET, SOCK_STREAM, 0); 13 bzero(&servaddr, sizeof(struct sockaddr_in)); 14 servaddr.sin_family = AF_INET; 15 servaddr.sin_port = htons(10010); 16 17 Inet_pton(AF_INET, DEST_IP, &servaddr.sin_addr); 18 Connect(sockfd, (SA *)&servaddr, sizeof(servaddr)); 19 20 struct sockaddr_in serv, guest; 21 socklen_t serv_len = sizeof(serv); 22 socklen_t guest_len = sizeof(guest); 23 24 getsockname(sockfd, (SA *)&guest, &guest_len); 25 getpeername(sockfd, (SA *)&serv, &serv_len); 26 27 Inet_ntop(AF_INET, &guest.sin_addr, guest_ip, sizeof(guest_ip)); 28 Inet_ntop(AF_INET, &serv.sin_addr, serv_ip, sizeof(serv_ip)); 29 30 printf("host %s:%d, guest %s:%d ", serv_ip, ntohs(serv.sin_port), guest_ip, ntohs(guest.sin_port)); 31 32 n = Read(sockfd, buf, 100); 33 buf[n] = '