1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <stdio.h> #include <unistd.h> #include <assert.h> #include <string.h> #include <arpa/inet.h>
int main(int argc, char *argv[]) { char* host = "localhost.localdomain"; struct hostent* hostinfo = gethostbyname(host);
#if 1 struct in_addr addr; addr.s_addr = inet_addr("10.12.129.189");
hostinfo = gethostbyaddr(&addr, 4, AF_INET); #else hostinfo = gethostbyname(host); #endif
assert(hostinfo); struct servent* servinfo = getservbyname("daytime", "tcp"); assert(servinfo); printf("daytime port is %d\n", ntohs(servinfo->s_port));
struct sockaddr_in address = { 0 }; address.sin_family = AF_INET; address.sin_port = servinfo->s_port; address.sin_addr = *(struct in_addr*)*hostinfo->h_addr_list;
int sockfd = socket(AF_INET, SOCK_STREAM, 0); int result = connect(sockfd, (struct sockaddr*)&address, sizeof(address)); assert(result != -1);
char buffer[128] = { 0 }; result = read(sockfd, buffer, sizeof(buffer)); assert(result > 0); buffer[result] = '\0'; printf("the day tiem is: %s", buffer); close(sockfd); return 0; }
|