I wish to get the IP address of a client so that I can connect a socket for the client to send data to the server. This is the code for the server program:
Code:
#include <winsock2.h>
#include <windows.h>
#include <iostream>
using namespace std;
int main (int argc, char **argv)
{
WSADATA WsaDat;
SOCKET ServSocket, ClientSocket, TempSocket = SOCKET_ERROR;
SOCKADDR_IN ServAddr, ClientAddr;
SOCKADDR PeerAddr;
char recv_str[6];
int RetVal = SOCKET_ERROR, paddr_sz;
if (WSAStartup (MAKEWORD (1, 1), &WsaDat) != 0)
{
cout << "Error in WSAStartup!!!";
return -1;
}
ServSocket = socket(AF_INET, SOCK_STREAM, 0);
if (ServSocket == INVALID_SOCKET)
{
cout << "Error making socket!!!";
return -1;
}
ClientSocket = socket(AF_INET, SOCK_STREAM, 0);
if (ClientSocket == INVALID_SOCKET)
{
cout << "Error making client socket!!!";
return -1;
}
ServAddr.sin_port = htons(100);
ServAddr.sin_family = AF_INET;
ServAddr.sin_addr.s_addr = inet_addr("192.168.1.100");
if (bind (ServSocket, (SOCKADDR *)(&ServAddr), sizeof (ServAddr)) == SOCKET_ERROR)
{
cout << "Error binding socket!!!";
return -1;
}
listen (ServSocket, 1);
paddr_sz = sizeof(SOCKADDR);
while (TempSocket == SOCKET_ERROR)
{
TempSocket = accept (ServSocket, &PeerAddr, &paddr_sz);
}
ServSocket = TempSocket;
cout << "Made it this far!!!";
send(ServSocket, "Hello", 6, 0);
cout << inet_addr(PeerAddr.sa_data);
if (connect (ClientSocket, &PeerAddr, sizeof (PeerAddr)) != 0)
{
cout << "Error connecting to client!!!";
system ("pause");
return -1;
}
while (RetVal == SOCKET_ERROR)
{
RetVal = recv (ClientSocket, recv_str, 6, 0);
}
cout << recv_str;
system ("pause");
return 0;
}
As you can see, I'm trying to return the address in a SOCKADDR structure. I have no idea why this is going wrong. This is more or less just a project to help me learn how to program with winsock, so im not worried about checks on every problem like is port 100 always open. i know that these ports may be in use, but this is just to learn. if anyone has any advice on why i cant seem to get the IP address, please help!! Thanks in advance!!! if you need the client code, I'll be more than happy to post it!!!