1 #include"winsock2.h"
2 #include 3 #include 4 using namespace std;
5 //This line is very important
6
7 #pragma comment(lib,"ws2_32.lib")
8 int main(int argc, char **argv)
9 {
10 WSADATA wsaData;
11 SOCKET SendingSocket;
12 SOCKADDR_IN ReceiverAddr;
13 int Port = 5150;
14 int Ret;
15
16 if (argc 1)
17 {
18 cout"USAGE: udpclient .\n";
19 return -1;
20 }
21
22 // Initialize Winsock version 2.2
23
24 if ((Ret = WSAStartup(MAKEWORD(2,2), &wsaData)) != 0)
25 {
26 cout"WSAStartup failed with error "endl;
27 return -1;
28 }
29
30 // Create a new socket to make a client connection.
31
32 SendingSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);//Note the difference with TCP
33 if (INVALID_SOCKET == SendingSocket)
34 {
35 cout "socket failed with error " endl;
36 WSACleanup();
37 return -1;
38 }
39
40 ReceiverAddr.sin_family = AF_INET;
41 ReceiverAddr.sin_port = htons(Port);
42 ReceiverAddr.sin_addr.s_addr = inet_addr(argv[1]);
43
44 // Make a connection to the server with socket s.
45
46 cout"We are trying to connect to " inet_ntoa(ReceiverAddr.sin_addr)
47 ":" "...\n";
48
49 cout "We will now try to send a hello message.\n";
50
51 if ((Ret = sendto(SendingSocket, "Hello", 5, 0, (SOCKADDR *)&ReceiverAddr,sizeof(ReceiverAddr))) == SOCKET_ERROR)
52 {
53 cout "Sendto failed with error " endl;
54 closesocket(SendingSocket);
55 WSACleanup();
56 return -1;
57 }
58
59 cout "We successfully sent " " byte(s).\n";
60
61 // When you are finished sending and receiving data on socket s,
62 // you should close the socket.
63
64 cout "We are closing the connection.\n";
65
66 closesocket(SendingSocket);
67
68 // When your application is finished handling the connection, call
69 // WSACleanup.
70
71 WSACleanup();
72 return 0;
73 }