#include #include #include int main(int argc, char *argv[]) { WSADATA wsaData; char *nodename; char *servname = "echo"; ADDRINFO hints; LPADDRINFO ai, ai0; int e; SOCKET s; char linebuf[BUFSIZ]; /** Process command line arguments (read the server name from the command line) */ if (argc != 2) { fprintf(stderr, "syntax: tcp-echo-client servername\n"); exit(1); } nodename = argv[1]; /** Initialize WinSock */ if (WSAStartup(MAKEWORD(2, 2), &wsaData)) { fprintf(stderr, "can not initilize WinSock\n"); exit(1); } /** Perform name resolution and create ADDRINFO list */ memset(&hints, 0, sizeof(hints)); /* IPv6/IPv4 */ hints.ai_family = AF_UNSPEC; /* Specify stream-type (TCP) socket */ hints.ai_socktype = SOCK_STREAM; /* Perform name resolution and create ADDRINFO list. ai0 is the first item of the list */ if (e = getaddrinfo(nodename, servname, &hints, &ai0)) { fprintf(stderr, "%s\n", gai_strerror(e)); exit(1); } /** Keep attempting to connect using each item in the ADDRINFO list */ /** until it connects to the server successfully. */ for (ai = ai0; ai; ai = ai->ai_next) { /* Attempt to create a socket. If this fails, */ /* attempt to connect using the next item in the ADDRINFO list. */ s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); if (s == INVALID_SOCKET) continue; /* Attempt to connect to the server. If this fails, */ /* attempt to connect using the next item in the ADDRINFO list. */ if (connect(s, ai->ai_addr, ai->ai_addrlen) == SOCKET_ERROR) { closesocket(s); s = INVALID_SOCKET; continue; } /* Since connection was successful, quit attempts to connect here. */ printf("connected\n"); break; } /** When attempts to connect using all of the ADDRINFO list items fail, */ /** the value of s is INVALID_SOCKET. */ if (s == INVALID_SOCKET) { freeaddrinfo(ai0); WSACleanup(); fprintf(stderr, "can not connect server(%s)\n", nodename); exit(1); } /** Process I/O between the client and the server. */ /** Send the character string to the server and receive a response from the server. */ while (fgets(linebuf, sizeof(linebuf), stdin) != NULL) { /* Send the character string received from the standard input to the server. */ if (send(s, linebuf, strlen(linebuf), 0) == SOCKET_ERROR) { fprintf(stderr, "send error\n"); exit(1); } /* Display the character string returned by the server. */ if (recv(s, linebuf, sizeof(linebuf), 0) == SOCKET_ERROR) { fprintf(stderr, "recv error\n"); exit(1); } printf(linebuf); } freeaddrinfo(ai0); WSACleanup(); }