// // File: // // simple network functions, largely take from the vb source code // should be merged with fobbit vb source so have only one set // // Written by: David M. Stanhope // // --------------------------------------------------------------------------- // if port present as part of the address, remove it from the address // and return the port, otherwise leave name alone and return default port static int scan_address(char *address, int default_port) { char *s; if((s = strchr(address, ':')) != NULL) // scan off port if present { *s++ = '\0'; return atoi(s); } else { return default_port; } } // --------------------------------------------------------------------------- void init_address(int port, struct sockaddr_in *pa) { memset((char *) pa, 0, sizeof(struct sockaddr_in)); #ifndef IS_WINDOWS pa->sin_len = sizeof(struct sockaddr_in); #endif pa->sin_family = AF_INET ; pa->sin_port = htons((u_short) port) ; } // --------------------------------------------------------------------------- // given a host name, and a port, build an address structure for it, // after calling the resolver, also overrides the passed port if port // specifed as part of the name int resolve_address(char *name, int port, struct sockaddr_in *pa) { struct hostent *hp; init_address(port, pa); if(isdigit((u_char) name[0])) { if(inet_aton(name, &(pa->sin_addr)) == 0) { ERR(("resolve_address: bogus ip(%s)\n", name)) return -1; } } else { if((hp = gethostbyname(name)) == NULL) { ERR(("resolve_address: unknown host(%s)\n", name)) return -1; } if(hp->h_addrtype != AF_INET) { ERR(("resolve_address: not an internet address(%s)\n", name)) return -1; } if(hp->h_length > sizeof(pa->sin_addr)) hp->h_length = sizeof(pa->sin_addr); memcpy(&(pa->sin_addr), hp->h_addr, hp->h_length); } MSG2(("resolve_address: (%s) is (%s)\n", name, inet_ntoa(pa->sin_addr))) return 0; } // --------------------------------------------------------------------------- SOCKET Connect_TCP(char *name, int port) { SOCKET fd; struct sockaddr_in server; port = scan_address(name, port); // see if port specified in address if(resolve_address(name, port, &server) != 0) { ERR(("Can't resolve (%s)\n", name)) return -1; } if((fd = socket(PF_INET, SOCK_STREAM, 0)) < 0) { ERR(("socket(%s) failed, error(%s)\n", name, Socket_Error())) return -1; } if(connect(fd, (struct sockaddr *) &server, sizeof(server)) < 0) { ERR(("connect() failed, error(%s)\n", Socket_Error())) close(fd); return -1; } return fd; } // --------------------------------------------------------------------------- // // The End! //