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

#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 <stdio.h> #include <string.h> #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 */ int alen; /* length of 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 ) { fprintf(stderr, "invalid host: %s\n", host); exit(1); } memcpy(&sad.sin_addr, ptrh->h_addr, ptrh->h_length); sad.sin_port = htons((u_short)PORT); /* use default port number */ alen = sizeof(sad); /* Map TCP transport protocol name to protocol number. */ ptrp = getprotobyname("udp"); if ( ptrp == 0) { fprintf(stderr, "cannot map \"udp\" to protocol number\n"); exit(1); } /* Create a socket. */ sd = socket(PF_INET, SOCK_DGRAM, ptrp->p_proto); if (sd < 0) { fprintf(stderr, "soclet creation failed\n"); exit(1); } { int n; /* number of characters received */ int m; /* number of characters sent back */ char buf[1000]; /* buffer for data from the server */ /* Send data to socket in order to request reply. */ m = 1; /* sned zero bytes */ m = sendto(sd,buf,m,0,(struct sockaddr*)&sad,alen); if(m<0) { fprintf(stderr,"Error in sending"); } else { /* Read data from socket and write to user's screen. */ n = recvfrom(sd,buf,sizeof(buf),0,(struct sockaddr*)&sad,&alen); if (n > 0) { buf[n]='\0'; /* just in case place the termination at the end of the string */ printf("%s", buf); } } } /* Close the socket. */ closesocket(sd); #ifdef WIN32 WSACleanup(); /* release use of winsock.dll */ #endif /* Terminate the client program gracefully. */ return(0); }