|
源程序guest.c
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int main(int argc, char *argv[])
{
int sockfd;
struct sockaddr_in seraddr;
struct sockaddr_in localaddr;
socklen_t locallen;
char ip[1024];
sockfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&seraddr, 0);
bzero(&localaddr, 0);
seraddr.sin_family = AF_INET;
seraddr.sin_port = htons(4000);
inet_pton(AF_INET,
argv[1],
&seraddr.sin_addr);
connect(sockfd,
(struct sockaddr *)&seraddr,
sizeof(seraddr));
locallen = sizeof(localaddr);
getsockname(sockfd,
(struct sockaddr *)&localaddr,
&locallen);
printf("local ip : %s\n"
"local port: %d\n",
inet_ntop(AF_INET, (struct sockaddr *)&localaddr, ip, sizeof(ip)),
ntohs(localaddr.sin_port));
close(sockfd);
exit(0);
}
程序输出的结果不正确啊, 如果写一个服务器程序,调用getpeername能够等到客户端的ip地址和端口,但调用getsockname同样结果不正确
是不是我的getsockname用法错了! |
|