/* * code for example client program that uses TCP * */

#ifndef unix #include <winsock2.h> /* also include Ws2_32.lib library in linking options */ #else #define closesocket close #define SOCKET int #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <unistd.h> /* also include xnet library for linking; on command line add: -lxnet */ #endif #include <iostream> #include <cstring> using namespace std; #define PORT 1200 /* default protocol port number */ char localhost[] = "localhost"; /* default host name */ /*------------------------------------------------------------------------ * Program: client * * Purpose: allocate a socket, connect to a server, and print all output * *------------------------------------------------------------------------ */ int main() { struct hostent *ptrh; /* pointer to a host table entry */ struct protoent *ptrp; /* pointer to a protocol table entry */ struct sockaddr_in sad; /* structure to hold an IP address */ SOCKET sd; /* socket descriptor - integer */ char host[256]; /* pointer to host name */ #ifdef WIN32 WSADATA wsaData; if(WSAStartup(0x0101, &wsaData)!=0) { fprintf(stderr, "Windows Socket Init failed: %d\n", GetLastError()); exit(1); } #endif memset((char *)&sad,0,sizeof(sad)); /* clear sockaddr structure */ sad.sin_family = AF_INET; /* set family to Internet */ strcpy(host,localhost); // host=localhost /* Convert host name to equivalent IP address and copy to sad. */ ptrh = gethostbyname(host); if ( ((char *)ptrh) == NULL ) { cerr << "invalid host: " << host << endl; exit(1); } memcpy(&sad.sin_addr, ptrh->h_addr, ptrh->h_length); sad.sin_port = htons((u_short)PORT); /* use default port number */ /* Map TCP transport protocol name to protocol number. */ ptrp = getprotobyname("tcp"); if ( ptrp == 0) { cerr << "cannot map \"tcp\" to protocol number" << endl; exit(1); } /* Create a socket. */ sd = socket(PF_INET, SOCK_STREAM, ptrp->p_proto); if (sd < 0) { cerr << "soclet creation failed" << endl; exit(1); } /* Connect the socket to the specified server. */ if (connect(sd, (struct sockaddr *)&sad, sizeof(sad)) < 0) { cerr << "connection failed" << endl; exit(1); } { int n; /* number of characters read */ char buf[1000]; /* buffer for data from the server */ /* Repeatedly read data from socket and write to user's screen. */ n = recv(sd, buf, sizeof(buf), 0); while (n > 0) { cout.write(buf, n); n = recv(sd, buf, sizeof(buf), 0); } } /* Close the socket. */ closesocket(sd); #ifdef WIN32 WSACleanup(); /* releaseuse of winsock.dll */ #endif /* Terminate the client program gracefully. */ return(0); }