A piece of a really working program. Call: int sock = Connect ("host: port");
Host can be by name or by type 10.1.3.122
Includs are actually a bit much, probably many are not needed for this piece.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/time.h> #include <unistd.h> #include <fcntl.h> #include <ctype.h> #include <errno.h> #ifdef WIN32 // gcc ... -lws2_32 -lwsock32 #include <winsock2.h> #include <ws2tcpip.h> #include <windows.h> #else #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #endif #ifdef WIN32 void Clean_tcp () { while (WSACleanup() == 0); } #endif static int cleanup = 0; int Connect (char *addr) { char *port, host[100]; struct sockaddr_in sin; struct hostent *h; short p; int conn; if (!cleanup) { #ifdef WIN32 WSADATA wsaData; WSAStartup (MAKEWORD(2,2),&wsaData); atexit (Clean_tcp); #endif cleanup = 1; } strncpy (host,addr,99); host[99] = 0; if (!(port = strchr(host,':'))) return -1; *port++ = 0; conn = socket ( AF_INET, SOCK_STREAM , 0 ); if ( conn < 0 ) { perror("socket"); exit (1); } memset ((char *)&sin,0,sizeof(sin)); sin.sin_family = AF_INET; if (!host[0]) sin.sin_addr.s_addr = inet_addr("127.0.0.1"); else { if ((sin.sin_addr.s_addr = inet_addr(host)) == -1) { errno = 0; if (h = gethostbyname(host)) memcpy((char *)&sin.sin_addr.s_addr,h->h_addr,h->h_length); else { if (errno) perror ("gethostbyname"); else fprintf (stderr,"Unknown host: [%s]\n",host); Err:; close (conn); return -1; } } } sin.sin_port = htons ( p = atoi(port) ); /* printf ("Ready to connect: %x:%d socket = %d (%s)\n", sin.sin_addr.s_addr,sin.sin_port,conn,inet_ntoa(sin.sin_addr)); */ if (connect(conn,(struct sockaddr *)&sin,sizeof(sin)) < 0) return -1; return conn; }
TIRED FORMAT