Question

I'm writing a basic proxy server in C for class.

I'm testing with firefox, and I've got the server successfully receiving the browser's requests.

But now I need to send them out to the internet to get the pages the browser wants, and I'm hesitant.

Here is my present code for connecting.

I'm not sure if port 8080 is correct, and I'm not sure what to put for "gethostbyname". That's the portion I was hoping to get some advice on.

  int sock = socket( PF_INET, SOCK_STREAM, 0 );

  if ( sock < 0 )
  {
    perror( "socket() failed" );
    return EXIT_FAILURE;
  }

  struct sockaddr_in server;
  struct hostent * hp;

  server.sin_family = PF_INET;
  hp = gethostbyname( "localhost" );
  if ( hp == NULL )
  {
    perror( "Unknown host" );
    return EXIT_FAILURE;
  }

  bcopy( (char *)hp->h_addr, (char *)&server.sin_addr, hp->h_length );
  int port = 8080;
  server.sin_port = htons( port );

  if ( connect( sock, (struct sockaddr *)&server, sizeof( server ) ) < 0 )
  {
    perror( "connect() failed" );
    return EXIT_FAILURE;
  }
Was it helpful?

Solution

That entire gethostbyname, copying around (ha - even with the overly old bcopy)... just use getaddrinfo (extensive error checking left out for brevity):

int ret = getaddrinfo("localhost", "80" /* (or 8080, whichever applies) */, NULL, &res);
if (ret == 0) {
    const struct addrinfo *r;
    for (r = res; r != NULL || ret != 0; r = r->ai_next)
       ret = connect(fd, res->ai_addr, res->ai_addrlen);
}
freeaddrinfo(res);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top