/* * Example of client using UDP protocol. */ #include "inet.h" #include #include #include int main(int argc, char *argv[]) { int sockfd; struct sockaddr_in serv_addr, cli_addr; struct hostent *hp; void dg_cli(FILE *, int, struct sockaddr *, int ); if (argc != 2) { cerr << "usage : " << argv[0] << " remote_host " << endl; exit(1); } /* * Get server's information */ hp = gethostbyname(argv[1]); bzero((char *)&serv_addr, sizeof(serv_addr)); bcopy(hp->h_addr, (char *)&serv_addr.sin_addr, hp->h_length); serv_addr.sin_port = htons(SERV_UDP_PORT); serv_addr.sin_family = hp->h_addrtype; // strcpy(serv_addr.sin_zero,argv[1]); /* * Open a UDP socket (an Internet datagram socket) */ if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) err_dump("client: can't open datagram socket"); /* * Bind any local address for us */ bzero((char *)&cli_addr, sizeof(cli_addr)); cli_addr.sin_family = AF_INET; cli_addr.sin_addr.s_addr = htonl(INADDR_ANY); /* port 0 allows the system to assign any available port */ cli_addr.sin_port = htons(0); /* cli_addr.sin_port = htons(3000); */ if (bind(sockfd, (struct sockaddr *)&cli_addr, sizeof(cli_addr)) < 0) err_dump("client: can't bind local address"); dg_cli(stdin, sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)); close(sockfd); return 0; } /* * Read the contents of the FILE *fp, write each line to the datagram * socket, then read a line back from the datagram socket and write it to the * standard output. * */ #define MAXLINE 50000 void dg_cli(FILE *fp, int sockfd, struct sockaddr *pserv_addr, int servlen) { int n; int maxservlen; char sendline[MAXLINE], recvline[MAXLINE+1]; int fd; fd = creat("new.dat", 0644); // while (fgets(sendline,MAXLINE,fp) != NULL) while ((n = read(0, sendline, MAXLINE)) > 0) { // n = strlen(sendline); if (sendto(sockfd, sendline, n, 0, pserv_addr, servlen) != n) err_dump("dg_cli: sendto error on socket"); /* * Now read a message from the socket and write to * standard output. */ maxservlen = servlen; n = recvfrom(sockfd, recvline, MAXLINE, 0, pserv_addr, (socklen_t*)&maxservlen); if (n < 0) err_dump("dg_cli: recvfrom error"); recvline[n] = 0; /* null terminate */ printf("%d === %s\n bytes received.", n, recvline); write(fd, recvline, n); // fputs(recvline,stdout); } close(fd); if (ferror(fp)) err_dump("dg_cli: error reading file"); }