/* An example of a TCP connection. Writes "Hello World" to the socket. This is designed for Linux, but may work on other unix-like systems. This is written in ISO C99 -- should be compiled with GCC. */ // standard C include files #include #include #include // unix header files #include // for write(), close() // BSD socket header files #include #include // resolver header files #include #include // hostname to ip address conversion functions #include int main(int argc, char **argv) { int fd, r; // fd = file descriptor (all unix systems use this // to represent sockets, files, devices, etc) // r = result returned from API functions char *hostname; // our hostname, from argv int port; // our port, from argv struct hostent *hent; // host entry, used by the resolver // (a resolver converts hostnames to IP addresses) struct sockaddr_in sin; // our socket address structure. // equivalent to SockAddress in java. char *string = "Hello World\n"; // our "Hello World" string // check parameters.. needs at least 2. if (argc < 3) { fprintf(stderr, "Syntax: \n"); exit(1); } // grab parameters from command line. hostname = argv[1]; port = atoi(argv[2]); // create a socket file descriptor -- this is not connected yet. fd = socket(AF_INET, SOCK_STREAM, 0); if (fd < 0) { perror("socket"); exit(1); } // setup our socket address structure sin.sin_family = AF_INET; sin.sin_port = htons(port); // there is a third field: // sin.sin_addr which contains an ip address field. // we use it in the resolver below. // resolve hostname to ip address // first step: IF hostname is IP ADDRESS format, then convert // using inet_aton() if (!inet_aton(hostname, &sin.sin_addr)) { // IF NOT, then do the rest: // call gethostbyname() to resolve our hostname. hent = gethostbyname(hostname); if (!hent) { perror("gethostbyname"); exit(1); } // copy our first (0th) result to our socket address // field "sin.sin_addr.saddr" memcpy(&sin.sin_addr.s_addr, hent->h_addr_list[0], sizeof(sin.sin_addr.s_addr)); } // to connect the socket, we supply: // a) file descriptor, b) socket address structure, c) size of // socket address structure. r = connect(fd, (struct sockaddr *) &sin, sizeof(sin)); if (r < 0) { perror("connect"); exit(1); } // if there were no errors, then we are connected now. printf("Connected\n"); // call unix 'write' operation write(fd, string, strlen(string)); // close file descriptor -- we are done with it. close(fd); }