I'm working on a client program, and I've got it connecting to the server fine when it's on my own computer (when the code is as-is seen below). The problem comes when I change the IP address in the code to my real IP and try running the client on another machine. I get the "Error initializing socket" code, and it doesn't run any further. Does anyone know how to get around this? I've been stuck here for a couple of days and couldn't find the answer through Googling.
Here's the client code:
#include <winsock2.h>
#include <windows.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <conio.h>
#include <iostream>
int main(int argv, char** argc)
{
int host_port= 1101;
char* host_name="127.0.0.1";
unsigned short wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 || ( LOBYTE( wsaData.wVersion ) != 2 ||
HIBYTE( wsaData.wVersion ) != 2 )) {
fprintf(stderr, "Could not find useable sock dll %d\n",WSAGetLastError());
return 0;
}
int hsock;
int * p_int ;
hsock = socket(AF_INET, SOCK_STREAM, 0);
if(hsock == -1){
printf("Error initializing socket %d\n",WSAGetLastError());
return 0;
}
p_int = new int;
*p_int = 1;
if( (setsockopt(hsock, SOL_SOCKET, SO_REUSEADDR, (char*)p_int, sizeof(int)) == -1 )||
(setsockopt(hsock, SOL_SOCKET, SO_KEEPALIVE, (char*)p_int, sizeof(int)) == -1 ) ){
printf("Error setting options %d\n", WSAGetLastError());
delete p_int;
return 0;
}
delete p_int;
struct sockaddr_in my_addr;
my_addr.sin_family = AF_INET ;
my_addr.sin_port = htons(host_port);
memset(&(my_addr.sin_zero), 0, 8);
my_addr.sin_addr.s_addr = inet_addr(host_name);
if( connect( hsock, (struct sockaddr*)&my_addr, sizeof(my_addr)) == SOCKET_ERROR ){
fprintf(stderr, "*Error connecting* (Socket %d)\n", WSAGetLastError());
return 0;
}
char buffer[1024];
int buffer_len = 1024;
int bytecount;
int c;
memset(buffer, '\0', buffer_len);
for(char* p=buffer ; (c=_getch())!=13 ; p++){
printf("%c", c);
*p = c;
}
if( (bytecount=send(hsock, buffer, strlen(buffer),0))==SOCKET_ERROR){
fprintf(stderr, "*Error sending data* (%d)\n", WSAGetLastError());
return 0;
}
if((bytecount = recv(hsock, buffer, buffer_len, 0))==SOCKET_ERROR){
fprintf(stderr, "*Error receiving data* (%d)\n", WSAGetLastError());
return 0;
}
printf("\nReceived string \"%s\"\n", buffer);
closesocket(hsock);
;
}