[1912323] | 1 | /* UDP client in the internet domain */
|
---|
| 2 | #include <sys/types.h>
|
---|
| 3 |
|
---|
| 4 | #include <winsock2.h>
|
---|
| 5 |
|
---|
| 6 | #include <stdio.h>
|
---|
| 7 | #include <stdlib.h>
|
---|
| 8 | #include <string.h>
|
---|
| 9 |
|
---|
| 10 | #include <iostream>
|
---|
| 11 |
|
---|
| 12 | #pragma comment(lib, "ws2_32.lib")
|
---|
| 13 |
|
---|
| 14 | using namespace std;
|
---|
| 15 |
|
---|
| 16 | void error(const char *);
|
---|
| 17 | int main(int argc, char *argv[])
|
---|
| 18 | {
|
---|
| 19 | int sock, n;
|
---|
| 20 | int length;
|
---|
| 21 | struct sockaddr_in server, from;
|
---|
| 22 | struct hostent *hp;
|
---|
| 23 | char buffer[256];
|
---|
| 24 |
|
---|
| 25 | if (argc != 3) {
|
---|
| 26 | printf("Usage: server port\n");
|
---|
| 27 | exit(1);
|
---|
| 28 | }
|
---|
| 29 |
|
---|
| 30 | WORD wVersionRequested;
|
---|
| 31 | WSADATA wsaData;
|
---|
| 32 | int wsaerr;
|
---|
| 33 |
|
---|
| 34 | wVersionRequested = MAKEWORD(2, 2);
|
---|
| 35 | wsaerr = WSAStartup(wVersionRequested, &wsaData);
|
---|
| 36 |
|
---|
| 37 | if (wsaerr != 0) {
|
---|
| 38 | printf("The Winsock dll not found.\n");
|
---|
| 39 | exit(1);
|
---|
| 40 | }else
|
---|
| 41 | printf("The Winsock dll was found.\n");
|
---|
| 42 |
|
---|
| 43 | sock= socket(AF_INET, SOCK_DGRAM, 0);
|
---|
| 44 | if (sock < 0) error("socket");
|
---|
| 45 |
|
---|
| 46 | server.sin_family = AF_INET;
|
---|
| 47 | hp = gethostbyname(argv[1]);
|
---|
| 48 | if (hp==0) error("Unknown host");
|
---|
| 49 |
|
---|
| 50 | memcpy((char *)&server.sin_addr,
|
---|
| 51 | (char *)hp->h_addr,
|
---|
| 52 | hp->h_length);
|
---|
| 53 | server.sin_port = htons(atoi(argv[2]));
|
---|
| 54 | length=sizeof(struct sockaddr_in);
|
---|
| 55 | printf("Please enter the message: ");
|
---|
| 56 | memset(buffer, 0, 256);
|
---|
| 57 | fgets(buffer,255,stdin);
|
---|
| 58 | n=sendto(sock,buffer,
|
---|
| 59 | strlen(buffer),0,(const struct sockaddr *)&server,length);
|
---|
| 60 | if (n < 0) error("Sendto");
|
---|
| 61 | n = recvfrom(sock,buffer,256,0,(struct sockaddr *)&from, &length);
|
---|
| 62 | if (n < 0) error("recvfrom");
|
---|
| 63 |
|
---|
| 64 | buffer[n] = '\0';
|
---|
| 65 | cout << "Got an ack: " << endl;
|
---|
| 66 | cout << buffer << endl;
|
---|
| 67 |
|
---|
| 68 | closesocket(sock);
|
---|
| 69 |
|
---|
| 70 | WSACleanup();
|
---|
| 71 |
|
---|
| 72 | return 0;
|
---|
| 73 | }
|
---|
| 74 |
|
---|
| 75 | void error(const char *msg)
|
---|
| 76 | {
|
---|
| 77 | perror(msg);
|
---|
| 78 | WSACleanup();
|
---|
| 79 | exit(1);
|
---|
| 80 | } |
---|