Click here to Skip to main content
12,953,230 members (47,752 online)
Rate this:
Please Sign up or sign in to vote.
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)
    //The port and address you want to connect to
    int host_port= 1101;
    char* host_name=""; // here's where I'm putting my IP address and trying to connect
    // Initialize socket support WINDOWS ONLY!
    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;
    // Initialize sockets and set any options
    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;
   //Connect to the server
   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;
   // Now let's do the client related stuff
   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);
Posted 5-May-12 7:14am
enhzflep 5-May-12 14:13pm
Just had a quick look - If I consider only the part of the code before it fails, I can see just a couple of small differences.

1) I'm starting up the WSA system with version 0x101 (you used 0x202)
2) Where you have: hsock = socket(AF_INET, SOCK_STREAM, 0); I have the same, though the 0 is replaced with IPPROTO_TCP (I understand this to likely be a conscious choice)

Here's the whole function I use to establish a connection, if it's of any use.

// return the socket number for a TCP connection
SOCKET connectToServer(char *szServerName, WORD portNum)
struct hostent *hp;
unsigned int addr;
struct sockaddr_in server;
SOCKET conn;

if (conn == INVALID_SOCKET)
return NULL;


return NULL;

server.sin_addr.s_addr=*((unsigned long*)hp->h_addr);
if(connect(conn,(struct sockaddr*)&server,sizeof(server)))
return NULL;
return conn;
Code-o-mat 5-May-12 14:35pm
Might help if you also tell us what the last error code was.
Pikky86 5-May-12 14:43pm
There is no error code since it compiles fine. The only error is that it won't connect to the server when I actually try using the client.
Code-o-mat 5-May-12 14:51pm
You said you get "Error initializing socket", so this means, this code runs:

printf("Error initializing socket %d\n",WSAGetLastError());

See the call to WSAGetLastError() in there? I'm talking about what that returns. What's the number you get after the text "Error initializing socket"?
Pikky86 5-May-12 15:31pm
Oh sorry I misunderstood. The error I get for
if( connect( hsock, (struct sockaddr*)&my_addr, sizeof(my_addr)) == SOCKET_ERROR ){
fprintf(stderr, "*Error connecting* (Socket %d)\n", WSAGetLastError());

is '10061'
Code-o-mat 5-May-12 15:36pm
If you check that code out here:
you can see this:

10061 (0x274D)
No connection could be made because the target machine actively refused it.

So i'd say, you have some firewall disallowing the connection.
Code-o-mat 5-May-12 15:39pm
Another thing, your question says "can't connect on different networks", if your two computers are on different subnets -if that should be the case- then they won't be able to connect. Am no network expert but i think you either need to use an "external IP" for that or somekinf of tunneling/bridging.
Pikky86 5-May-12 15:55pm
Oh, if it's a firewall, then that's something I think I can handle without any programming. I'll also look up external IP and see if it's something I can do too. I didn't think to look up the meaning of that error, I just assumed it was some problem with the port (is the port ok at 1101 by the way?). Thanks a lot for helping with that.
Code-o-mat 5-May-12 16:34pm
By external IP i mean the IP you get from your ISP. The port is fine if nothing else tries to use the same.
Pikky86 5-May-12 17:10pm
Oh thanks again. That helps.
michaelmel 6-May-12 23:57pm
Have you even tried to ping your "external" IP address? But then again, ICMPs are often blocked these days.Sounds like a firewall problem to me as well.

As Code-o-mat alluded to, if your client is attempting to connect to a server that has a private IP address and sits behind a router you generally cannot do it without tricks.

For example, if I have a subnet 192.168.x.x at home and if I want to run a server, the external client needs to attempt a connection to an IP address of my router (which is a routable public address that your ISP provides), not the server PC directly. Inside the router you can set up "port forwarding" which means all traffic sent to a particular port will be redirected to an internal IP address (e.g. your server with 192.168.x.x something address). Hope this is relevant.
Pikky86 7-May-12 1:11am
I think it's relevant, and that's a good idea.
Today I used wireless tethering through my laptop and ran the server, and when I did that it let me connect to itself (I connected on my laptop to the server, then ran the client on the same laptop on the same network); but when I tried another computer to my server (now no longer under my house's firewall) it didn't go through. I'm guessing that the other computer I tried must've been blocking it as well (seems many computers block IP these days), so I'll try a couple more different computers and see if I can't make it work.
Pikky86 7-May-12 1:13am
I am able to ping my own external IP though, but if I set the client to try and connect to that IP address, it'll never connect. The only time I've got a connection is when I used to my own machine.
michaelmel 7-May-12 3:28am
A logical thing to do would be to get it to work first on 2 computers (clien and server) that are on the same subnet. I get an impression that the only time this software works is when you use a loopback address e.g. both client and server run on the same PC (or may be I misunderstood).

When this part is working, you can try setting port forwarding on the router -e.g. open one port number and map it to your server's private IP address. If set correctly, remote clients will be able to connect to your server running on your private subnet. Well, at least until your ISP decides to change your IP address :)
Pikky86 7-May-12 3:43am
Yes, you're right. It works when I leave it on my own computer, with the IP at, or with the IP of my cell phone's wireless tether, but as soon as I put it on a second computer it won't connect to the server. I tried port forwarding once but I couldn't get it to work, but I'll try it again as you suggested.
JackDingler 7-May-12 11:40am
According to the error, you're just trying to initialize your socket.

You're not even attempting to use the host address yet, so most of the advice above doesn't fit the error code.

Are you sure you gave us the right error code?

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

I solved the problem by downloading the Portforward Static IP program, and changed my dynamic IP to a static IP (I also did port forwarding on my router, and left the IP in my code at my regular, home IP address), and everything works! I tried connecting with another computer and it's fine now. Woohoo!
JackDingler 7-May-12 11:41am
So your issue, is with NAT then. Are you sure you gave us the right error string?
michaelmel 7-May-12 20:00pm
Yes it probably was the right code - router without port forwarding would refuse connection on a requested port - error code sounds about right.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

    Print Answers RSS
Top Experts
Last 24hrsThis month
OriginalGriff 6,429
CHill60 3,490
Maciej Los 3,103
Jochen Arndt 1,975
ppolymorphe 1,920

Advertise | Privacy | Mobile
Web02 | 2.8.170525.1 | Last Updated 7 May 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100