Quote Originally Posted by oods1 View Post
How do I send data to an IP address?
Just in case you are still interested, or somebody else stumbles over this thread, here is source code that sends data to the host "hamster-nuc" on port 1234. The comments should be enough to know exactly what is going on.

Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <memory.h>
// Socket related headers
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>


char message[] = "Hello Server\r\n";


int main(int argc, char *argv[]) {
   int s; // The socket
   struct hostent *server;
   struct sockaddr_in server_addr;


   /* Create a socket to use for the connection */
   printf("Creating a socket...\n");
   s = socket(AF_INET, SOCK_STREAM,0);
   if(s == -1) {
      perror("socket()");
      exit(1);
   }


   /* Look up the server name to get the IP address */
   printf("Resolving server\n");
   server = gethostbyname("hamster-nuc");
   if(server == NULL) {
      herror("gethostbyname()");  // Note herror() not perror()
      exit(1);
   }


   /* Set up the memory structure that is used to conenct the socket */
   memset(&server_addr,0,sizeof(server_addr));  // Empty it out
   server_addr.sin_family = AF_INET;
   server_addr.sin_port   = htons(1234);
   server_addr.sin_addr = *((struct in_addr *)server->h_addr); // Copy the resolved address


   /* Connecting socket to remote machine */
   printf("Connecting to server\n");
   if(connect(s, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1 ) {
      perror("connect()");
      exit(1);
   }


   printf("Socket connected - you can read or write from it now\n");


   /* Writing data to the socket */
   printf("Writing data\n");
   size_t wrote = write(s, message,sizeof(message)-1);
   if(wrote == -1) {
      // Note there are some errors that are retryable, and
      // you should not just exit() as I have done here
      perror("write()");
      exit(1);
   }


   /* closing the socket */
   printf("Closing socket\n");
   close(s);
   return 0;
}
[/code]