CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Nov 2006
    Posts
    292

    Winsock connect to IP

    Hi all, I've searched for this answer only to find that other people have been asking the same question but with little or no answers. I have a socket function that I want to connect to a server by IP with out the use of gethostbyname(). Can anyone point me to a tutorial or some documentation that Google couldn't find when I was searching? Or just give me some starter suggestions? Thanx.

  2. #2
    Join Date
    Feb 2005
    Posts
    2,160

    Re: Winsock connect to IP

    Something like this?:

    Code:
      SOCKET sock;
      unsigned long ip_addr;
      struct sockaddr_in client;
    
      ip_addr=inet_addr("192.168.1.10");
      memcpy(&client.sin_addr,&ip_addr,sizeof(ip_addr));
      client.sin_port=htons(10010);
      sock=socket(AF_INET,SOCK_STREAM,0);
      connect(sock,(struct sockaddr *)&client,sizeof(client));

  3. #3
    Join Date
    Oct 2010
    Posts
    68

    Re: Winsock connect to IP

    Check out MSDN.

    There is some great information here. It is tough to get through at first because there is a lot of jargon. But once you start to learn the terms it makes sense.

    Hope this helps!

  4. #4
    Join Date
    Oct 2010
    Posts
    68

    Re: Winsock connect to IP

    Anyways, here is how I do it:

    Code:
    SOCKET hSocket;
    int iResult = 0;
    char ipaddress[18] = {NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL};
    int pnum = 0;
    //user input here or set values for ipaddress and pnum
    
    
    
    
    hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    
    sockaddr_in sockAddr1;
    
    sockAddr1.sin_family = AF_INET;
    
    sockAddr1.sin_port = htons(pnum);
    
    sockAddr1.sin_addr.S_un.S_addr = inet_addr((const char*)ipaddress);
    
    iResult=connect( hSocket, (SOCKADDR*) &sockAddr1, (int) sizeof(sockAddr1));


    Yes, I use a char array, so what?! It works for me...
    Last edited by Austin.Soucy; February 8th, 2011 at 10:35 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured