I'm new to socket programming. I'm making a client side socket in C++, and my friend is making a server side socket (also in C++), and our goal is to make a chat application together. Being new to socket programming, I was searching the internet on C++ socket and related, and I gathered enough information to make a socket and send something to another socket. The problem is with the send
and connect
functions. I don't really understand what parameters I should have in them, and how to initialize those. I'm hoping somebody with more experience can explain how they work, and what values to use as parameters. This is the code sample MSDN has. I hope someone helps! Regardless, thanks!
int send(
_In_ SOCKET s,
_In_ const char *buf,
_In_ int len,
_In_ int flags
);
int connect(
_In_ SOCKET s,
_In_ const struct sockaddr *name,
_In_ int namelen
);
I already know how to create a socket, so I know what goes in the first parameter; it's the socket.
EDIT 2:
These are the modules I use; I'm not sure if they are the ones I should use; I just copied them from a C++ socket example i saw online.
#include<iostream> //cout
#include<stdio.h> //printf
#include<string.h> //strlen
#include<string> //string
#include<sys/socket.h> //socket
#include<arpa/inet.h> //inet_addr
#include<netdb.h> //hostent
One more thing — I'm using a UDP protocol. Not sure if that will affect anything, tho!
Here is a bare minimum socket client for Windows. It connects to Google and makes a GET request and dumps the result. YMMV.
#include <winsock2.h>
#include <WS2tcpip.h>
int ResolveHostName(const char* pszHostName, sockaddr_in* pAddr)
{
int ret;
HRESULT hr = S_OK;
addrinfo* pResultList = NULL;
addrinfo hints = {};
int result = -1;
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
ret = getaddrinfo(pszHostName, NULL, &hints, &pResultList);
result = (ret == 0) ? 1 : -1;
if (result != -1)
{
// just pick the first one found
*pAddr = *(sockaddr_in*)(pResultList->ai_addr);
result = 0;
}
if (pResultList != NULL)
{
::freeaddrinfo(pResultList);
}
return result;
}
int main()
{
SOCKET sock = -1;
WSADATA data = {};
sockaddr_in addrRemote = {};
int result;
WSAStartup(MAKEWORD(2, 2), &data);
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock != -1)
{
if (ResolveHostName("www.google.com", &addrRemote) != -1)
{
addrRemote.sin_port = htons(80);
result = connect(sock, (sockaddr*)&addrRemote, sizeof(addrRemote));
if (result != -1)
{
char* msg = "GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n";
int msg_len = strlen(msg);
result = send(sock, msg, msg_len, 0);
if (result != -1)
{
char szBuffer[10000+1];
result = recv(sock, szBuffer, 10000, 0);
if (result > 0)
{
// safely null terminate
szBuffer[result] = '\0';
printf("%s\n", szBuffer);
}
}
}
}
}
if (sock != -1)
{
closesocket(sock);
sock = -1;
}
return 0;
}