Thread: connect to domain with gethostbyname

  1. #1
    Registered User
    Join Date
    Aug 2009

    connect to domain with gethostbyname

    I am using the following source code to connect to a domain. However, at runtime the printf error trap reveals that connection fails. What is so wrong?

    #include <winsock2.h>
    #include <stdio.h>
    #pragma comment(lib, "ws2_32.lib")
    int main(){
        WSADATA wsa;
        SOCKET sock;
        struct sockaddr_in info;
        char buffer[1024];
    	char *hostname="";
        if(WSAStartup(MAKEWORD(2,2), &wsa)==-1) return 0;
    	if(gethostbyname(hostname)==NULL) return 0;
        info.sin_addr.s_addr=*(LPDWORD)gethostbyname((char *)hostname)->h_addr_list[0];
    	memset(info.sin_zero, 0, 8);
        if(sock=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)==-1) return 0;
        if (connect(sock, (struct sockaddr *)&info, sizeof(info))==-1){

  2. #2
    Registered User
    Join Date
    Oct 2001
    Try to get a more detailed error message using "errno":

    #include <errno.h>
    #include <string.h>
    if (connect(....) == -1) {
      fprintf(stderr, strerror(errno));

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Non-blocking connect()?
    By pobri19 in forum Networking/Device Communication
    Replies: 9
    Last Post: 04-22-2009, 03:40 PM
  2. connect timeout
    By X PaYnE X in forum Networking/Device Communication
    Replies: 8
    Last Post: 05-14-2005, 09:30 PM
  3. Client timed-out once on connect(), can never connect() again
    By registering in forum Networking/Device Communication
    Replies: 6
    Last Post: 10-28-2003, 03:46 PM
  4. Domain Resolution :: Winsock
    By kuphryn in forum Windows Programming
    Replies: 5
    Last Post: 08-01-2002, 03:34 PM
  5. MSN Vital Information
    By iain in forum A Brief History of
    Replies: 9
    Last Post: 09-22-2001, 08:55 PM