1 /* 2 * Copyright 2008, Axel Dörfler, axeld@pinc-software.de. 3 * Distributed under the terms of the MIT license. 4 */ 5 6 7 #include <errno.h> 8 #include <netdb.h> 9 #include <netinet/in.h> 10 #include <stdio.h> 11 #include <stdlib.h> 12 #include <string.h> 13 #include <sys/socket.h> 14 #include <unistd.h> 15 16 17 extern const char* __progname; 18 19 20 int 21 main(int argc, char** argv) 22 { 23 if (argc < 2) { 24 printf("usage: %s <host> [port]\n" 25 "Connects to the host (default port 21, ftp), and calls\n" 26 "getpeername() to see if it works correctly with a short\n" 27 "buffer.\n", __progname); 28 return 0; 29 } 30 31 struct hostent* host = gethostbyname(argv[1]); 32 if (host == NULL) { 33 perror("gethostbyname"); 34 return 1; 35 } 36 37 uint16_t port = 21; 38 if (argc > 2) 39 port = atol(argv[2]); 40 41 int socket = ::socket(AF_INET, SOCK_STREAM, 0); 42 if (socket < 0) { 43 perror("socket"); 44 return 1; 45 } 46 47 sockaddr_in address; 48 memset(&address, 0, sizeof(sockaddr_in)); 49 50 address.sin_family = AF_INET; 51 address.sin_port = htons(port); 52 address.sin_addr = *((struct in_addr*)host->h_addr); 53 54 socklen_t length = 14; 55 sockaddr buffer; 56 int result = getpeername(socket, &buffer, &length); 57 printf("getpeername() before connect(): %d (%s), length: %d\n", result, 58 strerror(errno), length); 59 60 if (connect(socket, (sockaddr*)&address, sizeof(sockaddr_in)) < 0) { 61 perror("connect"); 62 return 1; 63 } 64 65 errno = 0; 66 length = 14; 67 result = getpeername(socket, &buffer, &length); 68 printf("getpeername() after connect(): %d (%s), length: %d\n", result, 69 strerror(errno), length); 70 71 close(socket); 72 return 0; 73 } 74 75