显示客户端本机的IP地址和端口
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <string.h> const int maxline=4096; int main(int argc, char **argv) { int sockfd, n; char recvline[maxline+1], errbuff[maxline]; struct sockaddr_in servaddr, localaddr; socklen_t len=sizeof(localaddr); if(argc != 2) { fprintf(stderr, "usage: a.out <IPaddress>\n"); exit(-1); } if((sockfd=socket(AF_INET, SOCK_STREAM, 0))<0) { strerror_r(errno, errbuff, maxline); fprintf(stderr, "socket error: %s\n", errbuff); exit(-1); } memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family=AF_INET; servaddr.sin_port=htons(9999); if(inet_pton(AF_INET, argv[1], &servaddr.sin_addr)<=0) { fprintf(stderr, "inet_pton error for %s\n", argv[1]); exit(-1); } if(connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr))<0) { strerror_r(errno, errbuff, maxline); fprintf(stderr, "connect error: %s\n", errbuff); exit(-1); } if(getsockname(sockfd, (struct sockaddr *)&localaddr, &len)<0) { strerror_r(errno, errbuff, maxline); fprintf(stderr, "connect error: %s\n", errbuff); exit(-1); } printf("local ip: %s, local port: %d\n", inet_ntop(AF_INET, &localaddr.sin_addr, errbuff, sizeof(errbuff)), ntohs(localaddr.sin_port)); while((n=read(sockfd, recvline, maxline))>0) { recvline[n]=0; if(fputs(recvline, stdout)==EOF) { fprintf(stderr, "fputs error\n"); exit(-1); } } if(n<0) { fprintf(stderr, "read error.\n"); exit(-1); } return 0; }